1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// 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 #include "clang/Driver/Driver.h" 10 #include "ToolChains/AIX.h" 11 #include "ToolChains/AMDGPU.h" 12 #include "ToolChains/AMDGPUOpenMP.h" 13 #include "ToolChains/AVR.h" 14 #include "ToolChains/Arch/RISCV.h" 15 #include "ToolChains/BareMetal.h" 16 #include "ToolChains/CSKYToolChain.h" 17 #include "ToolChains/Clang.h" 18 #include "ToolChains/CrossWindows.h" 19 #include "ToolChains/Cuda.h" 20 #include "ToolChains/Darwin.h" 21 #include "ToolChains/DragonFly.h" 22 #include "ToolChains/FreeBSD.h" 23 #include "ToolChains/Fuchsia.h" 24 #include "ToolChains/Gnu.h" 25 #include "ToolChains/HIPAMD.h" 26 #include "ToolChains/HIPSPV.h" 27 #include "ToolChains/HLSL.h" 28 #include "ToolChains/Haiku.h" 29 #include "ToolChains/Hexagon.h" 30 #include "ToolChains/Hurd.h" 31 #include "ToolChains/Lanai.h" 32 #include "ToolChains/Linux.h" 33 #include "ToolChains/MSP430.h" 34 #include "ToolChains/MSVC.h" 35 #include "ToolChains/MinGW.h" 36 #include "ToolChains/MipsLinux.h" 37 #include "ToolChains/NaCl.h" 38 #include "ToolChains/NetBSD.h" 39 #include "ToolChains/OHOS.h" 40 #include "ToolChains/OpenBSD.h" 41 #include "ToolChains/PPCFreeBSD.h" 42 #include "ToolChains/PPCLinux.h" 43 #include "ToolChains/PS4CPU.h" 44 #include "ToolChains/RISCVToolchain.h" 45 #include "ToolChains/SPIRV.h" 46 #include "ToolChains/Solaris.h" 47 #include "ToolChains/TCE.h" 48 #include "ToolChains/VEToolchain.h" 49 #include "ToolChains/WebAssembly.h" 50 #include "ToolChains/XCore.h" 51 #include "ToolChains/ZOS.h" 52 #include "clang/Basic/TargetID.h" 53 #include "clang/Basic/Version.h" 54 #include "clang/Config/config.h" 55 #include "clang/Driver/Action.h" 56 #include "clang/Driver/Compilation.h" 57 #include "clang/Driver/DriverDiagnostic.h" 58 #include "clang/Driver/InputInfo.h" 59 #include "clang/Driver/Job.h" 60 #include "clang/Driver/Options.h" 61 #include "clang/Driver/Phases.h" 62 #include "clang/Driver/SanitizerArgs.h" 63 #include "clang/Driver/Tool.h" 64 #include "clang/Driver/ToolChain.h" 65 #include "clang/Driver/Types.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/STLExtras.h" 68 #include "llvm/ADT/StringExtras.h" 69 #include "llvm/ADT/StringRef.h" 70 #include "llvm/ADT/StringSet.h" 71 #include "llvm/ADT/StringSwitch.h" 72 #include "llvm/Config/llvm-config.h" 73 #include "llvm/MC/TargetRegistry.h" 74 #include "llvm/Option/Arg.h" 75 #include "llvm/Option/ArgList.h" 76 #include "llvm/Option/OptSpecifier.h" 77 #include "llvm/Option/OptTable.h" 78 #include "llvm/Option/Option.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/ExitCodes.h" 82 #include "llvm/Support/FileSystem.h" 83 #include "llvm/Support/FormatVariadic.h" 84 #include "llvm/Support/MD5.h" 85 #include "llvm/Support/Path.h" 86 #include "llvm/Support/PrettyStackTrace.h" 87 #include "llvm/Support/Process.h" 88 #include "llvm/Support/Program.h" 89 #include "llvm/Support/RISCVISAInfo.h" 90 #include "llvm/Support/StringSaver.h" 91 #include "llvm/Support/VirtualFileSystem.h" 92 #include "llvm/Support/raw_ostream.h" 93 #include "llvm/TargetParser/Host.h" 94 #include <cstdlib> // ::getenv 95 #include <map> 96 #include <memory> 97 #include <optional> 98 #include <set> 99 #include <utility> 100 #if LLVM_ON_UNIX 101 #include <unistd.h> // getpid 102 #endif 103 104 using namespace clang::driver; 105 using namespace clang; 106 using namespace llvm::opt; 107 108 static std::optional<llvm::Triple> getOffloadTargetTriple(const Driver &D, 109 const ArgList &Args) { 110 auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ); 111 // Offload compilation flow does not support multiple targets for now. We 112 // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too) 113 // to support multiple tool chains first. 114 switch (OffloadTargets.size()) { 115 default: 116 D.Diag(diag::err_drv_only_one_offload_target_supported); 117 return std::nullopt; 118 case 0: 119 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << ""; 120 return std::nullopt; 121 case 1: 122 break; 123 } 124 return llvm::Triple(OffloadTargets[0]); 125 } 126 127 static std::optional<llvm::Triple> 128 getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args, 129 const llvm::Triple &HostTriple) { 130 if (!Args.hasArg(options::OPT_offload_EQ)) { 131 return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" 132 : "nvptx-nvidia-cuda"); 133 } 134 auto TT = getOffloadTargetTriple(D, Args); 135 if (TT && (TT->getArch() == llvm::Triple::spirv32 || 136 TT->getArch() == llvm::Triple::spirv64)) { 137 if (Args.hasArg(options::OPT_emit_llvm)) 138 return TT; 139 D.Diag(diag::err_drv_cuda_offload_only_emit_bc); 140 return std::nullopt; 141 } 142 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str(); 143 return std::nullopt; 144 } 145 static std::optional<llvm::Triple> 146 getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) { 147 if (!Args.hasArg(options::OPT_offload_EQ)) { 148 return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple. 149 } 150 auto TT = getOffloadTargetTriple(D, Args); 151 if (!TT) 152 return std::nullopt; 153 if (TT->getArch() == llvm::Triple::amdgcn && 154 TT->getVendor() == llvm::Triple::AMD && 155 TT->getOS() == llvm::Triple::AMDHSA) 156 return TT; 157 if (TT->getArch() == llvm::Triple::spirv64) 158 return TT; 159 D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str(); 160 return std::nullopt; 161 } 162 163 // static 164 std::string Driver::GetResourcesPath(StringRef BinaryPath, 165 StringRef CustomResourceDir) { 166 // Since the resource directory is embedded in the module hash, it's important 167 // that all places that need it call this function, so that they get the 168 // exact same string ("a/../b/" and "b/" get different hashes, for example). 169 170 // Dir is bin/ or lib/, depending on where BinaryPath is. 171 std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath)); 172 173 SmallString<128> P(Dir); 174 if (CustomResourceDir != "") { 175 llvm::sys::path::append(P, CustomResourceDir); 176 } else { 177 // On Windows, libclang.dll is in bin/. 178 // On non-Windows, libclang.so/.dylib is in lib/. 179 // With a static-library build of libclang, LibClangPath will contain the 180 // path of the embedding binary, which for LLVM binaries will be in bin/. 181 // ../lib gets us to lib/ in both cases. 182 P = llvm::sys::path::parent_path(Dir); 183 // This search path is also created in the COFF driver of lld, so any 184 // changes here also needs to happen in lld/COFF/Driver.cpp 185 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang", 186 CLANG_VERSION_MAJOR_STRING); 187 } 188 189 return std::string(P.str()); 190 } 191 192 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple, 193 DiagnosticsEngine &Diags, std::string Title, 194 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) 195 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode), 196 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), 197 Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None), 198 ModulesModeCXX20(false), LTOMode(LTOK_None), 199 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), 200 DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false), 201 CCLogDiagnostics(false), CCGenDiagnostics(false), 202 CCPrintProcessStats(false), CCPrintInternalStats(false), 203 TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr), 204 CheckInputsExist(true), ProbePrecompiled(true), 205 SuppressMissingInputWarning(false) { 206 // Provide a sane fallback if no VFS is specified. 207 if (!this->VFS) 208 this->VFS = llvm::vfs::getRealFileSystem(); 209 210 Name = std::string(llvm::sys::path::filename(ClangExecutable)); 211 Dir = std::string(llvm::sys::path::parent_path(ClangExecutable)); 212 InstalledDir = Dir; // Provide a sensible default installed dir. 213 214 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) { 215 // Prepend InstalledDir if SysRoot is relative 216 SmallString<128> P(InstalledDir); 217 llvm::sys::path::append(P, SysRoot); 218 SysRoot = std::string(P); 219 } 220 221 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR) 222 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR; 223 #endif 224 #if defined(CLANG_CONFIG_FILE_USER_DIR) 225 { 226 SmallString<128> P; 227 llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P); 228 UserConfigDir = static_cast<std::string>(P); 229 } 230 #endif 231 232 // Compute the path to the resource directory. 233 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 234 } 235 236 void Driver::setDriverMode(StringRef Value) { 237 static StringRef OptName = 238 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 239 if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value) 240 .Case("gcc", GCCMode) 241 .Case("g++", GXXMode) 242 .Case("cpp", CPPMode) 243 .Case("cl", CLMode) 244 .Case("flang", FlangMode) 245 .Case("dxc", DXCMode) 246 .Default(std::nullopt)) 247 Mode = *M; 248 else 249 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 250 } 251 252 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings, 253 bool UseDriverMode, bool &ContainsError) { 254 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 255 ContainsError = false; 256 257 llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode); 258 unsigned MissingArgIndex, MissingArgCount; 259 InputArgList Args = getOpts().ParseArgs(ArgStrings, MissingArgIndex, 260 MissingArgCount, VisibilityMask); 261 262 // Check for missing argument error. 263 if (MissingArgCount) { 264 Diag(diag::err_drv_missing_argument) 265 << Args.getArgString(MissingArgIndex) << MissingArgCount; 266 ContainsError |= 267 Diags.getDiagnosticLevel(diag::err_drv_missing_argument, 268 SourceLocation()) > DiagnosticsEngine::Warning; 269 } 270 271 // Check for unsupported options. 272 for (const Arg *A : Args) { 273 if (A->getOption().hasFlag(options::Unsupported)) { 274 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args); 275 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt, 276 SourceLocation()) > 277 DiagnosticsEngine::Warning; 278 continue; 279 } 280 281 // Warn about -mcpu= without an argument. 282 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { 283 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args); 284 ContainsError |= Diags.getDiagnosticLevel( 285 diag::warn_drv_empty_joined_argument, 286 SourceLocation()) > DiagnosticsEngine::Warning; 287 } 288 } 289 290 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) { 291 unsigned DiagID; 292 auto ArgString = A->getAsString(Args); 293 std::string Nearest; 294 if (getOpts().findNearest(ArgString, Nearest, VisibilityMask) > 1) { 295 if (!IsCLMode() && 296 getOpts().findExact(ArgString, Nearest, 297 llvm::opt::Visibility(options::CC1Option))) { 298 DiagID = diag::err_drv_unknown_argument_with_suggestion; 299 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest; 300 } else { 301 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl 302 : diag::err_drv_unknown_argument; 303 Diags.Report(DiagID) << ArgString; 304 } 305 } else { 306 DiagID = IsCLMode() 307 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion 308 : diag::err_drv_unknown_argument_with_suggestion; 309 Diags.Report(DiagID) << ArgString << Nearest; 310 } 311 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) > 312 DiagnosticsEngine::Warning; 313 } 314 315 for (const Arg *A : Args.filtered(options::OPT_o)) { 316 if (ArgStrings[A->getIndex()] == A->getSpelling()) 317 continue; 318 319 // Warn on joined arguments that are similar to a long argument. 320 std::string ArgString = ArgStrings[A->getIndex()]; 321 std::string Nearest; 322 if (getOpts().findExact("-" + ArgString, Nearest, VisibilityMask)) 323 Diags.Report(diag::warn_drv_potentially_misspelled_joined_argument) 324 << A->getAsString(Args) << Nearest; 325 } 326 327 return Args; 328 } 329 330 // Determine which compilation mode we are in. We look for options which 331 // affect the phase, starting with the earliest phases, and record which 332 // option we used to determine the final phase. 333 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, 334 Arg **FinalPhaseArg) const { 335 Arg *PhaseArg = nullptr; 336 phases::ID FinalPhase; 337 338 // -{E,EP,P,M,MM} only run the preprocessor. 339 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) || 340 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 341 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 342 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) || 343 CCGenDiagnostics) { 344 FinalPhase = phases::Preprocess; 345 346 // --precompile only runs up to precompilation. 347 // Options that cause the output of C++20 compiled module interfaces or 348 // header units have the same effect. 349 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) || 350 (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) || 351 (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header, 352 options::OPT_fmodule_header_EQ))) { 353 FinalPhase = phases::Precompile; 354 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. 355 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 356 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) || 357 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 358 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 359 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 360 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 361 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 362 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) || 363 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { 364 FinalPhase = phases::Compile; 365 366 // -S only runs up to the backend. 367 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) { 368 FinalPhase = phases::Backend; 369 370 // -c compilation only runs up to the assembler. 371 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 372 FinalPhase = phases::Assemble; 373 374 } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) { 375 FinalPhase = phases::IfsMerge; 376 377 // Otherwise do everything. 378 } else 379 FinalPhase = phases::Link; 380 381 if (FinalPhaseArg) 382 *FinalPhaseArg = PhaseArg; 383 384 return FinalPhase; 385 } 386 387 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts, 388 StringRef Value, bool Claim = true) { 389 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value, 390 Args.getBaseArgs().MakeIndex(Value), Value.data()); 391 Args.AddSynthesizedArg(A); 392 if (Claim) 393 A->claim(); 394 return A; 395 } 396 397 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 398 const llvm::opt::OptTable &Opts = getOpts(); 399 DerivedArgList *DAL = new DerivedArgList(Args); 400 401 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 402 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx); 403 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs); 404 bool IgnoreUnused = false; 405 for (Arg *A : Args) { 406 if (IgnoreUnused) 407 A->claim(); 408 409 if (A->getOption().matches(options::OPT_start_no_unused_arguments)) { 410 IgnoreUnused = true; 411 continue; 412 } 413 if (A->getOption().matches(options::OPT_end_no_unused_arguments)) { 414 IgnoreUnused = false; 415 continue; 416 } 417 418 // Unfortunately, we have to parse some forwarding options (-Xassembler, 419 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 420 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 421 422 // Rewrite linker options, to replace --no-demangle with a custom internal 423 // option. 424 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 425 A->getOption().matches(options::OPT_Xlinker)) && 426 A->containsValue("--no-demangle")) { 427 // Add the rewritten no-demangle argument. 428 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle)); 429 430 // Add the remaining values as Xlinker arguments. 431 for (StringRef Val : A->getValues()) 432 if (Val != "--no-demangle") 433 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val); 434 435 continue; 436 } 437 438 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 439 // some build systems. We don't try to be complete here because we don't 440 // care to encourage this usage model. 441 if (A->getOption().matches(options::OPT_Wp_COMMA) && 442 (A->getValue(0) == StringRef("-MD") || 443 A->getValue(0) == StringRef("-MMD"))) { 444 // Rewrite to -MD/-MMD along with -MF. 445 if (A->getValue(0) == StringRef("-MD")) 446 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD)); 447 else 448 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD)); 449 if (A->getNumValues() == 2) 450 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1)); 451 continue; 452 } 453 454 // Rewrite reserved library names. 455 if (A->getOption().matches(options::OPT_l)) { 456 StringRef Value = A->getValue(); 457 458 // Rewrite unless -nostdlib is present. 459 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx && 460 Value == "stdc++") { 461 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx)); 462 continue; 463 } 464 465 // Rewrite unconditionally. 466 if (Value == "cc_kext") { 467 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext)); 468 continue; 469 } 470 } 471 472 // Pick up inputs via the -- option. 473 if (A->getOption().matches(options::OPT__DASH_DASH)) { 474 A->claim(); 475 for (StringRef Val : A->getValues()) 476 DAL->append(MakeInputArg(*DAL, Opts, Val, false)); 477 continue; 478 } 479 480 DAL->append(A); 481 } 482 483 // DXC mode quits before assembly if an output object file isn't specified. 484 if (IsDXCMode() && !Args.hasArg(options::OPT_dxc_Fo)) 485 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S)); 486 487 // Enforce -static if -miamcu is present. 488 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) 489 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static)); 490 491 // Add a default value of -mlinker-version=, if one was given and the user 492 // didn't specify one. 493 #if defined(HOST_LINK_VERSION) 494 if (!Args.hasArg(options::OPT_mlinker_version_EQ) && 495 strlen(HOST_LINK_VERSION) > 0) { 496 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ), 497 HOST_LINK_VERSION); 498 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 499 } 500 #endif 501 502 return DAL; 503 } 504 505 /// Compute target triple from args. 506 /// 507 /// This routine provides the logic to compute a target triple from various 508 /// args passed to the driver and the default triple string. 509 static llvm::Triple computeTargetTriple(const Driver &D, 510 StringRef TargetTriple, 511 const ArgList &Args, 512 StringRef DarwinArchName = "") { 513 // FIXME: Already done in Compilation *Driver::BuildCompilation 514 if (const Arg *A = Args.getLastArg(options::OPT_target)) 515 TargetTriple = A->getValue(); 516 517 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 518 519 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made 520 // -gnu* only, and we can not change this, so we have to detect that case as 521 // being the Hurd OS. 522 if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu")) 523 Target.setOSName("hurd"); 524 525 // Handle Apple-specific options available here. 526 if (Target.isOSBinFormatMachO()) { 527 // If an explicit Darwin arch name is given, that trumps all. 528 if (!DarwinArchName.empty()) { 529 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName, 530 Args); 531 return Target; 532 } 533 534 // Handle the Darwin '-arch' flag. 535 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 536 StringRef ArchName = A->getValue(); 537 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName, Args); 538 } 539 } 540 541 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 542 // '-mbig-endian'/'-EB'. 543 if (Arg *A = Args.getLastArgNoClaim(options::OPT_mlittle_endian, 544 options::OPT_mbig_endian)) { 545 llvm::Triple T = A->getOption().matches(options::OPT_mlittle_endian) 546 ? Target.getLittleEndianArchVariant() 547 : Target.getBigEndianArchVariant(); 548 if (T.getArch() != llvm::Triple::UnknownArch) { 549 Target = std::move(T); 550 Args.claimAllArgs(options::OPT_mlittle_endian, options::OPT_mbig_endian); 551 } 552 } 553 554 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 555 if (Target.getArch() == llvm::Triple::tce) 556 return Target; 557 558 // On AIX, the env OBJECT_MODE may affect the resulting arch variant. 559 if (Target.isOSAIX()) { 560 if (std::optional<std::string> ObjectModeValue = 561 llvm::sys::Process::GetEnv("OBJECT_MODE")) { 562 StringRef ObjectMode = *ObjectModeValue; 563 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 564 565 if (ObjectMode.equals("64")) { 566 AT = Target.get64BitArchVariant().getArch(); 567 } else if (ObjectMode.equals("32")) { 568 AT = Target.get32BitArchVariant().getArch(); 569 } else { 570 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode; 571 } 572 573 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 574 Target.setArch(AT); 575 } 576 } 577 578 // The `-maix[32|64]` flags are only valid for AIX targets. 579 if (Arg *A = Args.getLastArgNoClaim(options::OPT_maix32, options::OPT_maix64); 580 A && !Target.isOSAIX()) 581 D.Diag(diag::err_drv_unsupported_opt_for_target) 582 << A->getAsString(Args) << Target.str(); 583 584 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 585 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 586 options::OPT_m32, options::OPT_m16, 587 options::OPT_maix32, options::OPT_maix64); 588 if (A) { 589 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 590 591 if (A->getOption().matches(options::OPT_m64) || 592 A->getOption().matches(options::OPT_maix64)) { 593 AT = Target.get64BitArchVariant().getArch(); 594 if (Target.getEnvironment() == llvm::Triple::GNUX32) 595 Target.setEnvironment(llvm::Triple::GNU); 596 else if (Target.getEnvironment() == llvm::Triple::MuslX32) 597 Target.setEnvironment(llvm::Triple::Musl); 598 } else if (A->getOption().matches(options::OPT_mx32) && 599 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 600 AT = llvm::Triple::x86_64; 601 if (Target.getEnvironment() == llvm::Triple::Musl) 602 Target.setEnvironment(llvm::Triple::MuslX32); 603 else 604 Target.setEnvironment(llvm::Triple::GNUX32); 605 } else if (A->getOption().matches(options::OPT_m32) || 606 A->getOption().matches(options::OPT_maix32)) { 607 AT = Target.get32BitArchVariant().getArch(); 608 if (Target.getEnvironment() == llvm::Triple::GNUX32) 609 Target.setEnvironment(llvm::Triple::GNU); 610 else if (Target.getEnvironment() == llvm::Triple::MuslX32) 611 Target.setEnvironment(llvm::Triple::Musl); 612 } else if (A->getOption().matches(options::OPT_m16) && 613 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 614 AT = llvm::Triple::x86; 615 Target.setEnvironment(llvm::Triple::CODE16); 616 } 617 618 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) { 619 Target.setArch(AT); 620 if (Target.isWindowsGNUEnvironment()) 621 toolchains::MinGW::fixTripleArch(D, Target, Args); 622 } 623 } 624 625 // Handle -miamcu flag. 626 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) { 627 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) 628 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu" 629 << Target.str(); 630 631 if (A && !A->getOption().matches(options::OPT_m32)) 632 D.Diag(diag::err_drv_argument_not_allowed_with) 633 << "-miamcu" << A->getBaseArg().getAsString(Args); 634 635 Target.setArch(llvm::Triple::x86); 636 Target.setArchName("i586"); 637 Target.setEnvironment(llvm::Triple::UnknownEnvironment); 638 Target.setEnvironmentName(""); 639 Target.setOS(llvm::Triple::ELFIAMCU); 640 Target.setVendor(llvm::Triple::UnknownVendor); 641 Target.setVendorName("intel"); 642 } 643 644 // If target is MIPS adjust the target triple 645 // accordingly to provided ABI name. 646 if (Target.isMIPS()) { 647 if ((A = Args.getLastArg(options::OPT_mabi_EQ))) { 648 StringRef ABIName = A->getValue(); 649 if (ABIName == "32") { 650 Target = Target.get32BitArchVariant(); 651 if (Target.getEnvironment() == llvm::Triple::GNUABI64 || 652 Target.getEnvironment() == llvm::Triple::GNUABIN32) 653 Target.setEnvironment(llvm::Triple::GNU); 654 } else if (ABIName == "n32") { 655 Target = Target.get64BitArchVariant(); 656 if (Target.getEnvironment() == llvm::Triple::GNU || 657 Target.getEnvironment() == llvm::Triple::GNUABI64) 658 Target.setEnvironment(llvm::Triple::GNUABIN32); 659 } else if (ABIName == "64") { 660 Target = Target.get64BitArchVariant(); 661 if (Target.getEnvironment() == llvm::Triple::GNU || 662 Target.getEnvironment() == llvm::Triple::GNUABIN32) 663 Target.setEnvironment(llvm::Triple::GNUABI64); 664 } 665 } 666 } 667 668 // If target is RISC-V adjust the target triple according to 669 // provided architecture name 670 if (Target.isRISCV()) { 671 if (Args.hasArg(options::OPT_march_EQ) || 672 Args.hasArg(options::OPT_mcpu_EQ)) { 673 StringRef ArchName = tools::riscv::getRISCVArch(Args, Target); 674 auto ISAInfo = llvm::RISCVISAInfo::parseArchString( 675 ArchName, /*EnableExperimentalExtensions=*/true); 676 if (!llvm::errorToBool(ISAInfo.takeError())) { 677 unsigned XLen = (*ISAInfo)->getXLen(); 678 if (XLen == 32) 679 Target.setArch(llvm::Triple::riscv32); 680 else if (XLen == 64) 681 Target.setArch(llvm::Triple::riscv64); 682 } 683 } 684 } 685 686 return Target; 687 } 688 689 // Parse the LTO options and record the type of LTO compilation 690 // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)? 691 // option occurs last. 692 static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args, 693 OptSpecifier OptEq, OptSpecifier OptNeg) { 694 if (!Args.hasFlag(OptEq, OptNeg, false)) 695 return LTOK_None; 696 697 const Arg *A = Args.getLastArg(OptEq); 698 StringRef LTOName = A->getValue(); 699 700 driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName) 701 .Case("full", LTOK_Full) 702 .Case("thin", LTOK_Thin) 703 .Default(LTOK_Unknown); 704 705 if (LTOMode == LTOK_Unknown) { 706 D.Diag(diag::err_drv_unsupported_option_argument) 707 << A->getSpelling() << A->getValue(); 708 return LTOK_None; 709 } 710 return LTOMode; 711 } 712 713 // Parse the LTO options. 714 void Driver::setLTOMode(const llvm::opt::ArgList &Args) { 715 LTOMode = 716 parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto); 717 718 OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ, 719 options::OPT_fno_offload_lto); 720 721 // Try to enable `-foffload-lto=full` if `-fopenmp-target-jit` is on. 722 if (Args.hasFlag(options::OPT_fopenmp_target_jit, 723 options::OPT_fno_openmp_target_jit, false)) { 724 if (Arg *A = Args.getLastArg(options::OPT_foffload_lto_EQ, 725 options::OPT_fno_offload_lto)) 726 if (OffloadLTOMode != LTOK_Full) 727 Diag(diag::err_drv_incompatible_options) 728 << A->getSpelling() << "-fopenmp-target-jit"; 729 OffloadLTOMode = LTOK_Full; 730 } 731 } 732 733 /// Compute the desired OpenMP runtime from the flags provided. 734 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const { 735 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME); 736 737 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ); 738 if (A) 739 RuntimeName = A->getValue(); 740 741 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName) 742 .Case("libomp", OMPRT_OMP) 743 .Case("libgomp", OMPRT_GOMP) 744 .Case("libiomp5", OMPRT_IOMP5) 745 .Default(OMPRT_Unknown); 746 747 if (RT == OMPRT_Unknown) { 748 if (A) 749 Diag(diag::err_drv_unsupported_option_argument) 750 << A->getSpelling() << A->getValue(); 751 else 752 // FIXME: We could use a nicer diagnostic here. 753 Diag(diag::err_drv_unsupported_opt) << "-fopenmp"; 754 } 755 756 return RT; 757 } 758 759 void Driver::CreateOffloadingDeviceToolChains(Compilation &C, 760 InputList &Inputs) { 761 762 // 763 // CUDA/HIP 764 // 765 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA 766 // or HIP type. However, mixed CUDA/HIP compilation is not supported. 767 bool IsCuda = 768 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 769 return types::isCuda(I.first); 770 }); 771 bool IsHIP = 772 llvm::any_of(Inputs, 773 [](std::pair<types::ID, const llvm::opt::Arg *> &I) { 774 return types::isHIP(I.first); 775 }) || 776 C.getInputArgs().hasArg(options::OPT_hip_link) || 777 C.getInputArgs().hasArg(options::OPT_hipstdpar); 778 if (IsCuda && IsHIP) { 779 Diag(clang::diag::err_drv_mix_cuda_hip); 780 return; 781 } 782 if (IsCuda) { 783 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 784 const llvm::Triple &HostTriple = HostTC->getTriple(); 785 auto OFK = Action::OFK_Cuda; 786 auto CudaTriple = 787 getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple); 788 if (!CudaTriple) 789 return; 790 // Use the CUDA and host triples as the key into the ToolChains map, 791 // because the device toolchain we create depends on both. 792 auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()]; 793 if (!CudaTC) { 794 CudaTC = std::make_unique<toolchains::CudaToolChain>( 795 *this, *CudaTriple, *HostTC, C.getInputArgs()); 796 797 // Emit a warning if the detected CUDA version is too new. 798 CudaInstallationDetector &CudaInstallation = 799 static_cast<toolchains::CudaToolChain &>(*CudaTC).CudaInstallation; 800 if (CudaInstallation.isValid()) 801 CudaInstallation.WarnIfUnsupportedVersion(); 802 } 803 C.addOffloadDeviceToolChain(CudaTC.get(), OFK); 804 } else if (IsHIP) { 805 if (auto *OMPTargetArg = 806 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) { 807 Diag(clang::diag::err_drv_unsupported_opt_for_language_mode) 808 << OMPTargetArg->getSpelling() << "HIP"; 809 return; 810 } 811 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 812 auto OFK = Action::OFK_HIP; 813 auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs()); 814 if (!HIPTriple) 815 return; 816 auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple, 817 *HostTC, OFK); 818 assert(HIPTC && "Could not create offloading device tool chain."); 819 C.addOffloadDeviceToolChain(HIPTC, OFK); 820 } 821 822 // 823 // OpenMP 824 // 825 // We need to generate an OpenMP toolchain if the user specified targets with 826 // the -fopenmp-targets option or used --offload-arch with OpenMP enabled. 827 bool IsOpenMPOffloading = 828 C.getInputArgs().hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 829 options::OPT_fno_openmp, false) && 830 (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) || 831 C.getInputArgs().hasArg(options::OPT_offload_arch_EQ)); 832 if (IsOpenMPOffloading) { 833 // We expect that -fopenmp-targets is always used in conjunction with the 834 // option -fopenmp specifying a valid runtime with offloading support, i.e. 835 // libomp or libiomp. 836 OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(C.getInputArgs()); 837 if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) { 838 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); 839 return; 840 } 841 842 llvm::StringMap<llvm::DenseSet<StringRef>> DerivedArchs; 843 llvm::StringMap<StringRef> FoundNormalizedTriples; 844 std::multiset<StringRef> OpenMPTriples; 845 846 // If the user specified -fopenmp-targets= we create a toolchain for each 847 // valid triple. Otherwise, if only --offload-arch= was specified we instead 848 // attempt to derive the appropriate toolchains from the arguments. 849 if (Arg *OpenMPTargets = 850 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) { 851 if (OpenMPTargets && !OpenMPTargets->getNumValues()) { 852 Diag(clang::diag::warn_drv_empty_joined_argument) 853 << OpenMPTargets->getAsString(C.getInputArgs()); 854 return; 855 } 856 for (StringRef T : OpenMPTargets->getValues()) 857 OpenMPTriples.insert(T); 858 } else if (C.getInputArgs().hasArg(options::OPT_offload_arch_EQ) && 859 !IsHIP && !IsCuda) { 860 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 861 auto AMDTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs()); 862 auto NVPTXTriple = getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), 863 HostTC->getTriple()); 864 865 // Attempt to deduce the offloading triple from the set of architectures. 866 // We can only correctly deduce NVPTX / AMDGPU triples currently. We need 867 // to temporarily create these toolchains so that we can access tools for 868 // inferring architectures. 869 llvm::DenseSet<StringRef> Archs; 870 if (NVPTXTriple) { 871 auto TempTC = std::make_unique<toolchains::CudaToolChain>( 872 *this, *NVPTXTriple, *HostTC, C.getInputArgs()); 873 for (StringRef Arch : getOffloadArchs( 874 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true)) 875 Archs.insert(Arch); 876 } 877 if (AMDTriple) { 878 auto TempTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>( 879 *this, *AMDTriple, *HostTC, C.getInputArgs()); 880 for (StringRef Arch : getOffloadArchs( 881 C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true)) 882 Archs.insert(Arch); 883 } 884 if (!AMDTriple && !NVPTXTriple) { 885 for (StringRef Arch : 886 getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true)) 887 Archs.insert(Arch); 888 } 889 890 for (StringRef Arch : Archs) { 891 if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch( 892 getProcessorFromTargetID(*NVPTXTriple, Arch)))) { 893 DerivedArchs[NVPTXTriple->getTriple()].insert(Arch); 894 } else if (AMDTriple && 895 IsAMDGpuArch(StringToCudaArch( 896 getProcessorFromTargetID(*AMDTriple, Arch)))) { 897 DerivedArchs[AMDTriple->getTriple()].insert(Arch); 898 } else { 899 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) << Arch; 900 return; 901 } 902 } 903 904 // If the set is empty then we failed to find a native architecture. 905 if (Archs.empty()) { 906 Diag(clang::diag::err_drv_failed_to_deduce_target_from_arch) 907 << "native"; 908 return; 909 } 910 911 for (const auto &TripleAndArchs : DerivedArchs) 912 OpenMPTriples.insert(TripleAndArchs.first()); 913 } 914 915 for (StringRef Val : OpenMPTriples) { 916 llvm::Triple TT(ToolChain::getOpenMPTriple(Val)); 917 std::string NormalizedName = TT.normalize(); 918 919 // Make sure we don't have a duplicate triple. 920 auto Duplicate = FoundNormalizedTriples.find(NormalizedName); 921 if (Duplicate != FoundNormalizedTriples.end()) { 922 Diag(clang::diag::warn_drv_omp_offload_target_duplicate) 923 << Val << Duplicate->second; 924 continue; 925 } 926 927 // Store the current triple so that we can check for duplicates in the 928 // following iterations. 929 FoundNormalizedTriples[NormalizedName] = Val; 930 931 // If the specified target is invalid, emit a diagnostic. 932 if (TT.getArch() == llvm::Triple::UnknownArch) 933 Diag(clang::diag::err_drv_invalid_omp_target) << Val; 934 else { 935 const ToolChain *TC; 936 // Device toolchains have to be selected differently. They pair host 937 // and device in their implementation. 938 if (TT.isNVPTX() || TT.isAMDGCN()) { 939 const ToolChain *HostTC = 940 C.getSingleOffloadToolChain<Action::OFK_Host>(); 941 assert(HostTC && "Host toolchain should be always defined."); 942 auto &DeviceTC = 943 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()]; 944 if (!DeviceTC) { 945 if (TT.isNVPTX()) 946 DeviceTC = std::make_unique<toolchains::CudaToolChain>( 947 *this, TT, *HostTC, C.getInputArgs()); 948 else if (TT.isAMDGCN()) 949 DeviceTC = std::make_unique<toolchains::AMDGPUOpenMPToolChain>( 950 *this, TT, *HostTC, C.getInputArgs()); 951 else 952 assert(DeviceTC && "Device toolchain not defined."); 953 } 954 955 TC = DeviceTC.get(); 956 } else 957 TC = &getToolChain(C.getInputArgs(), TT); 958 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP); 959 if (DerivedArchs.contains(TT.getTriple())) 960 KnownArchs[TC] = DerivedArchs[TT.getTriple()]; 961 } 962 } 963 } else if (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ)) { 964 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets); 965 return; 966 } 967 968 // 969 // TODO: Add support for other offloading programming models here. 970 // 971 } 972 973 static void appendOneArg(InputArgList &Args, const Arg *Opt, 974 const Arg *BaseArg) { 975 // The args for config files or /clang: flags belong to different InputArgList 976 // objects than Args. This copies an Arg from one of those other InputArgLists 977 // to the ownership of Args. 978 unsigned Index = Args.MakeIndex(Opt->getSpelling()); 979 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index), 980 Index, BaseArg); 981 Copy->getValues() = Opt->getValues(); 982 if (Opt->isClaimed()) 983 Copy->claim(); 984 Copy->setOwnsValues(Opt->getOwnsValues()); 985 Opt->setOwnsValues(false); 986 Args.append(Copy); 987 } 988 989 bool Driver::readConfigFile(StringRef FileName, 990 llvm::cl::ExpansionContext &ExpCtx) { 991 // Try opening the given file. 992 auto Status = getVFS().status(FileName); 993 if (!Status) { 994 Diag(diag::err_drv_cannot_open_config_file) 995 << FileName << Status.getError().message(); 996 return true; 997 } 998 if (Status->getType() != llvm::sys::fs::file_type::regular_file) { 999 Diag(diag::err_drv_cannot_open_config_file) 1000 << FileName << "not a regular file"; 1001 return true; 1002 } 1003 1004 // Try reading the given file. 1005 SmallVector<const char *, 32> NewCfgArgs; 1006 if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) { 1007 Diag(diag::err_drv_cannot_read_config_file) 1008 << FileName << toString(std::move(Err)); 1009 return true; 1010 } 1011 1012 // Read options from config file. 1013 llvm::SmallString<128> CfgFileName(FileName); 1014 llvm::sys::path::native(CfgFileName); 1015 bool ContainErrors; 1016 std::unique_ptr<InputArgList> NewOptions = std::make_unique<InputArgList>( 1017 ParseArgStrings(NewCfgArgs, /*UseDriverMode=*/true, ContainErrors)); 1018 if (ContainErrors) 1019 return true; 1020 1021 // Claim all arguments that come from a configuration file so that the driver 1022 // does not warn on any that is unused. 1023 for (Arg *A : *NewOptions) 1024 A->claim(); 1025 1026 if (!CfgOptions) 1027 CfgOptions = std::move(NewOptions); 1028 else { 1029 // If this is a subsequent config file, append options to the previous one. 1030 for (auto *Opt : *NewOptions) { 1031 const Arg *BaseArg = &Opt->getBaseArg(); 1032 if (BaseArg == Opt) 1033 BaseArg = nullptr; 1034 appendOneArg(*CfgOptions, Opt, BaseArg); 1035 } 1036 } 1037 ConfigFiles.push_back(std::string(CfgFileName)); 1038 return false; 1039 } 1040 1041 bool Driver::loadConfigFiles() { 1042 llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(), 1043 llvm::cl::tokenizeConfigFile); 1044 ExpCtx.setVFS(&getVFS()); 1045 1046 // Process options that change search path for config files. 1047 if (CLOptions) { 1048 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) { 1049 SmallString<128> CfgDir; 1050 CfgDir.append( 1051 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ)); 1052 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir)) 1053 SystemConfigDir.clear(); 1054 else 1055 SystemConfigDir = static_cast<std::string>(CfgDir); 1056 } 1057 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) { 1058 SmallString<128> CfgDir; 1059 llvm::sys::fs::expand_tilde( 1060 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ), CfgDir); 1061 if (CfgDir.empty() || getVFS().makeAbsolute(CfgDir)) 1062 UserConfigDir.clear(); 1063 else 1064 UserConfigDir = static_cast<std::string>(CfgDir); 1065 } 1066 } 1067 1068 // Prepare list of directories where config file is searched for. 1069 StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir}; 1070 ExpCtx.setSearchDirs(CfgFileSearchDirs); 1071 1072 // First try to load configuration from the default files, return on error. 1073 if (loadDefaultConfigFiles(ExpCtx)) 1074 return true; 1075 1076 // Then load configuration files specified explicitly. 1077 SmallString<128> CfgFilePath; 1078 if (CLOptions) { 1079 for (auto CfgFileName : CLOptions->getAllArgValues(options::OPT_config)) { 1080 // If argument contains directory separator, treat it as a path to 1081 // configuration file. 1082 if (llvm::sys::path::has_parent_path(CfgFileName)) { 1083 CfgFilePath.assign(CfgFileName); 1084 if (llvm::sys::path::is_relative(CfgFilePath)) { 1085 if (getVFS().makeAbsolute(CfgFilePath)) { 1086 Diag(diag::err_drv_cannot_open_config_file) 1087 << CfgFilePath << "cannot get absolute path"; 1088 return true; 1089 } 1090 } 1091 } else if (!ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) { 1092 // Report an error that the config file could not be found. 1093 Diag(diag::err_drv_config_file_not_found) << CfgFileName; 1094 for (const StringRef &SearchDir : CfgFileSearchDirs) 1095 if (!SearchDir.empty()) 1096 Diag(diag::note_drv_config_file_searched_in) << SearchDir; 1097 return true; 1098 } 1099 1100 // Try to read the config file, return on error. 1101 if (readConfigFile(CfgFilePath, ExpCtx)) 1102 return true; 1103 } 1104 } 1105 1106 // No error occurred. 1107 return false; 1108 } 1109 1110 bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) { 1111 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty 1112 // value. 1113 if (const char *NoConfigEnv = ::getenv("CLANG_NO_DEFAULT_CONFIG")) { 1114 if (*NoConfigEnv) 1115 return false; 1116 } 1117 if (CLOptions && CLOptions->hasArg(options::OPT_no_default_config)) 1118 return false; 1119 1120 std::string RealMode = getExecutableForDriverMode(Mode); 1121 std::string Triple; 1122 1123 // If name prefix is present, no --target= override was passed via CLOptions 1124 // and the name prefix is not a valid triple, force it for backwards 1125 // compatibility. 1126 if (!ClangNameParts.TargetPrefix.empty() && 1127 computeTargetTriple(*this, "/invalid/", *CLOptions).str() == 1128 "/invalid/") { 1129 llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix}; 1130 if (PrefixTriple.getArch() == llvm::Triple::UnknownArch || 1131 PrefixTriple.isOSUnknown()) 1132 Triple = PrefixTriple.str(); 1133 } 1134 1135 // Otherwise, use the real triple as used by the driver. 1136 if (Triple.empty()) { 1137 llvm::Triple RealTriple = 1138 computeTargetTriple(*this, TargetTriple, *CLOptions); 1139 Triple = RealTriple.str(); 1140 assert(!Triple.empty()); 1141 } 1142 1143 // Search for config files in the following order: 1144 // 1. <triple>-<mode>.cfg using real driver mode 1145 // (e.g. i386-pc-linux-gnu-clang++.cfg). 1146 // 2. <triple>-<mode>.cfg using executable suffix 1147 // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++). 1148 // 3. <triple>.cfg + <mode>.cfg using real driver mode 1149 // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg). 1150 // 4. <triple>.cfg + <mode>.cfg using executable suffix 1151 // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++). 1152 1153 // Try loading <triple>-<mode>.cfg, and return if we find a match. 1154 SmallString<128> CfgFilePath; 1155 std::string CfgFileName = Triple + '-' + RealMode + ".cfg"; 1156 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) 1157 return readConfigFile(CfgFilePath, ExpCtx); 1158 1159 bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() && 1160 ClangNameParts.ModeSuffix != RealMode; 1161 if (TryModeSuffix) { 1162 CfgFileName = Triple + '-' + ClangNameParts.ModeSuffix + ".cfg"; 1163 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) 1164 return readConfigFile(CfgFilePath, ExpCtx); 1165 } 1166 1167 // Try loading <mode>.cfg, and return if loading failed. If a matching file 1168 // was not found, still proceed on to try <triple>.cfg. 1169 CfgFileName = RealMode + ".cfg"; 1170 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) { 1171 if (readConfigFile(CfgFilePath, ExpCtx)) 1172 return true; 1173 } else if (TryModeSuffix) { 1174 CfgFileName = ClangNameParts.ModeSuffix + ".cfg"; 1175 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath) && 1176 readConfigFile(CfgFilePath, ExpCtx)) 1177 return true; 1178 } 1179 1180 // Try loading <triple>.cfg and return if we find a match. 1181 CfgFileName = Triple + ".cfg"; 1182 if (ExpCtx.findConfigFile(CfgFileName, CfgFilePath)) 1183 return readConfigFile(CfgFilePath, ExpCtx); 1184 1185 // If we were unable to find a config file deduced from executable name, 1186 // that is not an error. 1187 return false; 1188 } 1189 1190 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 1191 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 1192 1193 // FIXME: Handle environment options which affect driver behavior, somewhere 1194 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 1195 1196 // We look for the driver mode option early, because the mode can affect 1197 // how other options are parsed. 1198 1199 auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1)); 1200 if (!DriverMode.empty()) 1201 setDriverMode(DriverMode); 1202 1203 // FIXME: What are we going to do with -V and -b? 1204 1205 // Arguments specified in command line. 1206 bool ContainsError; 1207 CLOptions = std::make_unique<InputArgList>( 1208 ParseArgStrings(ArgList.slice(1), /*UseDriverMode=*/true, ContainsError)); 1209 1210 // Try parsing configuration file. 1211 if (!ContainsError) 1212 ContainsError = loadConfigFiles(); 1213 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr); 1214 1215 // All arguments, from both config file and command line. 1216 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions) 1217 : std::move(*CLOptions)); 1218 1219 if (HasConfigFile) 1220 for (auto *Opt : *CLOptions) { 1221 if (Opt->getOption().matches(options::OPT_config)) 1222 continue; 1223 const Arg *BaseArg = &Opt->getBaseArg(); 1224 if (BaseArg == Opt) 1225 BaseArg = nullptr; 1226 appendOneArg(Args, Opt, BaseArg); 1227 } 1228 1229 // In CL mode, look for any pass-through arguments 1230 if (IsCLMode() && !ContainsError) { 1231 SmallVector<const char *, 16> CLModePassThroughArgList; 1232 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) { 1233 A->claim(); 1234 CLModePassThroughArgList.push_back(A->getValue()); 1235 } 1236 1237 if (!CLModePassThroughArgList.empty()) { 1238 // Parse any pass through args using default clang processing rather 1239 // than clang-cl processing. 1240 auto CLModePassThroughOptions = std::make_unique<InputArgList>( 1241 ParseArgStrings(CLModePassThroughArgList, /*UseDriverMode=*/false, 1242 ContainsError)); 1243 1244 if (!ContainsError) 1245 for (auto *Opt : *CLModePassThroughOptions) { 1246 appendOneArg(Args, Opt, nullptr); 1247 } 1248 } 1249 } 1250 1251 // Check for working directory option before accessing any files 1252 if (Arg *WD = Args.getLastArg(options::OPT_working_directory)) 1253 if (VFS->setCurrentWorkingDirectory(WD->getValue())) 1254 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue(); 1255 1256 // FIXME: This stuff needs to go into the Compilation, not the driver. 1257 bool CCCPrintPhases; 1258 1259 // -canonical-prefixes, -no-canonical-prefixes are used very early in main. 1260 Args.ClaimAllArgs(options::OPT_canonical_prefixes); 1261 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes); 1262 1263 // f(no-)integated-cc1 is also used very early in main. 1264 Args.ClaimAllArgs(options::OPT_fintegrated_cc1); 1265 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1); 1266 1267 // Ignore -pipe. 1268 Args.ClaimAllArgs(options::OPT_pipe); 1269 1270 // Extract -ccc args. 1271 // 1272 // FIXME: We need to figure out where this behavior should live. Most of it 1273 // should be outside in the client; the parts that aren't should have proper 1274 // options, either by introducing new ones or by overloading gcc ones like -V 1275 // or -b. 1276 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases); 1277 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings); 1278 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name)) 1279 CCCGenericGCCName = A->getValue(); 1280 1281 // Process -fproc-stat-report options. 1282 if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) { 1283 CCPrintProcessStats = true; 1284 CCPrintStatReportFilename = A->getValue(); 1285 } 1286 if (Args.hasArg(options::OPT_fproc_stat_report)) 1287 CCPrintProcessStats = true; 1288 1289 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld 1290 // and getToolChain is const. 1291 if (IsCLMode()) { 1292 // clang-cl targets MSVC-style Win32. 1293 llvm::Triple T(TargetTriple); 1294 T.setOS(llvm::Triple::Win32); 1295 T.setVendor(llvm::Triple::PC); 1296 T.setEnvironment(llvm::Triple::MSVC); 1297 T.setObjectFormat(llvm::Triple::COFF); 1298 if (Args.hasArg(options::OPT__SLASH_arm64EC)) 1299 T.setArch(llvm::Triple::aarch64, llvm::Triple::AArch64SubArch_arm64ec); 1300 TargetTriple = T.str(); 1301 } else if (IsDXCMode()) { 1302 // Build TargetTriple from target_profile option for clang-dxc. 1303 if (const Arg *A = Args.getLastArg(options::OPT_target_profile)) { 1304 StringRef TargetProfile = A->getValue(); 1305 if (auto Triple = 1306 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile)) 1307 TargetTriple = *Triple; 1308 else 1309 Diag(diag::err_drv_invalid_directx_shader_module) << TargetProfile; 1310 1311 A->claim(); 1312 1313 // TODO: Specify Vulkan target environment somewhere in the triple. 1314 if (Args.hasArg(options::OPT_spirv)) { 1315 llvm::Triple T(TargetTriple); 1316 T.setArch(llvm::Triple::spirv); 1317 TargetTriple = T.str(); 1318 } 1319 } else { 1320 Diag(diag::err_drv_dxc_missing_target_profile); 1321 } 1322 } 1323 1324 if (const Arg *A = Args.getLastArg(options::OPT_target)) 1325 TargetTriple = A->getValue(); 1326 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir)) 1327 Dir = InstalledDir = A->getValue(); 1328 for (const Arg *A : Args.filtered(options::OPT_B)) { 1329 A->claim(); 1330 PrefixDirs.push_back(A->getValue(0)); 1331 } 1332 if (std::optional<std::string> CompilerPathValue = 1333 llvm::sys::Process::GetEnv("COMPILER_PATH")) { 1334 StringRef CompilerPath = *CompilerPathValue; 1335 while (!CompilerPath.empty()) { 1336 std::pair<StringRef, StringRef> Split = 1337 CompilerPath.split(llvm::sys::EnvPathSeparator); 1338 PrefixDirs.push_back(std::string(Split.first)); 1339 CompilerPath = Split.second; 1340 } 1341 } 1342 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) 1343 SysRoot = A->getValue(); 1344 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ)) 1345 DyldPrefix = A->getValue(); 1346 1347 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir)) 1348 ResourceDir = A->getValue(); 1349 1350 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) { 1351 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) 1352 .Case("cwd", SaveTempsCwd) 1353 .Case("obj", SaveTempsObj) 1354 .Default(SaveTempsCwd); 1355 } 1356 1357 if (const Arg *A = Args.getLastArg(options::OPT_offload_host_only, 1358 options::OPT_offload_device_only, 1359 options::OPT_offload_host_device)) { 1360 if (A->getOption().matches(options::OPT_offload_host_only)) 1361 Offload = OffloadHost; 1362 else if (A->getOption().matches(options::OPT_offload_device_only)) 1363 Offload = OffloadDevice; 1364 else 1365 Offload = OffloadHostDevice; 1366 } 1367 1368 setLTOMode(Args); 1369 1370 // Process -fembed-bitcode= flags. 1371 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) { 1372 StringRef Name = A->getValue(); 1373 unsigned Model = llvm::StringSwitch<unsigned>(Name) 1374 .Case("off", EmbedNone) 1375 .Case("all", EmbedBitcode) 1376 .Case("bitcode", EmbedBitcode) 1377 .Case("marker", EmbedMarker) 1378 .Default(~0U); 1379 if (Model == ~0U) { 1380 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 1381 << Name; 1382 } else 1383 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); 1384 } 1385 1386 // Remove existing compilation database so that each job can append to it. 1387 if (Arg *A = Args.getLastArg(options::OPT_MJ)) 1388 llvm::sys::fs::remove(A->getValue()); 1389 1390 // Setting up the jobs for some precompile cases depends on whether we are 1391 // treating them as PCH, implicit modules or C++20 ones. 1392 // TODO: inferring the mode like this seems fragile (it meets the objective 1393 // of not requiring anything new for operation, however). 1394 const Arg *Std = Args.getLastArg(options::OPT_std_EQ); 1395 ModulesModeCXX20 = 1396 !Args.hasArg(options::OPT_fmodules) && Std && 1397 (Std->containsValue("c++20") || Std->containsValue("c++2a") || 1398 Std->containsValue("c++23") || Std->containsValue("c++2b") || 1399 Std->containsValue("c++26") || Std->containsValue("c++2c") || 1400 Std->containsValue("c++latest")); 1401 1402 // Process -fmodule-header{=} flags. 1403 if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ, 1404 options::OPT_fmodule_header)) { 1405 // These flags force C++20 handling of headers. 1406 ModulesModeCXX20 = true; 1407 if (A->getOption().matches(options::OPT_fmodule_header)) 1408 CXX20HeaderType = HeaderMode_Default; 1409 else { 1410 StringRef ArgName = A->getValue(); 1411 unsigned Kind = llvm::StringSwitch<unsigned>(ArgName) 1412 .Case("user", HeaderMode_User) 1413 .Case("system", HeaderMode_System) 1414 .Default(~0U); 1415 if (Kind == ~0U) { 1416 Diags.Report(diag::err_drv_invalid_value) 1417 << A->getAsString(Args) << ArgName; 1418 } else 1419 CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind); 1420 } 1421 } 1422 1423 std::unique_ptr<llvm::opt::InputArgList> UArgs = 1424 std::make_unique<InputArgList>(std::move(Args)); 1425 1426 // Perform the default argument translations. 1427 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs); 1428 1429 // Owned by the host. 1430 const ToolChain &TC = getToolChain( 1431 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs)); 1432 1433 if (TC.getTriple().isAndroid()) { 1434 llvm::Triple Triple = TC.getTriple(); 1435 StringRef TripleVersionName = Triple.getEnvironmentVersionString(); 1436 1437 if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "") { 1438 Diags.Report(diag::err_drv_triple_version_invalid) 1439 << TripleVersionName << TC.getTripleString(); 1440 ContainsError = true; 1441 } 1442 } 1443 1444 // Report warning when arm64EC option is overridden by specified target 1445 if ((TC.getTriple().getArch() != llvm::Triple::aarch64 || 1446 TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) && 1447 UArgs->hasArg(options::OPT__SLASH_arm64EC)) { 1448 getDiags().Report(clang::diag::warn_target_override_arm64ec) 1449 << TC.getTriple().str(); 1450 } 1451 1452 // A common user mistake is specifying a target of aarch64-none-eabi or 1453 // arm-none-elf whereas the correct names are aarch64-none-elf & 1454 // arm-none-eabi. Detect these cases and issue a warning. 1455 if (TC.getTriple().getOS() == llvm::Triple::UnknownOS && 1456 TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) { 1457 switch (TC.getTriple().getArch()) { 1458 case llvm::Triple::arm: 1459 case llvm::Triple::armeb: 1460 case llvm::Triple::thumb: 1461 case llvm::Triple::thumbeb: 1462 if (TC.getTriple().getEnvironmentName() == "elf") { 1463 Diag(diag::warn_target_unrecognized_env) 1464 << TargetTriple 1465 << (TC.getTriple().getArchName().str() + "-none-eabi"); 1466 } 1467 break; 1468 case llvm::Triple::aarch64: 1469 case llvm::Triple::aarch64_be: 1470 case llvm::Triple::aarch64_32: 1471 if (TC.getTriple().getEnvironmentName().starts_with("eabi")) { 1472 Diag(diag::warn_target_unrecognized_env) 1473 << TargetTriple 1474 << (TC.getTriple().getArchName().str() + "-none-elf"); 1475 } 1476 break; 1477 default: 1478 break; 1479 } 1480 } 1481 1482 // The compilation takes ownership of Args. 1483 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs, 1484 ContainsError); 1485 1486 if (!HandleImmediateArgs(*C)) 1487 return C; 1488 1489 // Construct the list of inputs. 1490 InputList Inputs; 1491 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 1492 1493 // Populate the tool chains for the offloading devices, if any. 1494 CreateOffloadingDeviceToolChains(*C, Inputs); 1495 1496 // Construct the list of abstract actions to perform for this compilation. On 1497 // MachO targets this uses the driver-driver and universal actions. 1498 if (TC.getTriple().isOSBinFormatMachO()) 1499 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs); 1500 else 1501 BuildActions(*C, C->getArgs(), Inputs, C->getActions()); 1502 1503 if (CCCPrintPhases) { 1504 PrintActions(*C); 1505 return C; 1506 } 1507 1508 BuildJobs(*C); 1509 1510 return C; 1511 } 1512 1513 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { 1514 llvm::opt::ArgStringList ASL; 1515 for (const auto *A : Args) { 1516 // Use user's original spelling of flags. For example, use 1517 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user 1518 // wrote the former. 1519 while (A->getAlias()) 1520 A = A->getAlias(); 1521 A->render(Args, ASL); 1522 } 1523 1524 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { 1525 if (I != ASL.begin()) 1526 OS << ' '; 1527 llvm::sys::printArg(OS, *I, true); 1528 } 1529 OS << '\n'; 1530 } 1531 1532 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename, 1533 SmallString<128> &CrashDiagDir) { 1534 using namespace llvm::sys; 1535 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() && 1536 "Only knows about .crash files on Darwin"); 1537 1538 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/ 1539 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern 1540 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash. 1541 path::home_directory(CrashDiagDir); 1542 if (CrashDiagDir.starts_with("/var/root")) 1543 CrashDiagDir = "/"; 1544 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports"); 1545 int PID = 1546 #if LLVM_ON_UNIX 1547 getpid(); 1548 #else 1549 0; 1550 #endif 1551 std::error_code EC; 1552 fs::file_status FileStatus; 1553 TimePoint<> LastAccessTime; 1554 SmallString<128> CrashFilePath; 1555 // Lookup the .crash files and get the one generated by a subprocess spawned 1556 // by this driver invocation. 1557 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd; 1558 File != FileEnd && !EC; File.increment(EC)) { 1559 StringRef FileName = path::filename(File->path()); 1560 if (!FileName.starts_with(Name)) 1561 continue; 1562 if (fs::status(File->path(), FileStatus)) 1563 continue; 1564 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile = 1565 llvm::MemoryBuffer::getFile(File->path()); 1566 if (!CrashFile) 1567 continue; 1568 // The first line should start with "Process:", otherwise this isn't a real 1569 // .crash file. 1570 StringRef Data = CrashFile.get()->getBuffer(); 1571 if (!Data.starts_with("Process:")) 1572 continue; 1573 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]" 1574 size_t ParentProcPos = Data.find("Parent Process:"); 1575 if (ParentProcPos == StringRef::npos) 1576 continue; 1577 size_t LineEnd = Data.find_first_of("\n", ParentProcPos); 1578 if (LineEnd == StringRef::npos) 1579 continue; 1580 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim(); 1581 int OpenBracket = -1, CloseBracket = -1; 1582 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) { 1583 if (ParentProcess[i] == '[') 1584 OpenBracket = i; 1585 if (ParentProcess[i] == ']') 1586 CloseBracket = i; 1587 } 1588 // Extract the parent process PID from the .crash file and check whether 1589 // it matches this driver invocation pid. 1590 int CrashPID; 1591 if (OpenBracket < 0 || CloseBracket < 0 || 1592 ParentProcess.slice(OpenBracket + 1, CloseBracket) 1593 .getAsInteger(10, CrashPID) || CrashPID != PID) { 1594 continue; 1595 } 1596 1597 // Found a .crash file matching the driver pid. To avoid getting an older 1598 // and misleading crash file, continue looking for the most recent. 1599 // FIXME: the driver can dispatch multiple cc1 invocations, leading to 1600 // multiple crashes poiting to the same parent process. Since the driver 1601 // does not collect pid information for the dispatched invocation there's 1602 // currently no way to distinguish among them. 1603 const auto FileAccessTime = FileStatus.getLastModificationTime(); 1604 if (FileAccessTime > LastAccessTime) { 1605 CrashFilePath.assign(File->path()); 1606 LastAccessTime = FileAccessTime; 1607 } 1608 } 1609 1610 // If found, copy it over to the location of other reproducer files. 1611 if (!CrashFilePath.empty()) { 1612 EC = fs::copy_file(CrashFilePath, ReproCrashFilename); 1613 if (EC) 1614 return false; 1615 return true; 1616 } 1617 1618 return false; 1619 } 1620 1621 static const char BugReporMsg[] = 1622 "\n********************\n\n" 1623 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 1624 "Preprocessed source(s) and associated run script(s) are located at:"; 1625 1626 // When clang crashes, produce diagnostic information including the fully 1627 // preprocessed source file(s). Request that the developer attach the 1628 // diagnostic information to a bug report. 1629 void Driver::generateCompilationDiagnostics( 1630 Compilation &C, const Command &FailingCommand, 1631 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) { 1632 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 1633 return; 1634 1635 unsigned Level = 1; 1636 if (Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_EQ)) { 1637 Level = llvm::StringSwitch<unsigned>(A->getValue()) 1638 .Case("off", 0) 1639 .Case("compiler", 1) 1640 .Case("all", 2) 1641 .Default(1); 1642 } 1643 if (!Level) 1644 return; 1645 1646 // Don't try to generate diagnostics for dsymutil jobs. 1647 if (FailingCommand.getCreator().isDsymutilJob()) 1648 return; 1649 1650 bool IsLLD = false; 1651 ArgStringList SavedTemps; 1652 if (FailingCommand.getCreator().isLinkJob()) { 1653 C.getDefaultToolChain().GetLinkerPath(&IsLLD); 1654 if (!IsLLD || Level < 2) 1655 return; 1656 1657 // If lld crashed, we will re-run the same command with the input it used 1658 // to have. In that case we should not remove temp files in 1659 // initCompilationForDiagnostics yet. They will be added back and removed 1660 // later. 1661 SavedTemps = std::move(C.getTempFiles()); 1662 assert(!C.getTempFiles().size()); 1663 } 1664 1665 // Print the version of the compiler. 1666 PrintVersion(C, llvm::errs()); 1667 1668 // Suppress driver output and emit preprocessor output to temp file. 1669 CCGenDiagnostics = true; 1670 1671 // Save the original job command(s). 1672 Command Cmd = FailingCommand; 1673 1674 // Keep track of whether we produce any errors while trying to produce 1675 // preprocessed sources. 1676 DiagnosticErrorTrap Trap(Diags); 1677 1678 // Suppress tool output. 1679 C.initCompilationForDiagnostics(); 1680 1681 // If lld failed, rerun it again with --reproduce. 1682 if (IsLLD) { 1683 const char *TmpName = CreateTempFile(C, "linker-crash", "tar"); 1684 Command NewLLDInvocation = Cmd; 1685 llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments(); 1686 StringRef ReproduceOption = 1687 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() 1688 ? "/reproduce:" 1689 : "--reproduce="; 1690 ArgList.push_back(Saver.save(Twine(ReproduceOption) + TmpName).data()); 1691 NewLLDInvocation.replaceArguments(std::move(ArgList)); 1692 1693 // Redirect stdout/stderr to /dev/null. 1694 NewLLDInvocation.Execute({std::nullopt, {""}, {""}}, nullptr, nullptr); 1695 Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg; 1696 Diag(clang::diag::note_drv_command_failed_diag_msg) << TmpName; 1697 Diag(clang::diag::note_drv_command_failed_diag_msg) 1698 << "\n\n********************"; 1699 if (Report) 1700 Report->TemporaryFiles.push_back(TmpName); 1701 return; 1702 } 1703 1704 // Construct the list of inputs. 1705 InputList Inputs; 1706 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 1707 1708 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 1709 bool IgnoreInput = false; 1710 1711 // Ignore input from stdin or any inputs that cannot be preprocessed. 1712 // Check type first as not all linker inputs have a value. 1713 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 1714 IgnoreInput = true; 1715 } else if (!strcmp(it->second->getValue(), "-")) { 1716 Diag(clang::diag::note_drv_command_failed_diag_msg) 1717 << "Error generating preprocessed source(s) - " 1718 "ignoring input from stdin."; 1719 IgnoreInput = true; 1720 } 1721 1722 if (IgnoreInput) { 1723 it = Inputs.erase(it); 1724 ie = Inputs.end(); 1725 } else { 1726 ++it; 1727 } 1728 } 1729 1730 if (Inputs.empty()) { 1731 Diag(clang::diag::note_drv_command_failed_diag_msg) 1732 << "Error generating preprocessed source(s) - " 1733 "no preprocessable inputs."; 1734 return; 1735 } 1736 1737 // Don't attempt to generate preprocessed files if multiple -arch options are 1738 // used, unless they're all duplicates. 1739 llvm::StringSet<> ArchNames; 1740 for (const Arg *A : C.getArgs()) { 1741 if (A->getOption().matches(options::OPT_arch)) { 1742 StringRef ArchName = A->getValue(); 1743 ArchNames.insert(ArchName); 1744 } 1745 } 1746 if (ArchNames.size() > 1) { 1747 Diag(clang::diag::note_drv_command_failed_diag_msg) 1748 << "Error generating preprocessed source(s) - cannot generate " 1749 "preprocessed source with multiple -arch options."; 1750 return; 1751 } 1752 1753 // Construct the list of abstract actions to perform for this compilation. On 1754 // Darwin OSes this uses the driver-driver and builds universal actions. 1755 const ToolChain &TC = C.getDefaultToolChain(); 1756 if (TC.getTriple().isOSBinFormatMachO()) 1757 BuildUniversalActions(C, TC, Inputs); 1758 else 1759 BuildActions(C, C.getArgs(), Inputs, C.getActions()); 1760 1761 BuildJobs(C); 1762 1763 // If there were errors building the compilation, quit now. 1764 if (Trap.hasErrorOccurred()) { 1765 Diag(clang::diag::note_drv_command_failed_diag_msg) 1766 << "Error generating preprocessed source(s)."; 1767 return; 1768 } 1769 1770 // Generate preprocessed output. 1771 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 1772 C.ExecuteJobs(C.getJobs(), FailingCommands); 1773 1774 // If any of the preprocessing commands failed, clean up and exit. 1775 if (!FailingCommands.empty()) { 1776 Diag(clang::diag::note_drv_command_failed_diag_msg) 1777 << "Error generating preprocessed source(s)."; 1778 return; 1779 } 1780 1781 const ArgStringList &TempFiles = C.getTempFiles(); 1782 if (TempFiles.empty()) { 1783 Diag(clang::diag::note_drv_command_failed_diag_msg) 1784 << "Error generating preprocessed source(s)."; 1785 return; 1786 } 1787 1788 Diag(clang::diag::note_drv_command_failed_diag_msg) << BugReporMsg; 1789 1790 SmallString<128> VFS; 1791 SmallString<128> ReproCrashFilename; 1792 for (const char *TempFile : TempFiles) { 1793 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 1794 if (Report) 1795 Report->TemporaryFiles.push_back(TempFile); 1796 if (ReproCrashFilename.empty()) { 1797 ReproCrashFilename = TempFile; 1798 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash"); 1799 } 1800 if (StringRef(TempFile).ends_with(".cache")) { 1801 // In some cases (modules) we'll dump extra data to help with reproducing 1802 // the crash into a directory next to the output. 1803 VFS = llvm::sys::path::filename(TempFile); 1804 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 1805 } 1806 } 1807 1808 for (const char *TempFile : SavedTemps) 1809 C.addTempFile(TempFile); 1810 1811 // Assume associated files are based off of the first temporary file. 1812 CrashReportInfo CrashInfo(TempFiles[0], VFS); 1813 1814 llvm::SmallString<128> Script(CrashInfo.Filename); 1815 llvm::sys::path::replace_extension(Script, "sh"); 1816 std::error_code EC; 1817 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew, 1818 llvm::sys::fs::FA_Write, 1819 llvm::sys::fs::OF_Text); 1820 if (EC) { 1821 Diag(clang::diag::note_drv_command_failed_diag_msg) 1822 << "Error generating run script: " << Script << " " << EC.message(); 1823 } else { 1824 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" 1825 << "# Driver args: "; 1826 printArgList(ScriptOS, C.getInputArgs()); 1827 ScriptOS << "# Original command: "; 1828 Cmd.Print(ScriptOS, "\n", /*Quote=*/true); 1829 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 1830 if (!AdditionalInformation.empty()) 1831 ScriptOS << "\n# Additional information: " << AdditionalInformation 1832 << "\n"; 1833 if (Report) 1834 Report->TemporaryFiles.push_back(std::string(Script.str())); 1835 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 1836 } 1837 1838 // On darwin, provide information about the .crash diagnostic report. 1839 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) { 1840 SmallString<128> CrashDiagDir; 1841 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) { 1842 Diag(clang::diag::note_drv_command_failed_diag_msg) 1843 << ReproCrashFilename.str(); 1844 } else { // Suggest a directory for the user to look for .crash files. 1845 llvm::sys::path::append(CrashDiagDir, Name); 1846 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash"; 1847 Diag(clang::diag::note_drv_command_failed_diag_msg) 1848 << "Crash backtrace is located in"; 1849 Diag(clang::diag::note_drv_command_failed_diag_msg) 1850 << CrashDiagDir.str(); 1851 Diag(clang::diag::note_drv_command_failed_diag_msg) 1852 << "(choose the .crash file that corresponds to your crash)"; 1853 } 1854 } 1855 1856 Diag(clang::diag::note_drv_command_failed_diag_msg) 1857 << "\n\n********************"; 1858 } 1859 1860 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { 1861 // Since commandLineFitsWithinSystemLimits() may underestimate system's 1862 // capacity if the tool does not support response files, there is a chance/ 1863 // that things will just work without a response file, so we silently just 1864 // skip it. 1865 if (Cmd.getResponseFileSupport().ResponseKind == 1866 ResponseFileSupport::RF_None || 1867 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), 1868 Cmd.getArguments())) 1869 return; 1870 1871 std::string TmpName = GetTemporaryPath("response", "txt"); 1872 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName))); 1873 } 1874 1875 int Driver::ExecuteCompilation( 1876 Compilation &C, 1877 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { 1878 if (C.getArgs().hasArg(options::OPT_fdriver_only)) { 1879 if (C.getArgs().hasArg(options::OPT_v)) 1880 C.getJobs().Print(llvm::errs(), "\n", true); 1881 1882 C.ExecuteJobs(C.getJobs(), FailingCommands, /*LogOnly=*/true); 1883 1884 // If there were errors building the compilation, quit now. 1885 if (!FailingCommands.empty() || Diags.hasErrorOccurred()) 1886 return 1; 1887 1888 return 0; 1889 } 1890 1891 // Just print if -### was present. 1892 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 1893 C.getJobs().Print(llvm::errs(), "\n", true); 1894 return Diags.hasErrorOccurred() ? 1 : 0; 1895 } 1896 1897 // If there were errors building the compilation, quit now. 1898 if (Diags.hasErrorOccurred()) 1899 return 1; 1900 1901 // Set up response file names for each command, if necessary. 1902 for (auto &Job : C.getJobs()) 1903 setUpResponseFiles(C, Job); 1904 1905 C.ExecuteJobs(C.getJobs(), FailingCommands); 1906 1907 // If the command succeeded, we are done. 1908 if (FailingCommands.empty()) 1909 return 0; 1910 1911 // Otherwise, remove result files and print extra information about abnormal 1912 // failures. 1913 int Res = 0; 1914 for (const auto &CmdPair : FailingCommands) { 1915 int CommandRes = CmdPair.first; 1916 const Command *FailingCommand = CmdPair.second; 1917 1918 // Remove result files if we're not saving temps. 1919 if (!isSaveTempsEnabled()) { 1920 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 1921 C.CleanupFileMap(C.getResultFiles(), JA, true); 1922 1923 // Failure result files are valid unless we crashed. 1924 if (CommandRes < 0) 1925 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 1926 } 1927 1928 // llvm/lib/Support/*/Signals.inc will exit with a special return code 1929 // for SIGPIPE. Do not print diagnostics for this case. 1930 if (CommandRes == EX_IOERR) { 1931 Res = CommandRes; 1932 continue; 1933 } 1934 1935 // Print extra information about abnormal failures, if possible. 1936 // 1937 // This is ad-hoc, but we don't want to be excessively noisy. If the result 1938 // status was 1, assume the command failed normally. In particular, if it 1939 // was the compiler then assume it gave a reasonable error code. Failures 1940 // in other tools are less common, and they generally have worse 1941 // diagnostics, so always print the diagnostic there. 1942 const Tool &FailingTool = FailingCommand->getCreator(); 1943 1944 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) { 1945 // FIXME: See FIXME above regarding result code interpretation. 1946 if (CommandRes < 0) 1947 Diag(clang::diag::err_drv_command_signalled) 1948 << FailingTool.getShortName(); 1949 else 1950 Diag(clang::diag::err_drv_command_failed) 1951 << FailingTool.getShortName() << CommandRes; 1952 } 1953 } 1954 return Res; 1955 } 1956 1957 void Driver::PrintHelp(bool ShowHidden) const { 1958 llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(); 1959 1960 std::string Usage = llvm::formatv("{0} [options] file...", Name).str(); 1961 getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(), 1962 ShowHidden, /*ShowAllAliases=*/false, 1963 VisibilityMask); 1964 } 1965 1966 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 1967 if (IsFlangMode()) { 1968 OS << getClangToolFullVersion("flang-new") << '\n'; 1969 } else { 1970 // FIXME: The following handlers should use a callback mechanism, we don't 1971 // know what the client would like to do. 1972 OS << getClangFullVersion() << '\n'; 1973 } 1974 const ToolChain &TC = C.getDefaultToolChain(); 1975 OS << "Target: " << TC.getTripleString() << '\n'; 1976 1977 // Print the threading model. 1978 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 1979 // Don't print if the ToolChain would have barfed on it already 1980 if (TC.isThreadModelSupported(A->getValue())) 1981 OS << "Thread model: " << A->getValue(); 1982 } else 1983 OS << "Thread model: " << TC.getThreadModel(); 1984 OS << '\n'; 1985 1986 // Print out the install directory. 1987 OS << "InstalledDir: " << InstalledDir << '\n'; 1988 1989 // If configuration files were used, print their paths. 1990 for (auto ConfigFile : ConfigFiles) 1991 OS << "Configuration file: " << ConfigFile << '\n'; 1992 } 1993 1994 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 1995 /// option. 1996 static void PrintDiagnosticCategories(raw_ostream &OS) { 1997 // Skip the empty category. 1998 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; 1999 ++i) 2000 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 2001 } 2002 2003 void Driver::HandleAutocompletions(StringRef PassedFlags) const { 2004 if (PassedFlags == "") 2005 return; 2006 // Print out all options that start with a given argument. This is used for 2007 // shell autocompletion. 2008 std::vector<std::string> SuggestedCompletions; 2009 std::vector<std::string> Flags; 2010 2011 llvm::opt::Visibility VisibilityMask(options::ClangOption); 2012 2013 // Make sure that Flang-only options don't pollute the Clang output 2014 // TODO: Make sure that Clang-only options don't pollute Flang output 2015 if (IsFlangMode()) 2016 VisibilityMask = llvm::opt::Visibility(options::FlangOption); 2017 2018 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag," 2019 // because the latter indicates that the user put space before pushing tab 2020 // which should end up in a file completion. 2021 const bool HasSpace = PassedFlags.ends_with(","); 2022 2023 // Parse PassedFlags by "," as all the command-line flags are passed to this 2024 // function separated by "," 2025 StringRef TargetFlags = PassedFlags; 2026 while (TargetFlags != "") { 2027 StringRef CurFlag; 2028 std::tie(CurFlag, TargetFlags) = TargetFlags.split(","); 2029 Flags.push_back(std::string(CurFlag)); 2030 } 2031 2032 // We want to show cc1-only options only when clang is invoked with -cc1 or 2033 // -Xclang. 2034 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1")) 2035 VisibilityMask = llvm::opt::Visibility(options::CC1Option); 2036 2037 const llvm::opt::OptTable &Opts = getOpts(); 2038 StringRef Cur; 2039 Cur = Flags.at(Flags.size() - 1); 2040 StringRef Prev; 2041 if (Flags.size() >= 2) { 2042 Prev = Flags.at(Flags.size() - 2); 2043 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur); 2044 } 2045 2046 if (SuggestedCompletions.empty()) 2047 SuggestedCompletions = Opts.suggestValueCompletions(Cur, ""); 2048 2049 // If Flags were empty, it means the user typed `clang [tab]` where we should 2050 // list all possible flags. If there was no value completion and the user 2051 // pressed tab after a space, we should fall back to a file completion. 2052 // We're printing a newline to be consistent with what we print at the end of 2053 // this function. 2054 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) { 2055 llvm::outs() << '\n'; 2056 return; 2057 } 2058 2059 // When flag ends with '=' and there was no value completion, return empty 2060 // string and fall back to the file autocompletion. 2061 if (SuggestedCompletions.empty() && !Cur.ends_with("=")) { 2062 // If the flag is in the form of "--autocomplete=-foo", 2063 // we were requested to print out all option names that start with "-foo". 2064 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only". 2065 SuggestedCompletions = Opts.findByPrefix( 2066 Cur, VisibilityMask, 2067 /*DisableFlags=*/options::Unsupported | options::Ignored); 2068 2069 // We have to query the -W flags manually as they're not in the OptTable. 2070 // TODO: Find a good way to add them to OptTable instead and them remove 2071 // this code. 2072 for (StringRef S : DiagnosticIDs::getDiagnosticFlags()) 2073 if (S.starts_with(Cur)) 2074 SuggestedCompletions.push_back(std::string(S)); 2075 } 2076 2077 // Sort the autocomplete candidates so that shells print them out in a 2078 // deterministic order. We could sort in any way, but we chose 2079 // case-insensitive sorting for consistency with the -help option 2080 // which prints out options in the case-insensitive alphabetical order. 2081 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) { 2082 if (int X = A.compare_insensitive(B)) 2083 return X < 0; 2084 return A.compare(B) > 0; 2085 }); 2086 2087 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n'; 2088 } 2089 2090 bool Driver::HandleImmediateArgs(const Compilation &C) { 2091 // The order these options are handled in gcc is all over the place, but we 2092 // don't expect inconsistencies w.r.t. that to matter in practice. 2093 2094 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 2095 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 2096 return false; 2097 } 2098 2099 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 2100 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 2101 // return an answer which matches our definition of __VERSION__. 2102 llvm::outs() << CLANG_VERSION_STRING << "\n"; 2103 return false; 2104 } 2105 2106 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 2107 PrintDiagnosticCategories(llvm::outs()); 2108 return false; 2109 } 2110 2111 if (C.getArgs().hasArg(options::OPT_help) || 2112 C.getArgs().hasArg(options::OPT__help_hidden)) { 2113 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 2114 return false; 2115 } 2116 2117 if (C.getArgs().hasArg(options::OPT__version)) { 2118 // Follow gcc behavior and use stdout for --version and stderr for -v. 2119 PrintVersion(C, llvm::outs()); 2120 return false; 2121 } 2122 2123 if (C.getArgs().hasArg(options::OPT_v) || 2124 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) || 2125 C.getArgs().hasArg(options::OPT_print_supported_cpus) || 2126 C.getArgs().hasArg(options::OPT_print_supported_extensions)) { 2127 PrintVersion(C, llvm::errs()); 2128 SuppressMissingInputWarning = true; 2129 } 2130 2131 if (C.getArgs().hasArg(options::OPT_v)) { 2132 if (!SystemConfigDir.empty()) 2133 llvm::errs() << "System configuration file directory: " 2134 << SystemConfigDir << "\n"; 2135 if (!UserConfigDir.empty()) 2136 llvm::errs() << "User configuration file directory: " 2137 << UserConfigDir << "\n"; 2138 } 2139 2140 const ToolChain &TC = C.getDefaultToolChain(); 2141 2142 if (C.getArgs().hasArg(options::OPT_v)) 2143 TC.printVerboseInfo(llvm::errs()); 2144 2145 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) { 2146 llvm::outs() << ResourceDir << '\n'; 2147 return false; 2148 } 2149 2150 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 2151 llvm::outs() << "programs: ="; 2152 bool separator = false; 2153 // Print -B and COMPILER_PATH. 2154 for (const std::string &Path : PrefixDirs) { 2155 if (separator) 2156 llvm::outs() << llvm::sys::EnvPathSeparator; 2157 llvm::outs() << Path; 2158 separator = true; 2159 } 2160 for (const std::string &Path : TC.getProgramPaths()) { 2161 if (separator) 2162 llvm::outs() << llvm::sys::EnvPathSeparator; 2163 llvm::outs() << Path; 2164 separator = true; 2165 } 2166 llvm::outs() << "\n"; 2167 llvm::outs() << "libraries: =" << ResourceDir; 2168 2169 StringRef sysroot = C.getSysRoot(); 2170 2171 for (const std::string &Path : TC.getFilePaths()) { 2172 // Always print a separator. ResourceDir was the first item shown. 2173 llvm::outs() << llvm::sys::EnvPathSeparator; 2174 // Interpretation of leading '=' is needed only for NetBSD. 2175 if (Path[0] == '=') 2176 llvm::outs() << sysroot << Path.substr(1); 2177 else 2178 llvm::outs() << Path; 2179 } 2180 llvm::outs() << "\n"; 2181 return false; 2182 } 2183 2184 if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) { 2185 if (std::optional<std::string> RuntimePath = TC.getRuntimePath()) 2186 llvm::outs() << *RuntimePath << '\n'; 2187 else 2188 llvm::outs() << TC.getCompilerRTPath() << '\n'; 2189 return false; 2190 } 2191 2192 if (C.getArgs().hasArg(options::OPT_print_diagnostic_options)) { 2193 std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags(); 2194 for (std::size_t I = 0; I != Flags.size(); I += 2) 2195 llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n"; 2196 return false; 2197 } 2198 2199 // FIXME: The following handlers should use a callback mechanism, we don't 2200 // know what the client would like to do. 2201 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 2202 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 2203 return false; 2204 } 2205 2206 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 2207 StringRef ProgName = A->getValue(); 2208 2209 // Null program name cannot have a path. 2210 if (! ProgName.empty()) 2211 llvm::outs() << GetProgramPath(ProgName, TC); 2212 2213 llvm::outs() << "\n"; 2214 return false; 2215 } 2216 2217 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) { 2218 StringRef PassedFlags = A->getValue(); 2219 HandleAutocompletions(PassedFlags); 2220 return false; 2221 } 2222 2223 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 2224 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs()); 2225 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs())); 2226 RegisterEffectiveTriple TripleRAII(TC, Triple); 2227 switch (RLT) { 2228 case ToolChain::RLT_CompilerRT: 2229 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n"; 2230 break; 2231 case ToolChain::RLT_Libgcc: 2232 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 2233 break; 2234 } 2235 return false; 2236 } 2237 2238 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 2239 for (const Multilib &Multilib : TC.getMultilibs()) 2240 llvm::outs() << Multilib << "\n"; 2241 return false; 2242 } 2243 2244 if (C.getArgs().hasArg(options::OPT_print_multi_flags)) { 2245 Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs()); 2246 llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags); 2247 std::set<llvm::StringRef> SortedFlags; 2248 for (const auto &FlagEntry : ExpandedFlags) 2249 SortedFlags.insert(FlagEntry.getKey()); 2250 for (auto Flag : SortedFlags) 2251 llvm::outs() << Flag << '\n'; 2252 return false; 2253 } 2254 2255 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 2256 for (const Multilib &Multilib : TC.getSelectedMultilibs()) { 2257 if (Multilib.gccSuffix().empty()) 2258 llvm::outs() << ".\n"; 2259 else { 2260 StringRef Suffix(Multilib.gccSuffix()); 2261 assert(Suffix.front() == '/'); 2262 llvm::outs() << Suffix.substr(1) << "\n"; 2263 } 2264 } 2265 return false; 2266 } 2267 2268 if (C.getArgs().hasArg(options::OPT_print_target_triple)) { 2269 llvm::outs() << TC.getTripleString() << "\n"; 2270 return false; 2271 } 2272 2273 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) { 2274 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs())); 2275 llvm::outs() << Triple.getTriple() << "\n"; 2276 return false; 2277 } 2278 2279 if (C.getArgs().hasArg(options::OPT_print_targets)) { 2280 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs()); 2281 return false; 2282 } 2283 2284 return true; 2285 } 2286 2287 enum { 2288 TopLevelAction = 0, 2289 HeadSibAction = 1, 2290 OtherSibAction = 2, 2291 }; 2292 2293 // Display an action graph human-readably. Action A is the "sink" node 2294 // and latest-occuring action. Traversal is in pre-order, visiting the 2295 // inputs to each action before printing the action itself. 2296 static unsigned PrintActions1(const Compilation &C, Action *A, 2297 std::map<Action *, unsigned> &Ids, 2298 Twine Indent = {}, int Kind = TopLevelAction) { 2299 if (Ids.count(A)) // A was already visited. 2300 return Ids[A]; 2301 2302 std::string str; 2303 llvm::raw_string_ostream os(str); 2304 2305 auto getSibIndent = [](int K) -> Twine { 2306 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : ""; 2307 }; 2308 2309 Twine SibIndent = Indent + getSibIndent(Kind); 2310 int SibKind = HeadSibAction; 2311 os << Action::getClassName(A->getKind()) << ", "; 2312 if (InputAction *IA = dyn_cast<InputAction>(A)) { 2313 os << "\"" << IA->getInputArg().getValue() << "\""; 2314 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 2315 os << '"' << BIA->getArchName() << '"' << ", {" 2316 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}"; 2317 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 2318 bool IsFirst = true; 2319 OA->doOnEachDependence( 2320 [&](Action *A, const ToolChain *TC, const char *BoundArch) { 2321 assert(TC && "Unknown host toolchain"); 2322 // E.g. for two CUDA device dependences whose bound arch is sm_20 and 2323 // sm_35 this will generate: 2324 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device" 2325 // (nvptx64-nvidia-cuda:sm_35) {#ID} 2326 if (!IsFirst) 2327 os << ", "; 2328 os << '"'; 2329 os << A->getOffloadingKindPrefix(); 2330 os << " ("; 2331 os << TC->getTriple().normalize(); 2332 if (BoundArch) 2333 os << ":" << BoundArch; 2334 os << ")"; 2335 os << '"'; 2336 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}"; 2337 IsFirst = false; 2338 SibKind = OtherSibAction; 2339 }); 2340 } else { 2341 const ActionList *AL = &A->getInputs(); 2342 2343 if (AL->size()) { 2344 const char *Prefix = "{"; 2345 for (Action *PreRequisite : *AL) { 2346 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind); 2347 Prefix = ", "; 2348 SibKind = OtherSibAction; 2349 } 2350 os << "}"; 2351 } else 2352 os << "{}"; 2353 } 2354 2355 // Append offload info for all options other than the offloading action 2356 // itself (e.g. (cuda-device, sm_20) or (cuda-host)). 2357 std::string offload_str; 2358 llvm::raw_string_ostream offload_os(offload_str); 2359 if (!isa<OffloadAction>(A)) { 2360 auto S = A->getOffloadingKindPrefix(); 2361 if (!S.empty()) { 2362 offload_os << ", (" << S; 2363 if (A->getOffloadingArch()) 2364 offload_os << ", " << A->getOffloadingArch(); 2365 offload_os << ")"; 2366 } 2367 } 2368 2369 auto getSelfIndent = [](int K) -> Twine { 2370 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : ""; 2371 }; 2372 2373 unsigned Id = Ids.size(); 2374 Ids[A] = Id; 2375 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", " 2376 << types::getTypeName(A->getType()) << offload_os.str() << "\n"; 2377 2378 return Id; 2379 } 2380 2381 // Print the action graphs in a compilation C. 2382 // For example "clang -c file1.c file2.c" is composed of two subgraphs. 2383 void Driver::PrintActions(const Compilation &C) const { 2384 std::map<Action *, unsigned> Ids; 2385 for (Action *A : C.getActions()) 2386 PrintActions1(C, A, Ids); 2387 } 2388 2389 /// Check whether the given input tree contains any compilation or 2390 /// assembly actions. 2391 static bool ContainsCompileOrAssembleAction(const Action *A) { 2392 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) || 2393 isa<AssembleJobAction>(A)) 2394 return true; 2395 2396 return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction); 2397 } 2398 2399 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, 2400 const InputList &BAInputs) const { 2401 DerivedArgList &Args = C.getArgs(); 2402 ActionList &Actions = C.getActions(); 2403 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 2404 // Collect the list of architectures. Duplicates are allowed, but should only 2405 // be handled once (in the order seen). 2406 llvm::StringSet<> ArchNames; 2407 SmallVector<const char *, 4> Archs; 2408 for (Arg *A : Args) { 2409 if (A->getOption().matches(options::OPT_arch)) { 2410 // Validate the option here; we don't save the type here because its 2411 // particular spelling may participate in other driver choices. 2412 llvm::Triple::ArchType Arch = 2413 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 2414 if (Arch == llvm::Triple::UnknownArch) { 2415 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); 2416 continue; 2417 } 2418 2419 A->claim(); 2420 if (ArchNames.insert(A->getValue()).second) 2421 Archs.push_back(A->getValue()); 2422 } 2423 } 2424 2425 // When there is no explicit arch for this platform, make sure we still bind 2426 // the architecture (to the default) so that -Xarch_ is handled correctly. 2427 if (!Archs.size()) 2428 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 2429 2430 ActionList SingleActions; 2431 BuildActions(C, Args, BAInputs, SingleActions); 2432 2433 // Add in arch bindings for every top level action, as well as lipo and 2434 // dsymutil steps if needed. 2435 for (Action* Act : SingleActions) { 2436 // Make sure we can lipo this kind of output. If not (and it is an actual 2437 // output) then we disallow, since we can't create an output file with the 2438 // right name without overwriting it. We could remove this oddity by just 2439 // changing the output names to include the arch, which would also fix 2440 // -save-temps. Compatibility wins for now. 2441 2442 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 2443 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 2444 << types::getTypeName(Act->getType()); 2445 2446 ActionList Inputs; 2447 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 2448 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i])); 2449 2450 // Lipo if necessary, we do it this way because we need to set the arch flag 2451 // so that -Xarch_ gets overwritten. 2452 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 2453 Actions.append(Inputs.begin(), Inputs.end()); 2454 else 2455 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType())); 2456 2457 // Handle debug info queries. 2458 Arg *A = Args.getLastArg(options::OPT_g_Group); 2459 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) && 2460 !A->getOption().matches(options::OPT_gstabs); 2461 if ((enablesDebugInfo || willEmitRemarks(Args)) && 2462 ContainsCompileOrAssembleAction(Actions.back())) { 2463 2464 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 2465 // have a compile input. We need to run 'dsymutil' ourselves in such cases 2466 // because the debug info will refer to a temporary object file which 2467 // will be removed at the end of the compilation process. 2468 if (Act->getType() == types::TY_Image) { 2469 ActionList Inputs; 2470 Inputs.push_back(Actions.back()); 2471 Actions.pop_back(); 2472 Actions.push_back( 2473 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM)); 2474 } 2475 2476 // Verify the debug info output. 2477 if (Args.hasArg(options::OPT_verify_debug_info)) { 2478 Action* LastAction = Actions.back(); 2479 Actions.pop_back(); 2480 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>( 2481 LastAction, types::TY_Nothing)); 2482 } 2483 } 2484 } 2485 } 2486 2487 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value, 2488 types::ID Ty, bool TypoCorrect) const { 2489 if (!getCheckInputsExist()) 2490 return true; 2491 2492 // stdin always exists. 2493 if (Value == "-") 2494 return true; 2495 2496 // If it's a header to be found in the system or user search path, then defer 2497 // complaints about its absence until those searches can be done. When we 2498 // are definitely processing headers for C++20 header units, extend this to 2499 // allow the user to put "-fmodule-header -xc++-header vector" for example. 2500 if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader || 2501 (ModulesModeCXX20 && Ty == types::TY_CXXHeader)) 2502 return true; 2503 2504 if (getVFS().exists(Value)) 2505 return true; 2506 2507 if (TypoCorrect) { 2508 // Check if the filename is a typo for an option flag. OptTable thinks 2509 // that all args that are not known options and that start with / are 2510 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for 2511 // the option `/diagnostics:caret` than a reference to a file in the root 2512 // directory. 2513 std::string Nearest; 2514 if (getOpts().findNearest(Value, Nearest, getOptionVisibilityMask()) <= 1) { 2515 Diag(clang::diag::err_drv_no_such_file_with_suggestion) 2516 << Value << Nearest; 2517 return false; 2518 } 2519 } 2520 2521 // In CL mode, don't error on apparently non-existent linker inputs, because 2522 // they can be influenced by linker flags the clang driver might not 2523 // understand. 2524 // Examples: 2525 // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver 2526 // module look for an MSVC installation in the registry. (We could ask 2527 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to 2528 // look in the registry might move into lld-link in the future so that 2529 // lld-link invocations in non-MSVC shells just work too.) 2530 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker, 2531 // including /libpath:, which is used to find .lib and .obj files. 2532 // So do not diagnose this on the driver level. Rely on the linker diagnosing 2533 // it. (If we don't end up invoking the linker, this means we'll emit a 2534 // "'linker' input unused [-Wunused-command-line-argument]" warning instead 2535 // of an error.) 2536 // 2537 // Only do this skip after the typo correction step above. `/Brepo` is treated 2538 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit 2539 // an error if we have a flag that's within an edit distance of 1 from a 2540 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the 2541 // driver in the unlikely case they run into this.) 2542 // 2543 // Don't do this for inputs that start with a '/', else we'd pass options 2544 // like /libpath: through to the linker silently. 2545 // 2546 // Emitting an error for linker inputs can also cause incorrect diagnostics 2547 // with the gcc driver. The command 2548 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o 2549 // will make lld look for some/dir/file.o, while we will diagnose here that 2550 // `/file.o` does not exist. However, configure scripts check if 2551 // `clang /GR-` compiles without error to see if the compiler is cl.exe, 2552 // so we can't downgrade diagnostics for `/GR-` from an error to a warning 2553 // in cc mode. (We can in cl mode because cl.exe itself only warns on 2554 // unknown flags.) 2555 if (IsCLMode() && Ty == types::TY_Object && !Value.starts_with("/")) 2556 return true; 2557 2558 Diag(clang::diag::err_drv_no_such_file) << Value; 2559 return false; 2560 } 2561 2562 // Get the C++20 Header Unit type corresponding to the input type. 2563 static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) { 2564 switch (HM) { 2565 case HeaderMode_User: 2566 return types::TY_CXXUHeader; 2567 case HeaderMode_System: 2568 return types::TY_CXXSHeader; 2569 case HeaderMode_Default: 2570 break; 2571 case HeaderMode_None: 2572 llvm_unreachable("should not be called in this case"); 2573 } 2574 return types::TY_CXXHUHeader; 2575 } 2576 2577 // Construct a the list of inputs and their types. 2578 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 2579 InputList &Inputs) const { 2580 const llvm::opt::OptTable &Opts = getOpts(); 2581 // Track the current user specified (-x) input. We also explicitly track the 2582 // argument used to set the type; we only want to claim the type when we 2583 // actually use it, so we warn about unused -x arguments. 2584 types::ID InputType = types::TY_Nothing; 2585 Arg *InputTypeArg = nullptr; 2586 2587 // The last /TC or /TP option sets the input type to C or C++ globally. 2588 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 2589 options::OPT__SLASH_TP)) { 2590 InputTypeArg = TCTP; 2591 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 2592 ? types::TY_C 2593 : types::TY_CXX; 2594 2595 Arg *Previous = nullptr; 2596 bool ShowNote = false; 2597 for (Arg *A : 2598 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) { 2599 if (Previous) { 2600 Diag(clang::diag::warn_drv_overriding_option) 2601 << Previous->getSpelling() << A->getSpelling(); 2602 ShowNote = true; 2603 } 2604 Previous = A; 2605 } 2606 if (ShowNote) 2607 Diag(clang::diag::note_drv_t_option_is_global); 2608 } 2609 2610 // CUDA/HIP and their preprocessor expansions can be accepted by CL mode. 2611 // Warn -x after last input file has no effect 2612 auto LastXArg = Args.getLastArgValue(options::OPT_x); 2613 const llvm::StringSet<> ValidXArgs = {"cuda", "hip", "cui", "hipi"}; 2614 if (!IsCLMode() || ValidXArgs.contains(LastXArg)) { 2615 Arg *LastXArg = Args.getLastArgNoClaim(options::OPT_x); 2616 Arg *LastInputArg = Args.getLastArgNoClaim(options::OPT_INPUT); 2617 if (LastXArg && LastInputArg && 2618 LastInputArg->getIndex() < LastXArg->getIndex()) 2619 Diag(clang::diag::warn_drv_unused_x) << LastXArg->getValue(); 2620 } else { 2621 // In CL mode suggest /TC or /TP since -x doesn't make sense if passed via 2622 // /clang:. 2623 if (auto *A = Args.getLastArg(options::OPT_x)) 2624 Diag(diag::err_drv_unsupported_opt_with_suggestion) 2625 << A->getAsString(Args) << "/TC' or '/TP"; 2626 } 2627 2628 for (Arg *A : Args) { 2629 if (A->getOption().getKind() == Option::InputClass) { 2630 const char *Value = A->getValue(); 2631 types::ID Ty = types::TY_INVALID; 2632 2633 // Infer the input type if necessary. 2634 if (InputType == types::TY_Nothing) { 2635 // If there was an explicit arg for this, claim it. 2636 if (InputTypeArg) 2637 InputTypeArg->claim(); 2638 2639 // stdin must be handled specially. 2640 if (memcmp(Value, "-", 2) == 0) { 2641 if (IsFlangMode()) { 2642 Ty = types::TY_Fortran; 2643 } else if (IsDXCMode()) { 2644 Ty = types::TY_HLSL; 2645 } else { 2646 // If running with -E, treat as a C input (this changes the 2647 // builtin macros, for example). This may be overridden by -ObjC 2648 // below. 2649 // 2650 // Otherwise emit an error but still use a valid type to avoid 2651 // spurious errors (e.g., no inputs). 2652 assert(!CCGenDiagnostics && "stdin produces no crash reproducer"); 2653 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 2654 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 2655 : clang::diag::err_drv_unknown_stdin_type); 2656 Ty = types::TY_C; 2657 } 2658 } else { 2659 // Otherwise lookup by extension. 2660 // Fallback is C if invoked as C preprocessor, C++ if invoked with 2661 // clang-cl /E, or Object otherwise. 2662 // We use a host hook here because Darwin at least has its own 2663 // idea of what .s is. 2664 if (const char *Ext = strrchr(Value, '.')) 2665 Ty = TC.LookupTypeForExtension(Ext + 1); 2666 2667 if (Ty == types::TY_INVALID) { 2668 if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics)) 2669 Ty = types::TY_CXX; 2670 else if (CCCIsCPP() || CCGenDiagnostics) 2671 Ty = types::TY_C; 2672 else 2673 Ty = types::TY_Object; 2674 } 2675 2676 // If the driver is invoked as C++ compiler (like clang++ or c++) it 2677 // should autodetect some input files as C++ for g++ compatibility. 2678 if (CCCIsCXX()) { 2679 types::ID OldTy = Ty; 2680 Ty = types::lookupCXXTypeForCType(Ty); 2681 2682 // Do not complain about foo.h, when we are known to be processing 2683 // it as a C++20 header unit. 2684 if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode())) 2685 Diag(clang::diag::warn_drv_treating_input_as_cxx) 2686 << getTypeName(OldTy) << getTypeName(Ty); 2687 } 2688 2689 // If running with -fthinlto-index=, extensions that normally identify 2690 // native object files actually identify LLVM bitcode files. 2691 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) && 2692 Ty == types::TY_Object) 2693 Ty = types::TY_LLVM_BC; 2694 } 2695 2696 // -ObjC and -ObjC++ override the default language, but only for "source 2697 // files". We just treat everything that isn't a linker input as a 2698 // source file. 2699 // 2700 // FIXME: Clean this up if we move the phase sequence into the type. 2701 if (Ty != types::TY_Object) { 2702 if (Args.hasArg(options::OPT_ObjC)) 2703 Ty = types::TY_ObjC; 2704 else if (Args.hasArg(options::OPT_ObjCXX)) 2705 Ty = types::TY_ObjCXX; 2706 } 2707 2708 // Disambiguate headers that are meant to be header units from those 2709 // intended to be PCH. Avoid missing '.h' cases that are counted as 2710 // C headers by default - we know we are in C++ mode and we do not 2711 // want to issue a complaint about compiling things in the wrong mode. 2712 if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) && 2713 hasHeaderMode()) 2714 Ty = CXXHeaderUnitType(CXX20HeaderType); 2715 } else { 2716 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 2717 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 2718 // If emulating cl.exe, make sure that /TC and /TP don't affect input 2719 // object files. 2720 const char *Ext = strrchr(Value, '.'); 2721 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 2722 Ty = types::TY_Object; 2723 } 2724 if (Ty == types::TY_INVALID) { 2725 Ty = InputType; 2726 InputTypeArg->claim(); 2727 } 2728 } 2729 2730 if ((Ty == types::TY_C || Ty == types::TY_CXX) && 2731 Args.hasArgNoClaim(options::OPT_hipstdpar)) 2732 Ty = types::TY_HIP; 2733 2734 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true)) 2735 Inputs.push_back(std::make_pair(Ty, A)); 2736 2737 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 2738 StringRef Value = A->getValue(); 2739 if (DiagnoseInputExistence(Args, Value, types::TY_C, 2740 /*TypoCorrect=*/false)) { 2741 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2742 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 2743 } 2744 A->claim(); 2745 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 2746 StringRef Value = A->getValue(); 2747 if (DiagnoseInputExistence(Args, Value, types::TY_CXX, 2748 /*TypoCorrect=*/false)) { 2749 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2750 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 2751 } 2752 A->claim(); 2753 } else if (A->getOption().hasFlag(options::LinkerInput)) { 2754 // Just treat as object type, we could make a special type for this if 2755 // necessary. 2756 Inputs.push_back(std::make_pair(types::TY_Object, A)); 2757 2758 } else if (A->getOption().matches(options::OPT_x)) { 2759 InputTypeArg = A; 2760 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 2761 A->claim(); 2762 2763 // Follow gcc behavior and treat as linker input for invalid -x 2764 // options. Its not clear why we shouldn't just revert to unknown; but 2765 // this isn't very important, we might as well be bug compatible. 2766 if (!InputType) { 2767 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 2768 InputType = types::TY_Object; 2769 } 2770 2771 // If the user has put -fmodule-header{,=} then we treat C++ headers as 2772 // header unit inputs. So we 'promote' -xc++-header appropriately. 2773 if (InputType == types::TY_CXXHeader && hasHeaderMode()) 2774 InputType = CXXHeaderUnitType(CXX20HeaderType); 2775 } else if (A->getOption().getID() == options::OPT_U) { 2776 assert(A->getNumValues() == 1 && "The /U option has one value."); 2777 StringRef Val = A->getValue(0); 2778 if (Val.find_first_of("/\\") != StringRef::npos) { 2779 // Warn about e.g. "/Users/me/myfile.c". 2780 Diag(diag::warn_slash_u_filename) << Val; 2781 Diag(diag::note_use_dashdash); 2782 } 2783 } 2784 } 2785 if (CCCIsCPP() && Inputs.empty()) { 2786 // If called as standalone preprocessor, stdin is processed 2787 // if no other input is present. 2788 Arg *A = MakeInputArg(Args, Opts, "-"); 2789 Inputs.push_back(std::make_pair(types::TY_C, A)); 2790 } 2791 } 2792 2793 namespace { 2794 /// Provides a convenient interface for different programming models to generate 2795 /// the required device actions. 2796 class OffloadingActionBuilder final { 2797 /// Flag used to trace errors in the builder. 2798 bool IsValid = false; 2799 2800 /// The compilation that is using this builder. 2801 Compilation &C; 2802 2803 /// Map between an input argument and the offload kinds used to process it. 2804 std::map<const Arg *, unsigned> InputArgToOffloadKindMap; 2805 2806 /// Map between a host action and its originating input argument. 2807 std::map<Action *, const Arg *> HostActionToInputArgMap; 2808 2809 /// Builder interface. It doesn't build anything or keep any state. 2810 class DeviceActionBuilder { 2811 public: 2812 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy; 2813 2814 enum ActionBuilderReturnCode { 2815 // The builder acted successfully on the current action. 2816 ABRT_Success, 2817 // The builder didn't have to act on the current action. 2818 ABRT_Inactive, 2819 // The builder was successful and requested the host action to not be 2820 // generated. 2821 ABRT_Ignore_Host, 2822 }; 2823 2824 protected: 2825 /// Compilation associated with this builder. 2826 Compilation &C; 2827 2828 /// Tool chains associated with this builder. The same programming 2829 /// model may have associated one or more tool chains. 2830 SmallVector<const ToolChain *, 2> ToolChains; 2831 2832 /// The derived arguments associated with this builder. 2833 DerivedArgList &Args; 2834 2835 /// The inputs associated with this builder. 2836 const Driver::InputList &Inputs; 2837 2838 /// The associated offload kind. 2839 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None; 2840 2841 public: 2842 DeviceActionBuilder(Compilation &C, DerivedArgList &Args, 2843 const Driver::InputList &Inputs, 2844 Action::OffloadKind AssociatedOffloadKind) 2845 : C(C), Args(Args), Inputs(Inputs), 2846 AssociatedOffloadKind(AssociatedOffloadKind) {} 2847 virtual ~DeviceActionBuilder() {} 2848 2849 /// Fill up the array \a DA with all the device dependences that should be 2850 /// added to the provided host action \a HostAction. By default it is 2851 /// inactive. 2852 virtual ActionBuilderReturnCode 2853 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2854 phases::ID CurPhase, phases::ID FinalPhase, 2855 PhasesTy &Phases) { 2856 return ABRT_Inactive; 2857 } 2858 2859 /// Update the state to include the provided host action \a HostAction as a 2860 /// dependency of the current device action. By default it is inactive. 2861 virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) { 2862 return ABRT_Inactive; 2863 } 2864 2865 /// Append top level actions generated by the builder. 2866 virtual void appendTopLevelActions(ActionList &AL) {} 2867 2868 /// Append linker device actions generated by the builder. 2869 virtual void appendLinkDeviceActions(ActionList &AL) {} 2870 2871 /// Append linker host action generated by the builder. 2872 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; } 2873 2874 /// Append linker actions generated by the builder. 2875 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {} 2876 2877 /// Initialize the builder. Return true if any initialization errors are 2878 /// found. 2879 virtual bool initialize() { return false; } 2880 2881 /// Return true if the builder can use bundling/unbundling. 2882 virtual bool canUseBundlerUnbundler() const { return false; } 2883 2884 /// Return true if this builder is valid. We have a valid builder if we have 2885 /// associated device tool chains. 2886 bool isValid() { return !ToolChains.empty(); } 2887 2888 /// Return the associated offload kind. 2889 Action::OffloadKind getAssociatedOffloadKind() { 2890 return AssociatedOffloadKind; 2891 } 2892 }; 2893 2894 /// Base class for CUDA/HIP action builder. It injects device code in 2895 /// the host backend action. 2896 class CudaActionBuilderBase : public DeviceActionBuilder { 2897 protected: 2898 /// Flags to signal if the user requested host-only or device-only 2899 /// compilation. 2900 bool CompileHostOnly = false; 2901 bool CompileDeviceOnly = false; 2902 bool EmitLLVM = false; 2903 bool EmitAsm = false; 2904 2905 /// ID to identify each device compilation. For CUDA it is simply the 2906 /// GPU arch string. For HIP it is either the GPU arch string or GPU 2907 /// arch string plus feature strings delimited by a plus sign, e.g. 2908 /// gfx906+xnack. 2909 struct TargetID { 2910 /// Target ID string which is persistent throughout the compilation. 2911 const char *ID; 2912 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); } 2913 TargetID(const char *ID) : ID(ID) {} 2914 operator const char *() { return ID; } 2915 operator StringRef() { return StringRef(ID); } 2916 }; 2917 /// List of GPU architectures to use in this compilation. 2918 SmallVector<TargetID, 4> GpuArchList; 2919 2920 /// The CUDA actions for the current input. 2921 ActionList CudaDeviceActions; 2922 2923 /// The CUDA fat binary if it was generated for the current input. 2924 Action *CudaFatBinary = nullptr; 2925 2926 /// Flag that is set to true if this builder acted on the current input. 2927 bool IsActive = false; 2928 2929 /// Flag for -fgpu-rdc. 2930 bool Relocatable = false; 2931 2932 /// Default GPU architecture if there's no one specified. 2933 CudaArch DefaultCudaArch = CudaArch::UNKNOWN; 2934 2935 /// Method to generate compilation unit ID specified by option 2936 /// '-fuse-cuid='. 2937 enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid }; 2938 UseCUIDKind UseCUID = CUID_Hash; 2939 2940 /// Compilation unit ID specified by option '-cuid='. 2941 StringRef FixedCUID; 2942 2943 public: 2944 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args, 2945 const Driver::InputList &Inputs, 2946 Action::OffloadKind OFKind) 2947 : DeviceActionBuilder(C, Args, Inputs, OFKind) { 2948 2949 CompileDeviceOnly = C.getDriver().offloadDeviceOnly(); 2950 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc, 2951 options::OPT_fno_gpu_rdc, /*Default=*/false); 2952 } 2953 2954 ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override { 2955 // While generating code for CUDA, we only depend on the host input action 2956 // to trigger the creation of all the CUDA device actions. 2957 2958 // If we are dealing with an input action, replicate it for each GPU 2959 // architecture. If we are in host-only mode we return 'success' so that 2960 // the host uses the CUDA offload kind. 2961 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 2962 assert(!GpuArchList.empty() && 2963 "We should have at least one GPU architecture."); 2964 2965 // If the host input is not CUDA or HIP, we don't need to bother about 2966 // this input. 2967 if (!(IA->getType() == types::TY_CUDA || 2968 IA->getType() == types::TY_HIP || 2969 IA->getType() == types::TY_PP_HIP)) { 2970 // The builder will ignore this input. 2971 IsActive = false; 2972 return ABRT_Inactive; 2973 } 2974 2975 // Set the flag to true, so that the builder acts on the current input. 2976 IsActive = true; 2977 2978 if (CompileHostOnly) 2979 return ABRT_Success; 2980 2981 // Replicate inputs for each GPU architecture. 2982 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE 2983 : types::TY_CUDA_DEVICE; 2984 std::string CUID = FixedCUID.str(); 2985 if (CUID.empty()) { 2986 if (UseCUID == CUID_Random) 2987 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(), 2988 /*LowerCase=*/true); 2989 else if (UseCUID == CUID_Hash) { 2990 llvm::MD5 Hasher; 2991 llvm::MD5::MD5Result Hash; 2992 SmallString<256> RealPath; 2993 llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, 2994 /*expand_tilde=*/true); 2995 Hasher.update(RealPath); 2996 for (auto *A : Args) { 2997 if (A->getOption().matches(options::OPT_INPUT)) 2998 continue; 2999 Hasher.update(A->getAsString(Args)); 3000 } 3001 Hasher.final(Hash); 3002 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true); 3003 } 3004 } 3005 IA->setId(CUID); 3006 3007 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3008 CudaDeviceActions.push_back( 3009 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId())); 3010 } 3011 3012 return ABRT_Success; 3013 } 3014 3015 // If this is an unbundling action use it as is for each CUDA toolchain. 3016 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 3017 3018 // If -fgpu-rdc is disabled, should not unbundle since there is no 3019 // device code to link. 3020 if (UA->getType() == types::TY_Object && !Relocatable) 3021 return ABRT_Inactive; 3022 3023 CudaDeviceActions.clear(); 3024 auto *IA = cast<InputAction>(UA->getInputs().back()); 3025 std::string FileName = IA->getInputArg().getAsString(Args); 3026 // Check if the type of the file is the same as the action. Do not 3027 // unbundle it if it is not. Do not unbundle .so files, for example, 3028 // which are not object files. Files with extension ".lib" is classified 3029 // as TY_Object but they are actually archives, therefore should not be 3030 // unbundled here as objects. They will be handled at other places. 3031 const StringRef LibFileExt = ".lib"; 3032 if (IA->getType() == types::TY_Object && 3033 (!llvm::sys::path::has_extension(FileName) || 3034 types::lookupTypeForExtension( 3035 llvm::sys::path::extension(FileName).drop_front()) != 3036 types::TY_Object || 3037 llvm::sys::path::extension(FileName) == LibFileExt)) 3038 return ABRT_Inactive; 3039 3040 for (auto Arch : GpuArchList) { 3041 CudaDeviceActions.push_back(UA); 3042 UA->registerDependentActionInfo(ToolChains[0], Arch, 3043 AssociatedOffloadKind); 3044 } 3045 IsActive = true; 3046 return ABRT_Success; 3047 } 3048 3049 return IsActive ? ABRT_Success : ABRT_Inactive; 3050 } 3051 3052 void appendTopLevelActions(ActionList &AL) override { 3053 // Utility to append actions to the top level list. 3054 auto AddTopLevel = [&](Action *A, TargetID TargetID) { 3055 OffloadAction::DeviceDependences Dep; 3056 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind); 3057 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 3058 }; 3059 3060 // If we have a fat binary, add it to the list. 3061 if (CudaFatBinary) { 3062 AddTopLevel(CudaFatBinary, CudaArch::UNUSED); 3063 CudaDeviceActions.clear(); 3064 CudaFatBinary = nullptr; 3065 return; 3066 } 3067 3068 if (CudaDeviceActions.empty()) 3069 return; 3070 3071 // If we have CUDA actions at this point, that's because we have a have 3072 // partial compilation, so we should have an action for each GPU 3073 // architecture. 3074 assert(CudaDeviceActions.size() == GpuArchList.size() && 3075 "Expecting one action per GPU architecture."); 3076 assert(ToolChains.size() == 1 && 3077 "Expecting to have a single CUDA toolchain."); 3078 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 3079 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]); 3080 3081 CudaDeviceActions.clear(); 3082 } 3083 3084 /// Get canonicalized offload arch option. \returns empty StringRef if the 3085 /// option is invalid. 3086 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0; 3087 3088 virtual std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 3089 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0; 3090 3091 bool initialize() override { 3092 assert(AssociatedOffloadKind == Action::OFK_Cuda || 3093 AssociatedOffloadKind == Action::OFK_HIP); 3094 3095 // We don't need to support CUDA. 3096 if (AssociatedOffloadKind == Action::OFK_Cuda && 3097 !C.hasOffloadToolChain<Action::OFK_Cuda>()) 3098 return false; 3099 3100 // We don't need to support HIP. 3101 if (AssociatedOffloadKind == Action::OFK_HIP && 3102 !C.hasOffloadToolChain<Action::OFK_HIP>()) 3103 return false; 3104 3105 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 3106 assert(HostTC && "No toolchain for host compilation."); 3107 if (HostTC->getTriple().isNVPTX() || 3108 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) { 3109 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw 3110 // an error and abort pipeline construction early so we don't trip 3111 // asserts that assume device-side compilation. 3112 C.getDriver().Diag(diag::err_drv_cuda_host_arch) 3113 << HostTC->getTriple().getArchName(); 3114 return true; 3115 } 3116 3117 ToolChains.push_back( 3118 AssociatedOffloadKind == Action::OFK_Cuda 3119 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 3120 : C.getSingleOffloadToolChain<Action::OFK_HIP>()); 3121 3122 CompileHostOnly = C.getDriver().offloadHostOnly(); 3123 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm); 3124 EmitAsm = Args.getLastArg(options::OPT_S); 3125 FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ); 3126 if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) { 3127 StringRef UseCUIDStr = A->getValue(); 3128 UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr) 3129 .Case("hash", CUID_Hash) 3130 .Case("random", CUID_Random) 3131 .Case("none", CUID_None) 3132 .Default(CUID_Invalid); 3133 if (UseCUID == CUID_Invalid) { 3134 C.getDriver().Diag(diag::err_drv_invalid_value) 3135 << A->getAsString(Args) << UseCUIDStr; 3136 C.setContainsError(); 3137 return true; 3138 } 3139 } 3140 3141 // --offload and --offload-arch options are mutually exclusive. 3142 if (Args.hasArgNoClaim(options::OPT_offload_EQ) && 3143 Args.hasArgNoClaim(options::OPT_offload_arch_EQ, 3144 options::OPT_no_offload_arch_EQ)) { 3145 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch" 3146 << "--offload"; 3147 } 3148 3149 // Collect all offload arch parameters, removing duplicates. 3150 std::set<StringRef> GpuArchs; 3151 bool Error = false; 3152 for (Arg *A : Args) { 3153 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) || 3154 A->getOption().matches(options::OPT_no_offload_arch_EQ))) 3155 continue; 3156 A->claim(); 3157 3158 for (StringRef ArchStr : llvm::split(A->getValue(), ",")) { 3159 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) && 3160 ArchStr == "all") { 3161 GpuArchs.clear(); 3162 } else if (ArchStr == "native") { 3163 const ToolChain &TC = *ToolChains.front(); 3164 auto GPUsOrErr = ToolChains.front()->getSystemGPUArchs(Args); 3165 if (!GPUsOrErr) { 3166 TC.getDriver().Diag(diag::err_drv_undetermined_gpu_arch) 3167 << llvm::Triple::getArchTypeName(TC.getArch()) 3168 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch"; 3169 continue; 3170 } 3171 3172 for (auto GPU : *GPUsOrErr) { 3173 GpuArchs.insert(Args.MakeArgString(GPU)); 3174 } 3175 } else { 3176 ArchStr = getCanonicalOffloadArch(ArchStr); 3177 if (ArchStr.empty()) { 3178 Error = true; 3179 } else if (A->getOption().matches(options::OPT_offload_arch_EQ)) 3180 GpuArchs.insert(ArchStr); 3181 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ)) 3182 GpuArchs.erase(ArchStr); 3183 else 3184 llvm_unreachable("Unexpected option."); 3185 } 3186 } 3187 } 3188 3189 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs); 3190 if (ConflictingArchs) { 3191 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo) 3192 << ConflictingArchs->first << ConflictingArchs->second; 3193 C.setContainsError(); 3194 return true; 3195 } 3196 3197 // Collect list of GPUs remaining in the set. 3198 for (auto Arch : GpuArchs) 3199 GpuArchList.push_back(Arch.data()); 3200 3201 // Default to sm_20 which is the lowest common denominator for 3202 // supported GPUs. sm_20 code should work correctly, if 3203 // suboptimally, on all newer GPUs. 3204 if (GpuArchList.empty()) { 3205 if (ToolChains.front()->getTriple().isSPIRV()) 3206 GpuArchList.push_back(CudaArch::Generic); 3207 else 3208 GpuArchList.push_back(DefaultCudaArch); 3209 } 3210 3211 return Error; 3212 } 3213 }; 3214 3215 /// \brief CUDA action builder. It injects device code in the host backend 3216 /// action. 3217 class CudaActionBuilder final : public CudaActionBuilderBase { 3218 public: 3219 CudaActionBuilder(Compilation &C, DerivedArgList &Args, 3220 const Driver::InputList &Inputs) 3221 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) { 3222 DefaultCudaArch = CudaArch::SM_35; 3223 } 3224 3225 StringRef getCanonicalOffloadArch(StringRef ArchStr) override { 3226 CudaArch Arch = StringToCudaArch(ArchStr); 3227 if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) { 3228 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 3229 return StringRef(); 3230 } 3231 return CudaArchToString(Arch); 3232 } 3233 3234 std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 3235 getConflictOffloadArchCombination( 3236 const std::set<StringRef> &GpuArchs) override { 3237 return std::nullopt; 3238 } 3239 3240 ActionBuilderReturnCode 3241 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3242 phases::ID CurPhase, phases::ID FinalPhase, 3243 PhasesTy &Phases) override { 3244 if (!IsActive) 3245 return ABRT_Inactive; 3246 3247 // If we don't have more CUDA actions, we don't have any dependences to 3248 // create for the host. 3249 if (CudaDeviceActions.empty()) 3250 return ABRT_Success; 3251 3252 assert(CudaDeviceActions.size() == GpuArchList.size() && 3253 "Expecting one action per GPU architecture."); 3254 assert(!CompileHostOnly && 3255 "Not expecting CUDA actions in host-only compilation."); 3256 3257 // If we are generating code for the device or we are in a backend phase, 3258 // we attempt to generate the fat binary. We compile each arch to ptx and 3259 // assemble to cubin, then feed the cubin *and* the ptx into a device 3260 // "link" action, which uses fatbinary to combine these cubins into one 3261 // fatbin. The fatbin is then an input to the host action if not in 3262 // device-only mode. 3263 if (CompileDeviceOnly || CurPhase == phases::Backend) { 3264 ActionList DeviceActions; 3265 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3266 // Produce the device action from the current phase up to the assemble 3267 // phase. 3268 for (auto Ph : Phases) { 3269 // Skip the phases that were already dealt with. 3270 if (Ph < CurPhase) 3271 continue; 3272 // We have to be consistent with the host final phase. 3273 if (Ph > FinalPhase) 3274 break; 3275 3276 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction( 3277 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda); 3278 3279 if (Ph == phases::Assemble) 3280 break; 3281 } 3282 3283 // If we didn't reach the assemble phase, we can't generate the fat 3284 // binary. We don't need to generate the fat binary if we are not in 3285 // device-only mode. 3286 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) || 3287 CompileDeviceOnly) 3288 continue; 3289 3290 Action *AssembleAction = CudaDeviceActions[I]; 3291 assert(AssembleAction->getType() == types::TY_Object); 3292 assert(AssembleAction->getInputs().size() == 1); 3293 3294 Action *BackendAction = AssembleAction->getInputs()[0]; 3295 assert(BackendAction->getType() == types::TY_PP_Asm); 3296 3297 for (auto &A : {AssembleAction, BackendAction}) { 3298 OffloadAction::DeviceDependences DDep; 3299 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda); 3300 DeviceActions.push_back( 3301 C.MakeAction<OffloadAction>(DDep, A->getType())); 3302 } 3303 } 3304 3305 // We generate the fat binary if we have device input actions. 3306 if (!DeviceActions.empty()) { 3307 CudaFatBinary = 3308 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 3309 3310 if (!CompileDeviceOnly) { 3311 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3312 Action::OFK_Cuda); 3313 // Clear the fat binary, it is already a dependence to an host 3314 // action. 3315 CudaFatBinary = nullptr; 3316 } 3317 3318 // Remove the CUDA actions as they are already connected to an host 3319 // action or fat binary. 3320 CudaDeviceActions.clear(); 3321 } 3322 3323 // We avoid creating host action in device-only mode. 3324 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3325 } else if (CurPhase > phases::Backend) { 3326 // If we are past the backend phase and still have a device action, we 3327 // don't have to do anything as this action is already a device 3328 // top-level action. 3329 return ABRT_Success; 3330 } 3331 3332 assert(CurPhase < phases::Backend && "Generating single CUDA " 3333 "instructions should only occur " 3334 "before the backend phase!"); 3335 3336 // By default, we produce an action for each device arch. 3337 for (Action *&A : CudaDeviceActions) 3338 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 3339 3340 return ABRT_Success; 3341 } 3342 }; 3343 /// \brief HIP action builder. It injects device code in the host backend 3344 /// action. 3345 class HIPActionBuilder final : public CudaActionBuilderBase { 3346 /// The linker inputs obtained for each device arch. 3347 SmallVector<ActionList, 8> DeviceLinkerInputs; 3348 // The default bundling behavior depends on the type of output, therefore 3349 // BundleOutput needs to be tri-value: None, true, or false. 3350 // Bundle code objects except --no-gpu-output is specified for device 3351 // only compilation. Bundle other type of output files only if 3352 // --gpu-bundle-output is specified for device only compilation. 3353 std::optional<bool> BundleOutput; 3354 std::optional<bool> EmitReloc; 3355 3356 public: 3357 HIPActionBuilder(Compilation &C, DerivedArgList &Args, 3358 const Driver::InputList &Inputs) 3359 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) { 3360 3361 DefaultCudaArch = CudaArch::GFX906; 3362 3363 if (Args.hasArg(options::OPT_fhip_emit_relocatable, 3364 options::OPT_fno_hip_emit_relocatable)) { 3365 EmitReloc = Args.hasFlag(options::OPT_fhip_emit_relocatable, 3366 options::OPT_fno_hip_emit_relocatable, false); 3367 3368 if (*EmitReloc) { 3369 if (Relocatable) { 3370 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) 3371 << "-fhip-emit-relocatable" 3372 << "-fgpu-rdc"; 3373 } 3374 3375 if (!CompileDeviceOnly) { 3376 C.getDriver().Diag(diag::err_opt_not_valid_without_opt) 3377 << "-fhip-emit-relocatable" 3378 << "--cuda-device-only"; 3379 } 3380 } 3381 } 3382 3383 if (Args.hasArg(options::OPT_gpu_bundle_output, 3384 options::OPT_no_gpu_bundle_output)) 3385 BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output, 3386 options::OPT_no_gpu_bundle_output, true) && 3387 (!EmitReloc || !*EmitReloc); 3388 } 3389 3390 bool canUseBundlerUnbundler() const override { return true; } 3391 3392 StringRef getCanonicalOffloadArch(StringRef IdStr) override { 3393 llvm::StringMap<bool> Features; 3394 // getHIPOffloadTargetTriple() is known to return valid value as it has 3395 // been called successfully in the CreateOffloadingDeviceToolChains(). 3396 auto ArchStr = parseTargetID( 3397 *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr, 3398 &Features); 3399 if (!ArchStr) { 3400 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr; 3401 C.setContainsError(); 3402 return StringRef(); 3403 } 3404 auto CanId = getCanonicalTargetID(*ArchStr, Features); 3405 return Args.MakeArgStringRef(CanId); 3406 }; 3407 3408 std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 3409 getConflictOffloadArchCombination( 3410 const std::set<StringRef> &GpuArchs) override { 3411 return getConflictTargetIDCombination(GpuArchs); 3412 } 3413 3414 ActionBuilderReturnCode 3415 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3416 phases::ID CurPhase, phases::ID FinalPhase, 3417 PhasesTy &Phases) override { 3418 if (!IsActive) 3419 return ABRT_Inactive; 3420 3421 // amdgcn does not support linking of object files, therefore we skip 3422 // backend and assemble phases to output LLVM IR. Except for generating 3423 // non-relocatable device code, where we generate fat binary for device 3424 // code and pass to host in Backend phase. 3425 if (CudaDeviceActions.empty()) 3426 return ABRT_Success; 3427 3428 assert(((CurPhase == phases::Link && Relocatable) || 3429 CudaDeviceActions.size() == GpuArchList.size()) && 3430 "Expecting one action per GPU architecture."); 3431 assert(!CompileHostOnly && 3432 "Not expecting HIP actions in host-only compilation."); 3433 3434 bool ShouldLink = !EmitReloc || !*EmitReloc; 3435 3436 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM && 3437 !EmitAsm && ShouldLink) { 3438 // If we are in backend phase, we attempt to generate the fat binary. 3439 // We compile each arch to IR and use a link action to generate code 3440 // object containing ISA. Then we use a special "link" action to create 3441 // a fat binary containing all the code objects for different GPU's. 3442 // The fat binary is then an input to the host action. 3443 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3444 if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) { 3445 // When LTO is enabled, skip the backend and assemble phases and 3446 // use lld to link the bitcode. 3447 ActionList AL; 3448 AL.push_back(CudaDeviceActions[I]); 3449 // Create a link action to link device IR with device library 3450 // and generate ISA. 3451 CudaDeviceActions[I] = 3452 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 3453 } else { 3454 // When LTO is not enabled, we follow the conventional 3455 // compiler phases, including backend and assemble phases. 3456 ActionList AL; 3457 Action *BackendAction = nullptr; 3458 if (ToolChains.front()->getTriple().isSPIRV()) { 3459 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain 3460 // (HIPSPVToolChain) runs post-link LLVM IR passes. 3461 types::ID Output = Args.hasArg(options::OPT_S) 3462 ? types::TY_LLVM_IR 3463 : types::TY_LLVM_BC; 3464 BackendAction = 3465 C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output); 3466 } else 3467 BackendAction = C.getDriver().ConstructPhaseAction( 3468 C, Args, phases::Backend, CudaDeviceActions[I], 3469 AssociatedOffloadKind); 3470 auto AssembleAction = C.getDriver().ConstructPhaseAction( 3471 C, Args, phases::Assemble, BackendAction, 3472 AssociatedOffloadKind); 3473 AL.push_back(AssembleAction); 3474 // Create a link action to link device IR with device library 3475 // and generate ISA. 3476 CudaDeviceActions[I] = 3477 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 3478 } 3479 3480 // OffloadingActionBuilder propagates device arch until an offload 3481 // action. Since the next action for creating fatbin does 3482 // not have device arch, whereas the above link action and its input 3483 // have device arch, an offload action is needed to stop the null 3484 // device arch of the next action being propagated to the above link 3485 // action. 3486 OffloadAction::DeviceDependences DDep; 3487 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3488 AssociatedOffloadKind); 3489 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3490 DDep, CudaDeviceActions[I]->getType()); 3491 } 3492 3493 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) { 3494 // Create HIP fat binary with a special "link" action. 3495 CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions, 3496 types::TY_HIP_FATBIN); 3497 3498 if (!CompileDeviceOnly) { 3499 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3500 AssociatedOffloadKind); 3501 // Clear the fat binary, it is already a dependence to an host 3502 // action. 3503 CudaFatBinary = nullptr; 3504 } 3505 3506 // Remove the CUDA actions as they are already connected to an host 3507 // action or fat binary. 3508 CudaDeviceActions.clear(); 3509 } 3510 3511 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3512 } else if (CurPhase == phases::Link) { 3513 if (!ShouldLink) 3514 return ABRT_Success; 3515 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch. 3516 // This happens to each device action originated from each input file. 3517 // Later on, device actions in DeviceLinkerInputs are used to create 3518 // device link actions in appendLinkDependences and the created device 3519 // link actions are passed to the offload action as device dependence. 3520 DeviceLinkerInputs.resize(CudaDeviceActions.size()); 3521 auto LI = DeviceLinkerInputs.begin(); 3522 for (auto *A : CudaDeviceActions) { 3523 LI->push_back(A); 3524 ++LI; 3525 } 3526 3527 // We will pass the device action as a host dependence, so we don't 3528 // need to do anything else with them. 3529 CudaDeviceActions.clear(); 3530 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3531 } 3532 3533 // By default, we produce an action for each device arch. 3534 for (Action *&A : CudaDeviceActions) 3535 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A, 3536 AssociatedOffloadKind); 3537 3538 if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput && 3539 *BundleOutput) { 3540 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3541 OffloadAction::DeviceDependences DDep; 3542 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3543 AssociatedOffloadKind); 3544 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3545 DDep, CudaDeviceActions[I]->getType()); 3546 } 3547 CudaFatBinary = 3548 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions); 3549 CudaDeviceActions.clear(); 3550 } 3551 3552 return (CompileDeviceOnly && 3553 (CurPhase == FinalPhase || 3554 (!ShouldLink && CurPhase == phases::Assemble))) 3555 ? ABRT_Ignore_Host 3556 : ABRT_Success; 3557 } 3558 3559 void appendLinkDeviceActions(ActionList &AL) override { 3560 if (DeviceLinkerInputs.size() == 0) 3561 return; 3562 3563 assert(DeviceLinkerInputs.size() == GpuArchList.size() && 3564 "Linker inputs and GPU arch list sizes do not match."); 3565 3566 ActionList Actions; 3567 unsigned I = 0; 3568 // Append a new link action for each device. 3569 // Each entry in DeviceLinkerInputs corresponds to a GPU arch. 3570 for (auto &LI : DeviceLinkerInputs) { 3571 3572 types::ID Output = Args.hasArg(options::OPT_emit_llvm) 3573 ? types::TY_LLVM_BC 3574 : types::TY_Image; 3575 3576 auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output); 3577 // Linking all inputs for the current GPU arch. 3578 // LI contains all the inputs for the linker. 3579 OffloadAction::DeviceDependences DeviceLinkDeps; 3580 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0], 3581 GpuArchList[I], AssociatedOffloadKind); 3582 Actions.push_back(C.MakeAction<OffloadAction>( 3583 DeviceLinkDeps, DeviceLinkAction->getType())); 3584 ++I; 3585 } 3586 DeviceLinkerInputs.clear(); 3587 3588 // If emitting LLVM, do not generate final host/device compilation action 3589 if (Args.hasArg(options::OPT_emit_llvm)) { 3590 AL.append(Actions); 3591 return; 3592 } 3593 3594 // Create a host object from all the device images by embedding them 3595 // in a fat binary for mixed host-device compilation. For device-only 3596 // compilation, creates a fat binary. 3597 OffloadAction::DeviceDependences DDeps; 3598 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) { 3599 auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>( 3600 Actions, 3601 CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object); 3602 DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr, 3603 AssociatedOffloadKind); 3604 // Offload the host object to the host linker. 3605 AL.push_back( 3606 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType())); 3607 } else { 3608 AL.append(Actions); 3609 } 3610 } 3611 3612 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); } 3613 3614 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} 3615 }; 3616 3617 /// 3618 /// TODO: Add the implementation for other specialized builders here. 3619 /// 3620 3621 /// Specialized builders being used by this offloading action builder. 3622 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders; 3623 3624 /// Flag set to true if all valid builders allow file bundling/unbundling. 3625 bool CanUseBundler; 3626 3627 public: 3628 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args, 3629 const Driver::InputList &Inputs) 3630 : C(C) { 3631 // Create a specialized builder for each device toolchain. 3632 3633 IsValid = true; 3634 3635 // Create a specialized builder for CUDA. 3636 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs)); 3637 3638 // Create a specialized builder for HIP. 3639 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs)); 3640 3641 // 3642 // TODO: Build other specialized builders here. 3643 // 3644 3645 // Initialize all the builders, keeping track of errors. If all valid 3646 // builders agree that we can use bundling, set the flag to true. 3647 unsigned ValidBuilders = 0u; 3648 unsigned ValidBuildersSupportingBundling = 0u; 3649 for (auto *SB : SpecializedBuilders) { 3650 IsValid = IsValid && !SB->initialize(); 3651 3652 // Update the counters if the builder is valid. 3653 if (SB->isValid()) { 3654 ++ValidBuilders; 3655 if (SB->canUseBundlerUnbundler()) 3656 ++ValidBuildersSupportingBundling; 3657 } 3658 } 3659 CanUseBundler = 3660 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling; 3661 } 3662 3663 ~OffloadingActionBuilder() { 3664 for (auto *SB : SpecializedBuilders) 3665 delete SB; 3666 } 3667 3668 /// Record a host action and its originating input argument. 3669 void recordHostAction(Action *HostAction, const Arg *InputArg) { 3670 assert(HostAction && "Invalid host action"); 3671 assert(InputArg && "Invalid input argument"); 3672 auto Loc = HostActionToInputArgMap.find(HostAction); 3673 if (Loc == HostActionToInputArgMap.end()) 3674 HostActionToInputArgMap[HostAction] = InputArg; 3675 assert(HostActionToInputArgMap[HostAction] == InputArg && 3676 "host action mapped to multiple input arguments"); 3677 } 3678 3679 /// Generate an action that adds device dependences (if any) to a host action. 3680 /// If no device dependence actions exist, just return the host action \a 3681 /// HostAction. If an error is found or if no builder requires the host action 3682 /// to be generated, return nullptr. 3683 Action * 3684 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg, 3685 phases::ID CurPhase, phases::ID FinalPhase, 3686 DeviceActionBuilder::PhasesTy &Phases) { 3687 if (!IsValid) 3688 return nullptr; 3689 3690 if (SpecializedBuilders.empty()) 3691 return HostAction; 3692 3693 assert(HostAction && "Invalid host action!"); 3694 recordHostAction(HostAction, InputArg); 3695 3696 OffloadAction::DeviceDependences DDeps; 3697 // Check if all the programming models agree we should not emit the host 3698 // action. Also, keep track of the offloading kinds employed. 3699 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3700 unsigned InactiveBuilders = 0u; 3701 unsigned IgnoringBuilders = 0u; 3702 for (auto *SB : SpecializedBuilders) { 3703 if (!SB->isValid()) { 3704 ++InactiveBuilders; 3705 continue; 3706 } 3707 auto RetCode = 3708 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases); 3709 3710 // If the builder explicitly says the host action should be ignored, 3711 // we need to increment the variable that tracks the builders that request 3712 // the host object to be ignored. 3713 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host) 3714 ++IgnoringBuilders; 3715 3716 // Unless the builder was inactive for this action, we have to record the 3717 // offload kind because the host will have to use it. 3718 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3719 OffloadKind |= SB->getAssociatedOffloadKind(); 3720 } 3721 3722 // If all builders agree that the host object should be ignored, just return 3723 // nullptr. 3724 if (IgnoringBuilders && 3725 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)) 3726 return nullptr; 3727 3728 if (DDeps.getActions().empty()) 3729 return HostAction; 3730 3731 // We have dependences we need to bundle together. We use an offload action 3732 // for that. 3733 OffloadAction::HostDependence HDep( 3734 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3735 /*BoundArch=*/nullptr, DDeps); 3736 return C.MakeAction<OffloadAction>(HDep, DDeps); 3737 } 3738 3739 /// Generate an action that adds a host dependence to a device action. The 3740 /// results will be kept in this action builder. Return true if an error was 3741 /// found. 3742 bool addHostDependenceToDeviceActions(Action *&HostAction, 3743 const Arg *InputArg) { 3744 if (!IsValid) 3745 return true; 3746 3747 recordHostAction(HostAction, InputArg); 3748 3749 // If we are supporting bundling/unbundling and the current action is an 3750 // input action of non-source file, we replace the host action by the 3751 // unbundling action. The bundler tool has the logic to detect if an input 3752 // is a bundle or not and if the input is not a bundle it assumes it is a 3753 // host file. Therefore it is safe to create an unbundling action even if 3754 // the input is not a bundle. 3755 if (CanUseBundler && isa<InputAction>(HostAction) && 3756 InputArg->getOption().getKind() == llvm::opt::Option::InputClass && 3757 (!types::isSrcFile(HostAction->getType()) || 3758 HostAction->getType() == types::TY_PP_HIP)) { 3759 auto UnbundlingHostAction = 3760 C.MakeAction<OffloadUnbundlingJobAction>(HostAction); 3761 UnbundlingHostAction->registerDependentActionInfo( 3762 C.getSingleOffloadToolChain<Action::OFK_Host>(), 3763 /*BoundArch=*/StringRef(), Action::OFK_Host); 3764 HostAction = UnbundlingHostAction; 3765 recordHostAction(HostAction, InputArg); 3766 } 3767 3768 assert(HostAction && "Invalid host action!"); 3769 3770 // Register the offload kinds that are used. 3771 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3772 for (auto *SB : SpecializedBuilders) { 3773 if (!SB->isValid()) 3774 continue; 3775 3776 auto RetCode = SB->addDeviceDependences(HostAction); 3777 3778 // Host dependences for device actions are not compatible with that same 3779 // action being ignored. 3780 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host && 3781 "Host dependence not expected to be ignored.!"); 3782 3783 // Unless the builder was inactive for this action, we have to record the 3784 // offload kind because the host will have to use it. 3785 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3786 OffloadKind |= SB->getAssociatedOffloadKind(); 3787 } 3788 3789 // Do not use unbundler if the Host does not depend on device action. 3790 if (OffloadKind == Action::OFK_None && CanUseBundler) 3791 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) 3792 HostAction = UA->getInputs().back(); 3793 3794 return false; 3795 } 3796 3797 /// Add the offloading top level actions to the provided action list. This 3798 /// function can replace the host action by a bundling action if the 3799 /// programming models allow it. 3800 bool appendTopLevelActions(ActionList &AL, Action *HostAction, 3801 const Arg *InputArg) { 3802 if (HostAction) 3803 recordHostAction(HostAction, InputArg); 3804 3805 // Get the device actions to be appended. 3806 ActionList OffloadAL; 3807 for (auto *SB : SpecializedBuilders) { 3808 if (!SB->isValid()) 3809 continue; 3810 SB->appendTopLevelActions(OffloadAL); 3811 } 3812 3813 // If we can use the bundler, replace the host action by the bundling one in 3814 // the resulting list. Otherwise, just append the device actions. For 3815 // device only compilation, HostAction is a null pointer, therefore only do 3816 // this when HostAction is not a null pointer. 3817 if (CanUseBundler && HostAction && 3818 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) { 3819 // Add the host action to the list in order to create the bundling action. 3820 OffloadAL.push_back(HostAction); 3821 3822 // We expect that the host action was just appended to the action list 3823 // before this method was called. 3824 assert(HostAction == AL.back() && "Host action not in the list??"); 3825 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL); 3826 recordHostAction(HostAction, InputArg); 3827 AL.back() = HostAction; 3828 } else 3829 AL.append(OffloadAL.begin(), OffloadAL.end()); 3830 3831 // Propagate to the current host action (if any) the offload information 3832 // associated with the current input. 3833 if (HostAction) 3834 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg], 3835 /*BoundArch=*/nullptr); 3836 return false; 3837 } 3838 3839 void appendDeviceLinkActions(ActionList &AL) { 3840 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3841 if (!SB->isValid()) 3842 continue; 3843 SB->appendLinkDeviceActions(AL); 3844 } 3845 } 3846 3847 Action *makeHostLinkAction() { 3848 // Build a list of device linking actions. 3849 ActionList DeviceAL; 3850 appendDeviceLinkActions(DeviceAL); 3851 if (DeviceAL.empty()) 3852 return nullptr; 3853 3854 // Let builders add host linking actions. 3855 Action* HA = nullptr; 3856 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3857 if (!SB->isValid()) 3858 continue; 3859 HA = SB->appendLinkHostActions(DeviceAL); 3860 // This created host action has no originating input argument, therefore 3861 // needs to set its offloading kind directly. 3862 if (HA) 3863 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(), 3864 /*BoundArch=*/nullptr); 3865 } 3866 return HA; 3867 } 3868 3869 /// Processes the host linker action. This currently consists of replacing it 3870 /// with an offload action if there are device link objects and propagate to 3871 /// the host action all the offload kinds used in the current compilation. The 3872 /// resulting action is returned. 3873 Action *processHostLinkAction(Action *HostAction) { 3874 // Add all the dependences from the device linking actions. 3875 OffloadAction::DeviceDependences DDeps; 3876 for (auto *SB : SpecializedBuilders) { 3877 if (!SB->isValid()) 3878 continue; 3879 3880 SB->appendLinkDependences(DDeps); 3881 } 3882 3883 // Calculate all the offload kinds used in the current compilation. 3884 unsigned ActiveOffloadKinds = 0u; 3885 for (auto &I : InputArgToOffloadKindMap) 3886 ActiveOffloadKinds |= I.second; 3887 3888 // If we don't have device dependencies, we don't have to create an offload 3889 // action. 3890 if (DDeps.getActions().empty()) { 3891 // Set all the active offloading kinds to the link action. Given that it 3892 // is a link action it is assumed to depend on all actions generated so 3893 // far. 3894 HostAction->setHostOffloadInfo(ActiveOffloadKinds, 3895 /*BoundArch=*/nullptr); 3896 // Propagate active offloading kinds for each input to the link action. 3897 // Each input may have different active offloading kind. 3898 for (auto *A : HostAction->inputs()) { 3899 auto ArgLoc = HostActionToInputArgMap.find(A); 3900 if (ArgLoc == HostActionToInputArgMap.end()) 3901 continue; 3902 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second); 3903 if (OFKLoc == InputArgToOffloadKindMap.end()) 3904 continue; 3905 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr); 3906 } 3907 return HostAction; 3908 } 3909 3910 // Create the offload action with all dependences. When an offload action 3911 // is created the kinds are propagated to the host action, so we don't have 3912 // to do that explicitly here. 3913 OffloadAction::HostDependence HDep( 3914 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3915 /*BoundArch*/ nullptr, ActiveOffloadKinds); 3916 return C.MakeAction<OffloadAction>(HDep, DDeps); 3917 } 3918 }; 3919 } // anonymous namespace. 3920 3921 void Driver::handleArguments(Compilation &C, DerivedArgList &Args, 3922 const InputList &Inputs, 3923 ActionList &Actions) const { 3924 3925 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames. 3926 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 3927 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 3928 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 3929 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 3930 Args.eraseArg(options::OPT__SLASH_Yc); 3931 Args.eraseArg(options::OPT__SLASH_Yu); 3932 YcArg = YuArg = nullptr; 3933 } 3934 if (YcArg && Inputs.size() > 1) { 3935 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 3936 Args.eraseArg(options::OPT__SLASH_Yc); 3937 YcArg = nullptr; 3938 } 3939 3940 Arg *FinalPhaseArg; 3941 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 3942 3943 if (FinalPhase == phases::Link) { 3944 if (Args.hasArgNoClaim(options::OPT_hipstdpar)) { 3945 Args.AddFlagArg(nullptr, getOpts().getOption(options::OPT_hip_link)); 3946 Args.AddFlagArg(nullptr, 3947 getOpts().getOption(options::OPT_frtlib_add_rpath)); 3948 } 3949 // Emitting LLVM while linking disabled except in HIPAMD Toolchain 3950 if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link)) 3951 Diag(clang::diag::err_drv_emit_llvm_link); 3952 if (IsCLMode() && LTOMode != LTOK_None && 3953 !Args.getLastArgValue(options::OPT_fuse_ld_EQ) 3954 .equals_insensitive("lld")) 3955 Diag(clang::diag::err_drv_lto_without_lld); 3956 3957 // If -dumpdir is not specified, give a default prefix derived from the link 3958 // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes 3959 // `-dumpdir x-` to cc1. If -o is unspecified, use 3960 // stem(getDefaultImageName()) (usually stem("a.out") = "a"). 3961 if (!Args.hasArg(options::OPT_dumpdir)) { 3962 Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o); 3963 Arg *Arg = Args.MakeSeparateArg( 3964 nullptr, getOpts().getOption(options::OPT_dumpdir), 3965 Args.MakeArgString( 3966 (FinalOutput ? FinalOutput->getValue() 3967 : llvm::sys::path::stem(getDefaultImageName())) + 3968 "-")); 3969 Arg->claim(); 3970 Args.append(Arg); 3971 } 3972 } 3973 3974 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) { 3975 // If only preprocessing or /Y- is used, all pch handling is disabled. 3976 // Rather than check for it everywhere, just remove clang-cl pch-related 3977 // flags here. 3978 Args.eraseArg(options::OPT__SLASH_Fp); 3979 Args.eraseArg(options::OPT__SLASH_Yc); 3980 Args.eraseArg(options::OPT__SLASH_Yu); 3981 YcArg = YuArg = nullptr; 3982 } 3983 3984 unsigned LastPLSize = 0; 3985 for (auto &I : Inputs) { 3986 types::ID InputType = I.first; 3987 const Arg *InputArg = I.second; 3988 3989 auto PL = types::getCompilationPhases(InputType); 3990 LastPLSize = PL.size(); 3991 3992 // If the first step comes after the final phase we are doing as part of 3993 // this compilation, warn the user about it. 3994 phases::ID InitialPhase = PL[0]; 3995 if (InitialPhase > FinalPhase) { 3996 if (InputArg->isClaimed()) 3997 continue; 3998 3999 // Claim here to avoid the more general unused warning. 4000 InputArg->claim(); 4001 4002 // Suppress all unused style warnings with -Qunused-arguments 4003 if (Args.hasArg(options::OPT_Qunused_arguments)) 4004 continue; 4005 4006 // Special case when final phase determined by binary name, rather than 4007 // by a command-line argument with a corresponding Arg. 4008 if (CCCIsCPP()) 4009 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 4010 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 4011 // Special case '-E' warning on a previously preprocessed file to make 4012 // more sense. 4013 else if (InitialPhase == phases::Compile && 4014 (Args.getLastArg(options::OPT__SLASH_EP, 4015 options::OPT__SLASH_P) || 4016 Args.getLastArg(options::OPT_E) || 4017 Args.getLastArg(options::OPT_M, options::OPT_MM)) && 4018 getPreprocessedType(InputType) == types::TY_INVALID) 4019 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 4020 << InputArg->getAsString(Args) << !!FinalPhaseArg 4021 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 4022 else 4023 Diag(clang::diag::warn_drv_input_file_unused) 4024 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 4025 << !!FinalPhaseArg 4026 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 4027 continue; 4028 } 4029 4030 if (YcArg) { 4031 // Add a separate precompile phase for the compile phase. 4032 if (FinalPhase >= phases::Compile) { 4033 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType); 4034 // Build the pipeline for the pch file. 4035 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType); 4036 for (phases::ID Phase : types::getCompilationPhases(HeaderType)) 4037 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 4038 assert(ClangClPch); 4039 Actions.push_back(ClangClPch); 4040 // The driver currently exits after the first failed command. This 4041 // relies on that behavior, to make sure if the pch generation fails, 4042 // the main compilation won't run. 4043 // FIXME: If the main compilation fails, the PCH generation should 4044 // probably not be considered successful either. 4045 } 4046 } 4047 } 4048 4049 // If we are linking, claim any options which are obviously only used for 4050 // compilation. 4051 // FIXME: Understand why the last Phase List length is used here. 4052 if (FinalPhase == phases::Link && LastPLSize == 1) { 4053 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 4054 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 4055 } 4056 } 4057 4058 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 4059 const InputList &Inputs, ActionList &Actions) const { 4060 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 4061 4062 if (!SuppressMissingInputWarning && Inputs.empty()) { 4063 Diag(clang::diag::err_drv_no_input_files); 4064 return; 4065 } 4066 4067 // Diagnose misuse of /Fo. 4068 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 4069 StringRef V = A->getValue(); 4070 if (Inputs.size() > 1 && !V.empty() && 4071 !llvm::sys::path::is_separator(V.back())) { 4072 // Check whether /Fo tries to name an output file for multiple inputs. 4073 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 4074 << A->getSpelling() << V; 4075 Args.eraseArg(options::OPT__SLASH_Fo); 4076 } 4077 } 4078 4079 // Diagnose misuse of /Fa. 4080 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 4081 StringRef V = A->getValue(); 4082 if (Inputs.size() > 1 && !V.empty() && 4083 !llvm::sys::path::is_separator(V.back())) { 4084 // Check whether /Fa tries to name an asm file for multiple inputs. 4085 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 4086 << A->getSpelling() << V; 4087 Args.eraseArg(options::OPT__SLASH_Fa); 4088 } 4089 } 4090 4091 // Diagnose misuse of /o. 4092 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 4093 if (A->getValue()[0] == '\0') { 4094 // It has to have a value. 4095 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 4096 Args.eraseArg(options::OPT__SLASH_o); 4097 } 4098 } 4099 4100 handleArguments(C, Args, Inputs, Actions); 4101 4102 bool UseNewOffloadingDriver = 4103 C.isOffloadingHostKind(Action::OFK_OpenMP) || 4104 Args.hasFlag(options::OPT_offload_new_driver, 4105 options::OPT_no_offload_new_driver, false); 4106 4107 // Builder to be used to build offloading actions. 4108 std::unique_ptr<OffloadingActionBuilder> OffloadBuilder = 4109 !UseNewOffloadingDriver 4110 ? std::make_unique<OffloadingActionBuilder>(C, Args, Inputs) 4111 : nullptr; 4112 4113 // Construct the actions to perform. 4114 ExtractAPIJobAction *ExtractAPIAction = nullptr; 4115 ActionList LinkerInputs; 4116 ActionList MergerInputs; 4117 4118 for (auto &I : Inputs) { 4119 types::ID InputType = I.first; 4120 const Arg *InputArg = I.second; 4121 4122 auto PL = types::getCompilationPhases(*this, Args, InputType); 4123 if (PL.empty()) 4124 continue; 4125 4126 auto FullPL = types::getCompilationPhases(InputType); 4127 4128 // Build the pipeline for this file. 4129 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 4130 4131 // Use the current host action in any of the offloading actions, if 4132 // required. 4133 if (!UseNewOffloadingDriver) 4134 if (OffloadBuilder->addHostDependenceToDeviceActions(Current, InputArg)) 4135 break; 4136 4137 for (phases::ID Phase : PL) { 4138 4139 // Add any offload action the host action depends on. 4140 if (!UseNewOffloadingDriver) 4141 Current = OffloadBuilder->addDeviceDependencesToHostAction( 4142 Current, InputArg, Phase, PL.back(), FullPL); 4143 if (!Current) 4144 break; 4145 4146 // Queue linker inputs. 4147 if (Phase == phases::Link) { 4148 assert(Phase == PL.back() && "linking must be final compilation step."); 4149 // We don't need to generate additional link commands if emitting AMD 4150 // bitcode or compiling only for the offload device 4151 if (!(C.getInputArgs().hasArg(options::OPT_hip_link) && 4152 (C.getInputArgs().hasArg(options::OPT_emit_llvm))) && 4153 !offloadDeviceOnly()) 4154 LinkerInputs.push_back(Current); 4155 Current = nullptr; 4156 break; 4157 } 4158 4159 // TODO: Consider removing this because the merged may not end up being 4160 // the final Phase in the pipeline. Perhaps the merged could just merge 4161 // and then pass an artifact of some sort to the Link Phase. 4162 // Queue merger inputs. 4163 if (Phase == phases::IfsMerge) { 4164 assert(Phase == PL.back() && "merging must be final compilation step."); 4165 MergerInputs.push_back(Current); 4166 Current = nullptr; 4167 break; 4168 } 4169 4170 if (Phase == phases::Precompile && ExtractAPIAction) { 4171 ExtractAPIAction->addHeaderInput(Current); 4172 Current = nullptr; 4173 break; 4174 } 4175 4176 // FIXME: Should we include any prior module file outputs as inputs of 4177 // later actions in the same command line? 4178 4179 // Otherwise construct the appropriate action. 4180 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current); 4181 4182 // We didn't create a new action, so we will just move to the next phase. 4183 if (NewCurrent == Current) 4184 continue; 4185 4186 if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent)) 4187 ExtractAPIAction = EAA; 4188 4189 Current = NewCurrent; 4190 4191 // Try to build the offloading actions and add the result as a dependency 4192 // to the host. 4193 if (UseNewOffloadingDriver) 4194 Current = BuildOffloadingActions(C, Args, I, Current); 4195 // Use the current host action in any of the offloading actions, if 4196 // required. 4197 else if (OffloadBuilder->addHostDependenceToDeviceActions(Current, 4198 InputArg)) 4199 break; 4200 4201 if (Current->getType() == types::TY_Nothing) 4202 break; 4203 } 4204 4205 // If we ended with something, add to the output list. 4206 if (Current) 4207 Actions.push_back(Current); 4208 4209 // Add any top level actions generated for offloading. 4210 if (!UseNewOffloadingDriver) 4211 OffloadBuilder->appendTopLevelActions(Actions, Current, InputArg); 4212 else if (Current) 4213 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(), 4214 /*BoundArch=*/nullptr); 4215 } 4216 4217 // Add a link action if necessary. 4218 4219 if (LinkerInputs.empty()) { 4220 Arg *FinalPhaseArg; 4221 if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link) 4222 if (!UseNewOffloadingDriver) 4223 OffloadBuilder->appendDeviceLinkActions(Actions); 4224 } 4225 4226 if (!LinkerInputs.empty()) { 4227 if (!UseNewOffloadingDriver) 4228 if (Action *Wrapper = OffloadBuilder->makeHostLinkAction()) 4229 LinkerInputs.push_back(Wrapper); 4230 Action *LA; 4231 // Check if this Linker Job should emit a static library. 4232 if (ShouldEmitStaticLibrary(Args)) { 4233 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image); 4234 } else if (UseNewOffloadingDriver || 4235 Args.hasArg(options::OPT_offload_link)) { 4236 LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image); 4237 LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(), 4238 /*BoundArch=*/nullptr); 4239 } else { 4240 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image); 4241 } 4242 if (!UseNewOffloadingDriver) 4243 LA = OffloadBuilder->processHostLinkAction(LA); 4244 Actions.push_back(LA); 4245 } 4246 4247 // Add an interface stubs merge action if necessary. 4248 if (!MergerInputs.empty()) 4249 Actions.push_back( 4250 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4251 4252 if (Args.hasArg(options::OPT_emit_interface_stubs)) { 4253 auto PhaseList = types::getCompilationPhases( 4254 types::TY_IFS_CPP, 4255 Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge); 4256 4257 ActionList MergerInputs; 4258 4259 for (auto &I : Inputs) { 4260 types::ID InputType = I.first; 4261 const Arg *InputArg = I.second; 4262 4263 // Currently clang and the llvm assembler do not support generating symbol 4264 // stubs from assembly, so we skip the input on asm files. For ifs files 4265 // we rely on the normal pipeline setup in the pipeline setup code above. 4266 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || 4267 InputType == types::TY_Asm) 4268 continue; 4269 4270 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 4271 4272 for (auto Phase : PhaseList) { 4273 switch (Phase) { 4274 default: 4275 llvm_unreachable( 4276 "IFS Pipeline can only consist of Compile followed by IfsMerge."); 4277 case phases::Compile: { 4278 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs 4279 // files where the .o file is located. The compile action can not 4280 // handle this. 4281 if (InputType == types::TY_Object) 4282 break; 4283 4284 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP); 4285 break; 4286 } 4287 case phases::IfsMerge: { 4288 assert(Phase == PhaseList.back() && 4289 "merging must be final compilation step."); 4290 MergerInputs.push_back(Current); 4291 Current = nullptr; 4292 break; 4293 } 4294 } 4295 } 4296 4297 // If we ended with something, add to the output list. 4298 if (Current) 4299 Actions.push_back(Current); 4300 } 4301 4302 // Add an interface stubs merge action if necessary. 4303 if (!MergerInputs.empty()) 4304 Actions.push_back( 4305 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4306 } 4307 4308 for (auto Opt : {options::OPT_print_supported_cpus, 4309 options::OPT_print_supported_extensions}) { 4310 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a 4311 // custom Compile phase that prints out supported cpu models and quits. 4312 // 4313 // If --print-supported-extensions is specified, call the helper function 4314 // RISCVMarchHelp in RISCVISAInfo.cpp that prints out supported extensions 4315 // and quits. 4316 if (Arg *A = Args.getLastArg(Opt)) { 4317 if (Opt == options::OPT_print_supported_extensions && 4318 !C.getDefaultToolChain().getTriple().isRISCV() && 4319 !C.getDefaultToolChain().getTriple().isAArch64() && 4320 !C.getDefaultToolChain().getTriple().isARM()) { 4321 C.getDriver().Diag(diag::err_opt_not_valid_on_target) 4322 << "--print-supported-extensions"; 4323 return; 4324 } 4325 4326 // Use the -mcpu=? flag as the dummy input to cc1. 4327 Actions.clear(); 4328 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C); 4329 Actions.push_back( 4330 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing)); 4331 for (auto &I : Inputs) 4332 I.second->claim(); 4333 } 4334 } 4335 4336 // Call validator for dxil when -Vd not in Args. 4337 if (C.getDefaultToolChain().getTriple().isDXIL()) { 4338 // Only add action when needValidation. 4339 const auto &TC = 4340 static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain()); 4341 if (TC.requiresValidation(Args)) { 4342 Action *LastAction = Actions.back(); 4343 Actions.push_back(C.MakeAction<BinaryAnalyzeJobAction>( 4344 LastAction, types::TY_DX_CONTAINER)); 4345 } 4346 } 4347 4348 // Claim ignored clang-cl options. 4349 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 4350 } 4351 4352 /// Returns the canonical name for the offloading architecture when using a HIP 4353 /// or CUDA architecture. 4354 static StringRef getCanonicalArchString(Compilation &C, 4355 const llvm::opt::DerivedArgList &Args, 4356 StringRef ArchStr, 4357 const llvm::Triple &Triple, 4358 bool SuppressError = false) { 4359 // Lookup the CUDA / HIP architecture string. Only report an error if we were 4360 // expecting the triple to be only NVPTX / AMDGPU. 4361 CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr)); 4362 if (!SuppressError && Triple.isNVPTX() && 4363 (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) { 4364 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch) 4365 << "CUDA" << ArchStr; 4366 return StringRef(); 4367 } else if (!SuppressError && Triple.isAMDGPU() && 4368 (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) { 4369 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch) 4370 << "HIP" << ArchStr; 4371 return StringRef(); 4372 } 4373 4374 if (IsNVIDIAGpuArch(Arch)) 4375 return Args.MakeArgStringRef(CudaArchToString(Arch)); 4376 4377 if (IsAMDGpuArch(Arch)) { 4378 llvm::StringMap<bool> Features; 4379 auto HIPTriple = getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()); 4380 if (!HIPTriple) 4381 return StringRef(); 4382 auto Arch = parseTargetID(*HIPTriple, ArchStr, &Features); 4383 if (!Arch) { 4384 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr; 4385 C.setContainsError(); 4386 return StringRef(); 4387 } 4388 return Args.MakeArgStringRef(getCanonicalTargetID(*Arch, Features)); 4389 } 4390 4391 // If the input isn't CUDA or HIP just return the architecture. 4392 return ArchStr; 4393 } 4394 4395 /// Checks if the set offloading architectures does not conflict. Returns the 4396 /// incompatible pair if a conflict occurs. 4397 static std::optional<std::pair<llvm::StringRef, llvm::StringRef>> 4398 getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs, 4399 llvm::Triple Triple) { 4400 if (!Triple.isAMDGPU()) 4401 return std::nullopt; 4402 4403 std::set<StringRef> ArchSet; 4404 llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin())); 4405 return getConflictTargetIDCombination(ArchSet); 4406 } 4407 4408 llvm::DenseSet<StringRef> 4409 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, 4410 Action::OffloadKind Kind, const ToolChain *TC, 4411 bool SuppressError) const { 4412 if (!TC) 4413 TC = &C.getDefaultToolChain(); 4414 4415 // --offload and --offload-arch options are mutually exclusive. 4416 if (Args.hasArgNoClaim(options::OPT_offload_EQ) && 4417 Args.hasArgNoClaim(options::OPT_offload_arch_EQ, 4418 options::OPT_no_offload_arch_EQ)) { 4419 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) 4420 << "--offload" 4421 << (Args.hasArgNoClaim(options::OPT_offload_arch_EQ) 4422 ? "--offload-arch" 4423 : "--no-offload-arch"); 4424 } 4425 4426 if (KnownArchs.contains(TC)) 4427 return KnownArchs.lookup(TC); 4428 4429 llvm::DenseSet<StringRef> Archs; 4430 for (auto *Arg : Args) { 4431 // Extract any '--[no-]offload-arch' arguments intended for this toolchain. 4432 std::unique_ptr<llvm::opt::Arg> ExtractedArg = nullptr; 4433 if (Arg->getOption().matches(options::OPT_Xopenmp_target_EQ) && 4434 ToolChain::getOpenMPTriple(Arg->getValue(0)) == TC->getTriple()) { 4435 Arg->claim(); 4436 unsigned Index = Args.getBaseArgs().MakeIndex(Arg->getValue(1)); 4437 ExtractedArg = getOpts().ParseOneArg(Args, Index); 4438 Arg = ExtractedArg.get(); 4439 } 4440 4441 // Add or remove the seen architectures in order of appearance. If an 4442 // invalid architecture is given we simply exit. 4443 if (Arg->getOption().matches(options::OPT_offload_arch_EQ)) { 4444 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) { 4445 if (Arch == "native" || Arch.empty()) { 4446 auto GPUsOrErr = TC->getSystemGPUArchs(Args); 4447 if (!GPUsOrErr) { 4448 if (SuppressError) 4449 llvm::consumeError(GPUsOrErr.takeError()); 4450 else 4451 TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch) 4452 << llvm::Triple::getArchTypeName(TC->getArch()) 4453 << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch"; 4454 continue; 4455 } 4456 4457 for (auto ArchStr : *GPUsOrErr) { 4458 Archs.insert( 4459 getCanonicalArchString(C, Args, Args.MakeArgString(ArchStr), 4460 TC->getTriple(), SuppressError)); 4461 } 4462 } else { 4463 StringRef ArchStr = getCanonicalArchString( 4464 C, Args, Arch, TC->getTriple(), SuppressError); 4465 if (ArchStr.empty()) 4466 return Archs; 4467 Archs.insert(ArchStr); 4468 } 4469 } 4470 } else if (Arg->getOption().matches(options::OPT_no_offload_arch_EQ)) { 4471 for (StringRef Arch : llvm::split(Arg->getValue(), ",")) { 4472 if (Arch == "all") { 4473 Archs.clear(); 4474 } else { 4475 StringRef ArchStr = getCanonicalArchString( 4476 C, Args, Arch, TC->getTriple(), SuppressError); 4477 if (ArchStr.empty()) 4478 return Archs; 4479 Archs.erase(ArchStr); 4480 } 4481 } 4482 } 4483 } 4484 4485 if (auto ConflictingArchs = 4486 getConflictOffloadArchCombination(Archs, TC->getTriple())) { 4487 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo) 4488 << ConflictingArchs->first << ConflictingArchs->second; 4489 C.setContainsError(); 4490 } 4491 4492 // Skip filling defaults if we're just querying what is availible. 4493 if (SuppressError) 4494 return Archs; 4495 4496 if (Archs.empty()) { 4497 if (Kind == Action::OFK_Cuda) 4498 Archs.insert(CudaArchToString(CudaArch::CudaDefault)); 4499 else if (Kind == Action::OFK_HIP) 4500 Archs.insert(CudaArchToString(CudaArch::HIPDefault)); 4501 else if (Kind == Action::OFK_OpenMP) 4502 Archs.insert(StringRef()); 4503 } else { 4504 Args.ClaimAllArgs(options::OPT_offload_arch_EQ); 4505 Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ); 4506 } 4507 4508 return Archs; 4509 } 4510 4511 Action *Driver::BuildOffloadingActions(Compilation &C, 4512 llvm::opt::DerivedArgList &Args, 4513 const InputTy &Input, 4514 Action *HostAction) const { 4515 // Don't build offloading actions if explicitly disabled or we do not have a 4516 // valid source input and compile action to embed it in. If preprocessing only 4517 // ignore embedding. 4518 if (offloadHostOnly() || !types::isSrcFile(Input.first) || 4519 !(isa<CompileJobAction>(HostAction) || 4520 getFinalPhase(Args) == phases::Preprocess)) 4521 return HostAction; 4522 4523 ActionList OffloadActions; 4524 OffloadAction::DeviceDependences DDeps; 4525 4526 const Action::OffloadKind OffloadKinds[] = { 4527 Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP}; 4528 4529 for (Action::OffloadKind Kind : OffloadKinds) { 4530 SmallVector<const ToolChain *, 2> ToolChains; 4531 ActionList DeviceActions; 4532 4533 auto TCRange = C.getOffloadToolChains(Kind); 4534 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI) 4535 ToolChains.push_back(TI->second); 4536 4537 if (ToolChains.empty()) 4538 continue; 4539 4540 types::ID InputType = Input.first; 4541 const Arg *InputArg = Input.second; 4542 4543 // The toolchain can be active for unsupported file types. 4544 if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) || 4545 (Kind == Action::OFK_HIP && !types::isHIP(InputType))) 4546 continue; 4547 4548 // Get the product of all bound architectures and toolchains. 4549 SmallVector<std::pair<const ToolChain *, StringRef>> TCAndArchs; 4550 for (const ToolChain *TC : ToolChains) 4551 for (StringRef Arch : getOffloadArchs(C, Args, Kind, TC)) 4552 TCAndArchs.push_back(std::make_pair(TC, Arch)); 4553 4554 for (unsigned I = 0, E = TCAndArchs.size(); I != E; ++I) 4555 DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType)); 4556 4557 if (DeviceActions.empty()) 4558 return HostAction; 4559 4560 auto PL = types::getCompilationPhases(*this, Args, InputType); 4561 4562 for (phases::ID Phase : PL) { 4563 if (Phase == phases::Link) { 4564 assert(Phase == PL.back() && "linking must be final compilation step."); 4565 break; 4566 } 4567 4568 auto TCAndArch = TCAndArchs.begin(); 4569 for (Action *&A : DeviceActions) { 4570 if (A->getType() == types::TY_Nothing) 4571 continue; 4572 4573 // Propagate the ToolChain so we can use it in ConstructPhaseAction. 4574 A->propagateDeviceOffloadInfo(Kind, TCAndArch->second.data(), 4575 TCAndArch->first); 4576 A = ConstructPhaseAction(C, Args, Phase, A, Kind); 4577 4578 if (isa<CompileJobAction>(A) && isa<CompileJobAction>(HostAction) && 4579 Kind == Action::OFK_OpenMP && 4580 HostAction->getType() != types::TY_Nothing) { 4581 // OpenMP offloading has a dependency on the host compile action to 4582 // identify which declarations need to be emitted. This shouldn't be 4583 // collapsed with any other actions so we can use it in the device. 4584 HostAction->setCannotBeCollapsedWithNextDependentAction(); 4585 OffloadAction::HostDependence HDep( 4586 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4587 TCAndArch->second.data(), Kind); 4588 OffloadAction::DeviceDependences DDep; 4589 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind); 4590 A = C.MakeAction<OffloadAction>(HDep, DDep); 4591 } 4592 4593 ++TCAndArch; 4594 } 4595 } 4596 4597 // Compiling HIP in non-RDC mode requires linking each action individually. 4598 for (Action *&A : DeviceActions) { 4599 if ((A->getType() != types::TY_Object && 4600 A->getType() != types::TY_LTO_BC) || 4601 Kind != Action::OFK_HIP || 4602 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 4603 continue; 4604 ActionList LinkerInput = {A}; 4605 A = C.MakeAction<LinkJobAction>(LinkerInput, types::TY_Image); 4606 } 4607 4608 auto TCAndArch = TCAndArchs.begin(); 4609 for (Action *A : DeviceActions) { 4610 DDeps.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind); 4611 OffloadAction::DeviceDependences DDep; 4612 DDep.add(*A, *TCAndArch->first, TCAndArch->second.data(), Kind); 4613 OffloadActions.push_back(C.MakeAction<OffloadAction>(DDep, A->getType())); 4614 ++TCAndArch; 4615 } 4616 } 4617 4618 if (offloadDeviceOnly()) 4619 return C.MakeAction<OffloadAction>(DDeps, types::TY_Nothing); 4620 4621 if (OffloadActions.empty()) 4622 return HostAction; 4623 4624 OffloadAction::DeviceDependences DDep; 4625 if (C.isOffloadingHostKind(Action::OFK_Cuda) && 4626 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) { 4627 // If we are not in RDC-mode we just emit the final CUDA fatbinary for 4628 // each translation unit without requiring any linking. 4629 Action *FatbinAction = 4630 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_CUDA_FATBIN); 4631 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_Cuda>(), 4632 nullptr, Action::OFK_Cuda); 4633 } else if (C.isOffloadingHostKind(Action::OFK_HIP) && 4634 !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 4635 false)) { 4636 // If we are not in RDC-mode we just emit the final HIP fatbinary for each 4637 // translation unit, linking each input individually. 4638 Action *FatbinAction = 4639 C.MakeAction<LinkJobAction>(OffloadActions, types::TY_HIP_FATBIN); 4640 DDep.add(*FatbinAction, *C.getSingleOffloadToolChain<Action::OFK_HIP>(), 4641 nullptr, Action::OFK_HIP); 4642 } else { 4643 // Package all the offloading actions into a single output that can be 4644 // embedded in the host and linked. 4645 Action *PackagerAction = 4646 C.MakeAction<OffloadPackagerJobAction>(OffloadActions, types::TY_Image); 4647 DDep.add(*PackagerAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4648 nullptr, C.getActiveOffloadKinds()); 4649 } 4650 4651 // If we are unable to embed a single device output into the host, we need to 4652 // add each device output as a host dependency to ensure they are still built. 4653 bool SingleDeviceOutput = !llvm::any_of(OffloadActions, [](Action *A) { 4654 return A->getType() == types::TY_Nothing; 4655 }) && isa<CompileJobAction>(HostAction); 4656 OffloadAction::HostDependence HDep( 4657 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4658 /*BoundArch=*/nullptr, SingleDeviceOutput ? DDep : DDeps); 4659 return C.MakeAction<OffloadAction>(HDep, SingleDeviceOutput ? DDep : DDeps); 4660 } 4661 4662 Action *Driver::ConstructPhaseAction( 4663 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, 4664 Action::OffloadKind TargetDeviceOffloadKind) const { 4665 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 4666 4667 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 4668 // encode this in the steps because the intermediate type depends on 4669 // arguments. Just special case here. 4670 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) 4671 return Input; 4672 4673 // Build the appropriate action. 4674 switch (Phase) { 4675 case phases::Link: 4676 llvm_unreachable("link action invalid here."); 4677 case phases::IfsMerge: 4678 llvm_unreachable("ifsmerge action invalid here."); 4679 case phases::Preprocess: { 4680 types::ID OutputTy; 4681 // -M and -MM specify the dependency file name by altering the output type, 4682 // -if -MD and -MMD are not specified. 4683 if (Args.hasArg(options::OPT_M, options::OPT_MM) && 4684 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) { 4685 OutputTy = types::TY_Dependencies; 4686 } else { 4687 OutputTy = Input->getType(); 4688 // For these cases, the preprocessor is only translating forms, the Output 4689 // still needs preprocessing. 4690 if (!Args.hasFlag(options::OPT_frewrite_includes, 4691 options::OPT_fno_rewrite_includes, false) && 4692 !Args.hasFlag(options::OPT_frewrite_imports, 4693 options::OPT_fno_rewrite_imports, false) && 4694 !Args.hasFlag(options::OPT_fdirectives_only, 4695 options::OPT_fno_directives_only, false) && 4696 !CCGenDiagnostics) 4697 OutputTy = types::getPreprocessedType(OutputTy); 4698 assert(OutputTy != types::TY_INVALID && 4699 "Cannot preprocess this input type!"); 4700 } 4701 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 4702 } 4703 case phases::Precompile: { 4704 // API extraction should not generate an actual precompilation action. 4705 if (Args.hasArg(options::OPT_extract_api)) 4706 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO); 4707 4708 types::ID OutputTy = getPrecompiledType(Input->getType()); 4709 assert(OutputTy != types::TY_INVALID && 4710 "Cannot precompile this input type!"); 4711 4712 // If we're given a module name, precompile header file inputs as a 4713 // module, not as a precompiled header. 4714 const char *ModName = nullptr; 4715 if (OutputTy == types::TY_PCH) { 4716 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ)) 4717 ModName = A->getValue(); 4718 if (ModName) 4719 OutputTy = types::TY_ModuleFile; 4720 } 4721 4722 if (Args.hasArg(options::OPT_fsyntax_only)) { 4723 // Syntax checks should not emit a PCH file 4724 OutputTy = types::TY_Nothing; 4725 } 4726 4727 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 4728 } 4729 case phases::Compile: { 4730 if (Args.hasArg(options::OPT_fsyntax_only)) 4731 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 4732 if (Args.hasArg(options::OPT_rewrite_objc)) 4733 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 4734 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 4735 return C.MakeAction<CompileJobAction>(Input, 4736 types::TY_RewrittenLegacyObjC); 4737 if (Args.hasArg(options::OPT__analyze)) 4738 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 4739 if (Args.hasArg(options::OPT__migrate)) 4740 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 4741 if (Args.hasArg(options::OPT_emit_ast)) 4742 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 4743 if (Args.hasArg(options::OPT_module_file_info)) 4744 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 4745 if (Args.hasArg(options::OPT_verify_pch)) 4746 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 4747 if (Args.hasArg(options::OPT_extract_api)) 4748 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO); 4749 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 4750 } 4751 case phases::Backend: { 4752 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) { 4753 types::ID Output; 4754 if (Args.hasArg(options::OPT_S)) 4755 Output = types::TY_LTO_IR; 4756 else if (Args.hasArg(options::OPT_ffat_lto_objects)) 4757 Output = types::TY_PP_Asm; 4758 else 4759 Output = types::TY_LTO_BC; 4760 return C.MakeAction<BackendJobAction>(Input, Output); 4761 } 4762 if (isUsingLTO(/* IsOffload */ true) && 4763 TargetDeviceOffloadKind != Action::OFK_None) { 4764 types::ID Output = 4765 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 4766 return C.MakeAction<BackendJobAction>(Input, Output); 4767 } 4768 if (Args.hasArg(options::OPT_emit_llvm) || 4769 (((Input->getOffloadingToolChain() && 4770 Input->getOffloadingToolChain()->getTriple().isAMDGPU()) || 4771 TargetDeviceOffloadKind == Action::OFK_HIP) && 4772 (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 4773 false) || 4774 TargetDeviceOffloadKind == Action::OFK_OpenMP))) { 4775 types::ID Output = 4776 Args.hasArg(options::OPT_S) && 4777 (TargetDeviceOffloadKind == Action::OFK_None || 4778 offloadDeviceOnly() || 4779 (TargetDeviceOffloadKind == Action::OFK_HIP && 4780 !Args.hasFlag(options::OPT_offload_new_driver, 4781 options::OPT_no_offload_new_driver, false))) 4782 ? types::TY_LLVM_IR 4783 : types::TY_LLVM_BC; 4784 return C.MakeAction<BackendJobAction>(Input, Output); 4785 } 4786 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 4787 } 4788 case phases::Assemble: 4789 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 4790 } 4791 4792 llvm_unreachable("invalid phase in ConstructPhaseAction"); 4793 } 4794 4795 void Driver::BuildJobs(Compilation &C) const { 4796 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4797 4798 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 4799 4800 // It is an error to provide a -o option if we are making multiple output 4801 // files. There are exceptions: 4802 // 4803 // IfsMergeJob: when generating interface stubs enabled we want to be able to 4804 // generate the stub file at the same time that we generate the real 4805 // library/a.out. So when a .o, .so, etc are the output, with clang interface 4806 // stubs there will also be a .ifs and .ifso at the same location. 4807 // 4808 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled 4809 // and -c is passed, we still want to be able to generate a .ifs file while 4810 // we are also generating .o files. So we allow more than one output file in 4811 // this case as well. 4812 // 4813 // OffloadClass of type TY_Nothing: device-only output will place many outputs 4814 // into a single offloading action. We should count all inputs to the action 4815 // as outputs. Also ignore device-only outputs if we're compiling with 4816 // -fsyntax-only. 4817 if (FinalOutput) { 4818 unsigned NumOutputs = 0; 4819 unsigned NumIfsOutputs = 0; 4820 for (const Action *A : C.getActions()) { 4821 if (A->getType() != types::TY_Nothing && 4822 A->getType() != types::TY_DX_CONTAINER && 4823 !(A->getKind() == Action::IfsMergeJobClass || 4824 (A->getType() == clang::driver::types::TY_IFS_CPP && 4825 A->getKind() == clang::driver::Action::CompileJobClass && 4826 0 == NumIfsOutputs++) || 4827 (A->getKind() == Action::BindArchClass && A->getInputs().size() && 4828 A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) 4829 ++NumOutputs; 4830 else if (A->getKind() == Action::OffloadClass && 4831 A->getType() == types::TY_Nothing && 4832 !C.getArgs().hasArg(options::OPT_fsyntax_only)) 4833 NumOutputs += A->size(); 4834 } 4835 4836 if (NumOutputs > 1) { 4837 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 4838 FinalOutput = nullptr; 4839 } 4840 } 4841 4842 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); 4843 4844 // Collect the list of architectures. 4845 llvm::StringSet<> ArchNames; 4846 if (RawTriple.isOSBinFormatMachO()) 4847 for (const Arg *A : C.getArgs()) 4848 if (A->getOption().matches(options::OPT_arch)) 4849 ArchNames.insert(A->getValue()); 4850 4851 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 4852 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults; 4853 for (Action *A : C.getActions()) { 4854 // If we are linking an image for multiple archs then the linker wants 4855 // -arch_multiple and -final_output <final image name>. Unfortunately, this 4856 // doesn't fit in cleanly because we have to pass this information down. 4857 // 4858 // FIXME: This is a hack; find a cleaner way to integrate this into the 4859 // process. 4860 const char *LinkingOutput = nullptr; 4861 if (isa<LipoJobAction>(A)) { 4862 if (FinalOutput) 4863 LinkingOutput = FinalOutput->getValue(); 4864 else 4865 LinkingOutput = getDefaultImageName(); 4866 } 4867 4868 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 4869 /*BoundArch*/ StringRef(), 4870 /*AtTopLevel*/ true, 4871 /*MultipleArchs*/ ArchNames.size() > 1, 4872 /*LinkingOutput*/ LinkingOutput, CachedResults, 4873 /*TargetDeviceOffloadKind*/ Action::OFK_None); 4874 } 4875 4876 // If we have more than one job, then disable integrated-cc1 for now. Do this 4877 // also when we need to report process execution statistics. 4878 if (C.getJobs().size() > 1 || CCPrintProcessStats) 4879 for (auto &J : C.getJobs()) 4880 J.InProcess = false; 4881 4882 if (CCPrintProcessStats) { 4883 C.setPostCallback([=](const Command &Cmd, int Res) { 4884 std::optional<llvm::sys::ProcessStatistics> ProcStat = 4885 Cmd.getProcessStatistics(); 4886 if (!ProcStat) 4887 return; 4888 4889 const char *LinkingOutput = nullptr; 4890 if (FinalOutput) 4891 LinkingOutput = FinalOutput->getValue(); 4892 else if (!Cmd.getOutputFilenames().empty()) 4893 LinkingOutput = Cmd.getOutputFilenames().front().c_str(); 4894 else 4895 LinkingOutput = getDefaultImageName(); 4896 4897 if (CCPrintStatReportFilename.empty()) { 4898 using namespace llvm; 4899 // Human readable output. 4900 outs() << sys::path::filename(Cmd.getExecutable()) << ": " 4901 << "output=" << LinkingOutput; 4902 outs() << ", total=" 4903 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms" 4904 << ", user=" 4905 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms" 4906 << ", mem=" << ProcStat->PeakMemory << " Kb\n"; 4907 } else { 4908 // CSV format. 4909 std::string Buffer; 4910 llvm::raw_string_ostream Out(Buffer); 4911 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()), 4912 /*Quote*/ true); 4913 Out << ','; 4914 llvm::sys::printArg(Out, LinkingOutput, true); 4915 Out << ',' << ProcStat->TotalTime.count() << ',' 4916 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory 4917 << '\n'; 4918 Out.flush(); 4919 std::error_code EC; 4920 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, 4921 llvm::sys::fs::OF_Append | 4922 llvm::sys::fs::OF_Text); 4923 if (EC) 4924 return; 4925 auto L = OS.lock(); 4926 if (!L) { 4927 llvm::errs() << "ERROR: Cannot lock file " 4928 << CCPrintStatReportFilename << ": " 4929 << toString(L.takeError()) << "\n"; 4930 return; 4931 } 4932 OS << Buffer; 4933 OS.flush(); 4934 } 4935 }); 4936 } 4937 4938 // If the user passed -Qunused-arguments or there were errors, don't warn 4939 // about any unused arguments. 4940 if (Diags.hasErrorOccurred() || 4941 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 4942 return; 4943 4944 // Claim -fdriver-only here. 4945 (void)C.getArgs().hasArg(options::OPT_fdriver_only); 4946 // Claim -### here. 4947 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 4948 4949 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 4950 (void)C.getArgs().hasArg(options::OPT_driver_mode); 4951 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 4952 4953 bool HasAssembleJob = llvm::any_of(C.getJobs(), [](auto &J) { 4954 // Match ClangAs and other derived assemblers of Tool. ClangAs uses a 4955 // longer ShortName "clang integrated assembler" while other assemblers just 4956 // use "assembler". 4957 return strstr(J.getCreator().getShortName(), "assembler"); 4958 }); 4959 for (Arg *A : C.getArgs()) { 4960 // FIXME: It would be nice to be able to send the argument to the 4961 // DiagnosticsEngine, so that extra values, position, and so on could be 4962 // printed. 4963 if (!A->isClaimed()) { 4964 if (A->getOption().hasFlag(options::NoArgumentUnused)) 4965 continue; 4966 4967 // Suppress the warning automatically if this is just a flag, and it is an 4968 // instance of an argument we already claimed. 4969 const Option &Opt = A->getOption(); 4970 if (Opt.getKind() == Option::FlagClass) { 4971 bool DuplicateClaimed = false; 4972 4973 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 4974 if (AA->isClaimed()) { 4975 DuplicateClaimed = true; 4976 break; 4977 } 4978 } 4979 4980 if (DuplicateClaimed) 4981 continue; 4982 } 4983 4984 // In clang-cl, don't mention unknown arguments here since they have 4985 // already been warned about. 4986 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) { 4987 if (A->getOption().hasFlag(options::TargetSpecific) && 4988 !A->isIgnoredTargetSpecific() && !HasAssembleJob && 4989 // When for example -### or -v is used 4990 // without a file, target specific options are not 4991 // consumed/validated. 4992 // Instead emitting an error emit a warning instead. 4993 !C.getActions().empty()) { 4994 Diag(diag::err_drv_unsupported_opt_for_target) 4995 << A->getSpelling() << getTargetTriple(); 4996 } else { 4997 Diag(clang::diag::warn_drv_unused_argument) 4998 << A->getAsString(C.getArgs()); 4999 } 5000 } 5001 } 5002 } 5003 } 5004 5005 namespace { 5006 /// Utility class to control the collapse of dependent actions and select the 5007 /// tools accordingly. 5008 class ToolSelector final { 5009 /// The tool chain this selector refers to. 5010 const ToolChain &TC; 5011 5012 /// The compilation this selector refers to. 5013 const Compilation &C; 5014 5015 /// The base action this selector refers to. 5016 const JobAction *BaseAction; 5017 5018 /// Set to true if the current toolchain refers to host actions. 5019 bool IsHostSelector; 5020 5021 /// Set to true if save-temps and embed-bitcode functionalities are active. 5022 bool SaveTemps; 5023 bool EmbedBitcode; 5024 5025 /// Get previous dependent action or null if that does not exist. If 5026 /// \a CanBeCollapsed is false, that action must be legal to collapse or 5027 /// null will be returned. 5028 const JobAction *getPrevDependentAction(const ActionList &Inputs, 5029 ActionList &SavedOffloadAction, 5030 bool CanBeCollapsed = true) { 5031 // An option can be collapsed only if it has a single input. 5032 if (Inputs.size() != 1) 5033 return nullptr; 5034 5035 Action *CurAction = *Inputs.begin(); 5036 if (CanBeCollapsed && 5037 !CurAction->isCollapsingWithNextDependentActionLegal()) 5038 return nullptr; 5039 5040 // If the input action is an offload action. Look through it and save any 5041 // offload action that can be dropped in the event of a collapse. 5042 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 5043 // If the dependent action is a device action, we will attempt to collapse 5044 // only with other device actions. Otherwise, we would do the same but 5045 // with host actions only. 5046 if (!IsHostSelector) { 5047 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { 5048 CurAction = 5049 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); 5050 if (CanBeCollapsed && 5051 !CurAction->isCollapsingWithNextDependentActionLegal()) 5052 return nullptr; 5053 SavedOffloadAction.push_back(OA); 5054 return dyn_cast<JobAction>(CurAction); 5055 } 5056 } else if (OA->hasHostDependence()) { 5057 CurAction = OA->getHostDependence(); 5058 if (CanBeCollapsed && 5059 !CurAction->isCollapsingWithNextDependentActionLegal()) 5060 return nullptr; 5061 SavedOffloadAction.push_back(OA); 5062 return dyn_cast<JobAction>(CurAction); 5063 } 5064 return nullptr; 5065 } 5066 5067 return dyn_cast<JobAction>(CurAction); 5068 } 5069 5070 /// Return true if an assemble action can be collapsed. 5071 bool canCollapseAssembleAction() const { 5072 return TC.useIntegratedAs() && !SaveTemps && 5073 !C.getArgs().hasArg(options::OPT_via_file_asm) && 5074 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 5075 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && 5076 !C.getArgs().hasArg(options::OPT_dxc_Fc); 5077 } 5078 5079 /// Return true if a preprocessor action can be collapsed. 5080 bool canCollapsePreprocessorAction() const { 5081 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 5082 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 5083 !C.getArgs().hasArg(options::OPT_rewrite_objc); 5084 } 5085 5086 /// Struct that relates an action with the offload actions that would be 5087 /// collapsed with it. 5088 struct JobActionInfo final { 5089 /// The action this info refers to. 5090 const JobAction *JA = nullptr; 5091 /// The offload actions we need to take care off if this action is 5092 /// collapsed. 5093 ActionList SavedOffloadAction; 5094 }; 5095 5096 /// Append collapsed offload actions from the give nnumber of elements in the 5097 /// action info array. 5098 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, 5099 ArrayRef<JobActionInfo> &ActionInfo, 5100 unsigned ElementNum) { 5101 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements."); 5102 for (unsigned I = 0; I < ElementNum; ++I) 5103 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(), 5104 ActionInfo[I].SavedOffloadAction.end()); 5105 } 5106 5107 /// Functions that attempt to perform the combining. They detect if that is 5108 /// legal, and if so they update the inputs \a Inputs and the offload action 5109 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with 5110 /// the combined action is returned. If the combining is not legal or if the 5111 /// tool does not exist, null is returned. 5112 /// Currently three kinds of collapsing are supported: 5113 /// - Assemble + Backend + Compile; 5114 /// - Assemble + Backend ; 5115 /// - Backend + Compile. 5116 const Tool * 5117 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 5118 ActionList &Inputs, 5119 ActionList &CollapsedOffloadAction) { 5120 if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) 5121 return nullptr; 5122 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 5123 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 5124 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA); 5125 if (!AJ || !BJ || !CJ) 5126 return nullptr; 5127 5128 // Get compiler tool. 5129 const Tool *T = TC.SelectTool(*CJ); 5130 if (!T) 5131 return nullptr; 5132 5133 // Can't collapse if we don't have codegen support unless we are 5134 // emitting LLVM IR. 5135 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 5136 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 5137 return nullptr; 5138 5139 // When using -fembed-bitcode, it is required to have the same tool (clang) 5140 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 5141 if (EmbedBitcode) { 5142 const Tool *BT = TC.SelectTool(*BJ); 5143 if (BT == T) 5144 return nullptr; 5145 } 5146 5147 if (!T->hasIntegratedAssembler()) 5148 return nullptr; 5149 5150 Inputs = CJ->getInputs(); 5151 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 5152 /*NumElements=*/3); 5153 return T; 5154 } 5155 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, 5156 ActionList &Inputs, 5157 ActionList &CollapsedOffloadAction) { 5158 if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) 5159 return nullptr; 5160 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 5161 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 5162 if (!AJ || !BJ) 5163 return nullptr; 5164 5165 // Get backend tool. 5166 const Tool *T = TC.SelectTool(*BJ); 5167 if (!T) 5168 return nullptr; 5169 5170 if (!T->hasIntegratedAssembler()) 5171 return nullptr; 5172 5173 Inputs = BJ->getInputs(); 5174 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 5175 /*NumElements=*/2); 5176 return T; 5177 } 5178 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 5179 ActionList &Inputs, 5180 ActionList &CollapsedOffloadAction) { 5181 if (ActionInfo.size() < 2) 5182 return nullptr; 5183 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA); 5184 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA); 5185 if (!BJ || !CJ) 5186 return nullptr; 5187 5188 // Check if the initial input (to the compile job or its predessor if one 5189 // exists) is LLVM bitcode. In that case, no preprocessor step is required 5190 // and we can still collapse the compile and backend jobs when we have 5191 // -save-temps. I.e. there is no need for a separate compile job just to 5192 // emit unoptimized bitcode. 5193 bool InputIsBitcode = true; 5194 for (size_t i = 1; i < ActionInfo.size(); i++) 5195 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC && 5196 ActionInfo[i].JA->getType() != types::TY_LTO_BC) { 5197 InputIsBitcode = false; 5198 break; 5199 } 5200 if (!InputIsBitcode && !canCollapsePreprocessorAction()) 5201 return nullptr; 5202 5203 // Get compiler tool. 5204 const Tool *T = TC.SelectTool(*CJ); 5205 if (!T) 5206 return nullptr; 5207 5208 // Can't collapse if we don't have codegen support unless we are 5209 // emitting LLVM IR. 5210 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 5211 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 5212 return nullptr; 5213 5214 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode)) 5215 return nullptr; 5216 5217 Inputs = CJ->getInputs(); 5218 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 5219 /*NumElements=*/2); 5220 return T; 5221 } 5222 5223 /// Updates the inputs if the obtained tool supports combining with 5224 /// preprocessor action, and the current input is indeed a preprocessor 5225 /// action. If combining results in the collapse of offloading actions, those 5226 /// are appended to \a CollapsedOffloadAction. 5227 void combineWithPreprocessor(const Tool *T, ActionList &Inputs, 5228 ActionList &CollapsedOffloadAction) { 5229 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) 5230 return; 5231 5232 // Attempt to get a preprocessor action dependence. 5233 ActionList PreprocessJobOffloadActions; 5234 ActionList NewInputs; 5235 for (Action *A : Inputs) { 5236 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions); 5237 if (!PJ || !isa<PreprocessJobAction>(PJ)) { 5238 NewInputs.push_back(A); 5239 continue; 5240 } 5241 5242 // This is legal to combine. Append any offload action we found and add the 5243 // current input to preprocessor inputs. 5244 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(), 5245 PreprocessJobOffloadActions.end()); 5246 NewInputs.append(PJ->input_begin(), PJ->input_end()); 5247 } 5248 Inputs = NewInputs; 5249 } 5250 5251 public: 5252 ToolSelector(const JobAction *BaseAction, const ToolChain &TC, 5253 const Compilation &C, bool SaveTemps, bool EmbedBitcode) 5254 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), 5255 EmbedBitcode(EmbedBitcode) { 5256 assert(BaseAction && "Invalid base action."); 5257 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; 5258 } 5259 5260 /// Check if a chain of actions can be combined and return the tool that can 5261 /// handle the combination of actions. The pointer to the current inputs \a 5262 /// Inputs and the list of offload actions \a CollapsedOffloadActions 5263 /// connected to collapsed actions are updated accordingly. The latter enables 5264 /// the caller of the selector to process them afterwards instead of just 5265 /// dropping them. If no suitable tool is found, null will be returned. 5266 const Tool *getTool(ActionList &Inputs, 5267 ActionList &CollapsedOffloadAction) { 5268 // 5269 // Get the largest chain of actions that we could combine. 5270 // 5271 5272 SmallVector<JobActionInfo, 5> ActionChain(1); 5273 ActionChain.back().JA = BaseAction; 5274 while (ActionChain.back().JA) { 5275 const Action *CurAction = ActionChain.back().JA; 5276 5277 // Grow the chain by one element. 5278 ActionChain.resize(ActionChain.size() + 1); 5279 JobActionInfo &AI = ActionChain.back(); 5280 5281 // Attempt to fill it with the 5282 AI.JA = 5283 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction); 5284 } 5285 5286 // Pop the last action info as it could not be filled. 5287 ActionChain.pop_back(); 5288 5289 // 5290 // Attempt to combine actions. If all combining attempts failed, just return 5291 // the tool of the provided action. At the end we attempt to combine the 5292 // action with any preprocessor action it may depend on. 5293 // 5294 5295 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs, 5296 CollapsedOffloadAction); 5297 if (!T) 5298 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction); 5299 if (!T) 5300 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction); 5301 if (!T) { 5302 Inputs = BaseAction->getInputs(); 5303 T = TC.SelectTool(*BaseAction); 5304 } 5305 5306 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); 5307 return T; 5308 } 5309 }; 5310 } 5311 5312 /// Return a string that uniquely identifies the result of a job. The bound arch 5313 /// is not necessarily represented in the toolchain's triple -- for example, 5314 /// armv7 and armv7s both map to the same triple -- so we need both in our map. 5315 /// Also, we need to add the offloading device kind, as the same tool chain can 5316 /// be used for host and device for some programming models, e.g. OpenMP. 5317 static std::string GetTriplePlusArchString(const ToolChain *TC, 5318 StringRef BoundArch, 5319 Action::OffloadKind OffloadKind) { 5320 std::string TriplePlusArch = TC->getTriple().normalize(); 5321 if (!BoundArch.empty()) { 5322 TriplePlusArch += "-"; 5323 TriplePlusArch += BoundArch; 5324 } 5325 TriplePlusArch += "-"; 5326 TriplePlusArch += Action::GetOffloadKindName(OffloadKind); 5327 return TriplePlusArch; 5328 } 5329 5330 InputInfoList Driver::BuildJobsForAction( 5331 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 5332 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 5333 std::map<std::pair<const Action *, std::string>, InputInfoList> 5334 &CachedResults, 5335 Action::OffloadKind TargetDeviceOffloadKind) const { 5336 std::pair<const Action *, std::string> ActionTC = { 5337 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5338 auto CachedResult = CachedResults.find(ActionTC); 5339 if (CachedResult != CachedResults.end()) { 5340 return CachedResult->second; 5341 } 5342 InputInfoList Result = BuildJobsForActionNoCache( 5343 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 5344 CachedResults, TargetDeviceOffloadKind); 5345 CachedResults[ActionTC] = Result; 5346 return Result; 5347 } 5348 5349 static void handleTimeTrace(Compilation &C, const ArgList &Args, 5350 const JobAction *JA, const char *BaseInput, 5351 const InputInfo &Result) { 5352 Arg *A = 5353 Args.getLastArg(options::OPT_ftime_trace, options::OPT_ftime_trace_EQ); 5354 if (!A) 5355 return; 5356 SmallString<128> Path; 5357 if (A->getOption().matches(options::OPT_ftime_trace_EQ)) { 5358 Path = A->getValue(); 5359 if (llvm::sys::fs::is_directory(Path)) { 5360 SmallString<128> Tmp(Result.getFilename()); 5361 llvm::sys::path::replace_extension(Tmp, "json"); 5362 llvm::sys::path::append(Path, llvm::sys::path::filename(Tmp)); 5363 } 5364 } else { 5365 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) { 5366 // The trace file is ${dumpdir}${basename}.json. Note that dumpdir may not 5367 // end with a path separator. 5368 Path = DumpDir->getValue(); 5369 Path += llvm::sys::path::filename(BaseInput); 5370 } else { 5371 Path = Result.getFilename(); 5372 } 5373 llvm::sys::path::replace_extension(Path, "json"); 5374 } 5375 const char *ResultFile = C.getArgs().MakeArgString(Path); 5376 C.addTimeTraceFile(ResultFile, JA); 5377 C.addResultFile(ResultFile, JA); 5378 } 5379 5380 InputInfoList Driver::BuildJobsForActionNoCache( 5381 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 5382 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 5383 std::map<std::pair<const Action *, std::string>, InputInfoList> 5384 &CachedResults, 5385 Action::OffloadKind TargetDeviceOffloadKind) const { 5386 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 5387 5388 InputInfoList OffloadDependencesInputInfo; 5389 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; 5390 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 5391 // The 'Darwin' toolchain is initialized only when its arguments are 5392 // computed. Get the default arguments for OFK_None to ensure that 5393 // initialization is performed before processing the offload action. 5394 // FIXME: Remove when darwin's toolchain is initialized during construction. 5395 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None); 5396 5397 // The offload action is expected to be used in four different situations. 5398 // 5399 // a) Set a toolchain/architecture/kind for a host action: 5400 // Host Action 1 -> OffloadAction -> Host Action 2 5401 // 5402 // b) Set a toolchain/architecture/kind for a device action; 5403 // Device Action 1 -> OffloadAction -> Device Action 2 5404 // 5405 // c) Specify a device dependence to a host action; 5406 // Device Action 1 _ 5407 // \ 5408 // Host Action 1 ---> OffloadAction -> Host Action 2 5409 // 5410 // d) Specify a host dependence to a device action. 5411 // Host Action 1 _ 5412 // \ 5413 // Device Action 1 ---> OffloadAction -> Device Action 2 5414 // 5415 // For a) and b), we just return the job generated for the dependences. For 5416 // c) and d) we override the current action with the host/device dependence 5417 // if the current toolchain is host/device and set the offload dependences 5418 // info with the jobs obtained from the device/host dependence(s). 5419 5420 // If there is a single device option or has no host action, just generate 5421 // the job for it. 5422 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) { 5423 InputInfoList DevA; 5424 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 5425 const char *DepBoundArch) { 5426 DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 5427 /*MultipleArchs*/ !!DepBoundArch, 5428 LinkingOutput, CachedResults, 5429 DepA->getOffloadingDeviceKind())); 5430 }); 5431 return DevA; 5432 } 5433 5434 // If 'Action 2' is host, we generate jobs for the device dependences and 5435 // override the current action with the host dependence. Otherwise, we 5436 // generate the host dependences and override the action with the device 5437 // dependence. The dependences can't therefore be a top-level action. 5438 OA->doOnEachDependence( 5439 /*IsHostDependence=*/BuildingForOffloadDevice, 5440 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 5441 OffloadDependencesInputInfo.append(BuildJobsForAction( 5442 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 5443 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 5444 DepA->getOffloadingDeviceKind())); 5445 }); 5446 5447 A = BuildingForOffloadDevice 5448 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 5449 : OA->getHostDependence(); 5450 5451 // We may have already built this action as a part of the offloading 5452 // toolchain, return the cached input if so. 5453 std::pair<const Action *, std::string> ActionTC = { 5454 OA->getHostDependence(), 5455 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5456 if (CachedResults.find(ActionTC) != CachedResults.end()) { 5457 InputInfoList Inputs = CachedResults[ActionTC]; 5458 Inputs.append(OffloadDependencesInputInfo); 5459 return Inputs; 5460 } 5461 } 5462 5463 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 5464 // FIXME: It would be nice to not claim this here; maybe the old scheme of 5465 // just using Args was better? 5466 const Arg &Input = IA->getInputArg(); 5467 Input.claim(); 5468 if (Input.getOption().matches(options::OPT_INPUT)) { 5469 const char *Name = Input.getValue(); 5470 return {InputInfo(A, Name, /* _BaseInput = */ Name)}; 5471 } 5472 return {InputInfo(A, &Input, /* _BaseInput = */ "")}; 5473 } 5474 5475 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 5476 const ToolChain *TC; 5477 StringRef ArchName = BAA->getArchName(); 5478 5479 if (!ArchName.empty()) 5480 TC = &getToolChain(C.getArgs(), 5481 computeTargetTriple(*this, TargetTriple, 5482 C.getArgs(), ArchName)); 5483 else 5484 TC = &C.getDefaultToolChain(); 5485 5486 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 5487 MultipleArchs, LinkingOutput, CachedResults, 5488 TargetDeviceOffloadKind); 5489 } 5490 5491 5492 ActionList Inputs = A->getInputs(); 5493 5494 const JobAction *JA = cast<JobAction>(A); 5495 ActionList CollapsedOffloadActions; 5496 5497 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), 5498 embedBitcodeInObject() && !isUsingLTO()); 5499 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions); 5500 5501 if (!T) 5502 return {InputInfo()}; 5503 5504 // If we've collapsed action list that contained OffloadAction we 5505 // need to build jobs for host/device-side inputs it may have held. 5506 for (const auto *OA : CollapsedOffloadActions) 5507 cast<OffloadAction>(OA)->doOnEachDependence( 5508 /*IsHostDependence=*/BuildingForOffloadDevice, 5509 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 5510 OffloadDependencesInputInfo.append(BuildJobsForAction( 5511 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, 5512 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 5513 DepA->getOffloadingDeviceKind())); 5514 }); 5515 5516 // Only use pipes when there is exactly one input. 5517 InputInfoList InputInfos; 5518 for (const Action *Input : Inputs) { 5519 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 5520 // shouldn't get temporary output names. 5521 // FIXME: Clean this up. 5522 bool SubJobAtTopLevel = 5523 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 5524 InputInfos.append(BuildJobsForAction( 5525 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 5526 CachedResults, A->getOffloadingDeviceKind())); 5527 } 5528 5529 // Always use the first file input as the base input. 5530 const char *BaseInput = InputInfos[0].getBaseInput(); 5531 for (auto &Info : InputInfos) { 5532 if (Info.isFilename()) { 5533 BaseInput = Info.getBaseInput(); 5534 break; 5535 } 5536 } 5537 5538 // ... except dsymutil actions, which use their actual input as the base 5539 // input. 5540 if (JA->getType() == types::TY_dSYM) 5541 BaseInput = InputInfos[0].getFilename(); 5542 5543 // Append outputs of offload device jobs to the input list 5544 if (!OffloadDependencesInputInfo.empty()) 5545 InputInfos.append(OffloadDependencesInputInfo.begin(), 5546 OffloadDependencesInputInfo.end()); 5547 5548 // Set the effective triple of the toolchain for the duration of this job. 5549 llvm::Triple EffectiveTriple; 5550 const ToolChain &ToolTC = T->getToolChain(); 5551 const ArgList &Args = 5552 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind()); 5553 if (InputInfos.size() != 1) { 5554 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 5555 } else { 5556 // Pass along the input type if it can be unambiguously determined. 5557 EffectiveTriple = llvm::Triple( 5558 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 5559 } 5560 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 5561 5562 // Determine the place to write output to, if any. 5563 InputInfo Result; 5564 InputInfoList UnbundlingResults; 5565 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) { 5566 // If we have an unbundling job, we need to create results for all the 5567 // outputs. We also update the results cache so that other actions using 5568 // this unbundling action can get the right results. 5569 for (auto &UI : UA->getDependentActionsInfo()) { 5570 assert(UI.DependentOffloadKind != Action::OFK_None && 5571 "Unbundling with no offloading??"); 5572 5573 // Unbundling actions are never at the top level. When we generate the 5574 // offloading prefix, we also do that for the host file because the 5575 // unbundling action does not change the type of the output which can 5576 // cause a overwrite. 5577 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5578 UI.DependentOffloadKind, 5579 UI.DependentToolChain->getTriple().normalize(), 5580 /*CreatePrefixForHost=*/true); 5581 auto CurI = InputInfo( 5582 UA, 5583 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch, 5584 /*AtTopLevel=*/false, 5585 MultipleArchs || 5586 UI.DependentOffloadKind == Action::OFK_HIP, 5587 OffloadingPrefix), 5588 BaseInput); 5589 // Save the unbundling result. 5590 UnbundlingResults.push_back(CurI); 5591 5592 // Get the unique string identifier for this dependence and cache the 5593 // result. 5594 StringRef Arch; 5595 if (TargetDeviceOffloadKind == Action::OFK_HIP) { 5596 if (UI.DependentOffloadKind == Action::OFK_Host) 5597 Arch = StringRef(); 5598 else 5599 Arch = UI.DependentBoundArch; 5600 } else 5601 Arch = BoundArch; 5602 5603 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch, 5604 UI.DependentOffloadKind)}] = { 5605 CurI}; 5606 } 5607 5608 // Now that we have all the results generated, select the one that should be 5609 // returned for the current depending action. 5610 std::pair<const Action *, std::string> ActionTC = { 5611 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5612 assert(CachedResults.find(ActionTC) != CachedResults.end() && 5613 "Result does not exist??"); 5614 Result = CachedResults[ActionTC].front(); 5615 } else if (JA->getType() == types::TY_Nothing) 5616 Result = {InputInfo(A, BaseInput)}; 5617 else { 5618 // We only have to generate a prefix for the host if this is not a top-level 5619 // action. 5620 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5621 A->getOffloadingDeviceKind(), TC->getTriple().normalize(), 5622 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(A) || 5623 !(A->getOffloadingHostActiveKinds() == Action::OFK_None || 5624 AtTopLevel)); 5625 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 5626 AtTopLevel, MultipleArchs, 5627 OffloadingPrefix), 5628 BaseInput); 5629 if (T->canEmitIR() && OffloadingPrefix.empty()) 5630 handleTimeTrace(C, Args, JA, BaseInput, Result); 5631 } 5632 5633 if (CCCPrintBindings && !CCGenDiagnostics) { 5634 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 5635 << " - \"" << T->getName() << "\", inputs: ["; 5636 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 5637 llvm::errs() << InputInfos[i].getAsString(); 5638 if (i + 1 != e) 5639 llvm::errs() << ", "; 5640 } 5641 if (UnbundlingResults.empty()) 5642 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 5643 else { 5644 llvm::errs() << "], outputs: ["; 5645 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { 5646 llvm::errs() << UnbundlingResults[i].getAsString(); 5647 if (i + 1 != e) 5648 llvm::errs() << ", "; 5649 } 5650 llvm::errs() << "] \n"; 5651 } 5652 } else { 5653 if (UnbundlingResults.empty()) 5654 T->ConstructJob( 5655 C, *JA, Result, InputInfos, 5656 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5657 LinkingOutput); 5658 else 5659 T->ConstructJobMultipleOutputs( 5660 C, *JA, UnbundlingResults, InputInfos, 5661 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5662 LinkingOutput); 5663 } 5664 return {Result}; 5665 } 5666 5667 const char *Driver::getDefaultImageName() const { 5668 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 5669 return Target.isOSWindows() ? "a.exe" : "a.out"; 5670 } 5671 5672 /// Create output filename based on ArgValue, which could either be a 5673 /// full filename, filename without extension, or a directory. If ArgValue 5674 /// does not provide a filename, then use BaseName, and use the extension 5675 /// suitable for FileType. 5676 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 5677 StringRef BaseName, 5678 types::ID FileType) { 5679 SmallString<128> Filename = ArgValue; 5680 5681 if (ArgValue.empty()) { 5682 // If the argument is empty, output to BaseName in the current dir. 5683 Filename = BaseName; 5684 } else if (llvm::sys::path::is_separator(Filename.back())) { 5685 // If the argument is a directory, output to BaseName in that dir. 5686 llvm::sys::path::append(Filename, BaseName); 5687 } 5688 5689 if (!llvm::sys::path::has_extension(ArgValue)) { 5690 // If the argument didn't provide an extension, then set it. 5691 const char *Extension = types::getTypeTempSuffix(FileType, true); 5692 5693 if (FileType == types::TY_Image && 5694 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 5695 // The output file is a dll. 5696 Extension = "dll"; 5697 } 5698 5699 llvm::sys::path::replace_extension(Filename, Extension); 5700 } 5701 5702 return Args.MakeArgString(Filename.c_str()); 5703 } 5704 5705 static bool HasPreprocessOutput(const Action &JA) { 5706 if (isa<PreprocessJobAction>(JA)) 5707 return true; 5708 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0])) 5709 return true; 5710 if (isa<OffloadBundlingJobAction>(JA) && 5711 HasPreprocessOutput(*(JA.getInputs()[0]))) 5712 return true; 5713 return false; 5714 } 5715 5716 const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix, 5717 StringRef Suffix, bool MultipleArchs, 5718 StringRef BoundArch, 5719 bool NeedUniqueDirectory) const { 5720 SmallString<128> TmpName; 5721 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir); 5722 std::optional<std::string> CrashDirectory = 5723 CCGenDiagnostics && A 5724 ? std::string(A->getValue()) 5725 : llvm::sys::Process::GetEnv("CLANG_CRASH_DIAGNOSTICS_DIR"); 5726 if (CrashDirectory) { 5727 if (!getVFS().exists(*CrashDirectory)) 5728 llvm::sys::fs::create_directories(*CrashDirectory); 5729 SmallString<128> Path(*CrashDirectory); 5730 llvm::sys::path::append(Path, Prefix); 5731 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%"; 5732 if (std::error_code EC = 5733 llvm::sys::fs::createUniqueFile(Path + Middle + Suffix, TmpName)) { 5734 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5735 return ""; 5736 } 5737 } else { 5738 if (MultipleArchs && !BoundArch.empty()) { 5739 if (NeedUniqueDirectory) { 5740 TmpName = GetTemporaryDirectory(Prefix); 5741 llvm::sys::path::append(TmpName, 5742 Twine(Prefix) + "-" + BoundArch + "." + Suffix); 5743 } else { 5744 TmpName = 5745 GetTemporaryPath((Twine(Prefix) + "-" + BoundArch).str(), Suffix); 5746 } 5747 5748 } else { 5749 TmpName = GetTemporaryPath(Prefix, Suffix); 5750 } 5751 } 5752 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5753 } 5754 5755 // Calculate the output path of the module file when compiling a module unit 5756 // with the `-fmodule-output` option or `-fmodule-output=` option specified. 5757 // The behavior is: 5758 // - If `-fmodule-output=` is specfied, then the module file is 5759 // writing to the value. 5760 // - Otherwise if the output object file of the module unit is specified, the 5761 // output path 5762 // of the module file should be the same with the output object file except 5763 // the corresponding suffix. This requires both `-o` and `-c` are specified. 5764 // - Otherwise, the output path of the module file will be the same with the 5765 // input with the corresponding suffix. 5766 static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA, 5767 const char *BaseInput) { 5768 assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile && 5769 (C.getArgs().hasArg(options::OPT_fmodule_output) || 5770 C.getArgs().hasArg(options::OPT_fmodule_output_EQ))); 5771 5772 if (Arg *ModuleOutputEQ = 5773 C.getArgs().getLastArg(options::OPT_fmodule_output_EQ)) 5774 return C.addResultFile(ModuleOutputEQ->getValue(), &JA); 5775 5776 SmallString<64> OutputPath; 5777 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 5778 if (FinalOutput && C.getArgs().hasArg(options::OPT_c)) 5779 OutputPath = FinalOutput->getValue(); 5780 else 5781 OutputPath = BaseInput; 5782 5783 const char *Extension = types::getTypeTempSuffix(JA.getType()); 5784 llvm::sys::path::replace_extension(OutputPath, Extension); 5785 return C.addResultFile(C.getArgs().MakeArgString(OutputPath.c_str()), &JA); 5786 } 5787 5788 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 5789 const char *BaseInput, 5790 StringRef OrigBoundArch, bool AtTopLevel, 5791 bool MultipleArchs, 5792 StringRef OffloadingPrefix) const { 5793 std::string BoundArch = OrigBoundArch.str(); 5794 if (is_style_windows(llvm::sys::path::Style::native)) { 5795 // BoundArch may contains ':', which is invalid in file names on Windows, 5796 // therefore replace it with '%'. 5797 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@'); 5798 } 5799 5800 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 5801 // Output to a user requested destination? 5802 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 5803 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 5804 return C.addResultFile(FinalOutput->getValue(), &JA); 5805 } 5806 5807 // For /P, preprocess to file named after BaseInput. 5808 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 5809 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 5810 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5811 StringRef NameArg; 5812 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 5813 NameArg = A->getValue(); 5814 return C.addResultFile( 5815 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 5816 &JA); 5817 } 5818 5819 // Default to writing to stdout? 5820 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { 5821 return "-"; 5822 } 5823 5824 if (JA.getType() == types::TY_ModuleFile && 5825 C.getArgs().getLastArg(options::OPT_module_file_info)) { 5826 return "-"; 5827 } 5828 5829 if (JA.getType() == types::TY_PP_Asm && 5830 C.getArgs().hasArg(options::OPT_dxc_Fc)) { 5831 StringRef FcValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fc); 5832 // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably 5833 // handle this as part of the SLASH_Fa handling below. 5834 return C.addResultFile(C.getArgs().MakeArgString(FcValue.str()), &JA); 5835 } 5836 5837 if (JA.getType() == types::TY_Object && 5838 C.getArgs().hasArg(options::OPT_dxc_Fo)) { 5839 StringRef FoValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fo); 5840 // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably 5841 // handle this as part of the SLASH_Fo handling below. 5842 return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA); 5843 } 5844 5845 // Is this the assembly listing for /FA? 5846 if (JA.getType() == types::TY_PP_Asm && 5847 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 5848 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 5849 // Use /Fa and the input filename to determine the asm file name. 5850 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5851 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 5852 return C.addResultFile( 5853 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 5854 &JA); 5855 } 5856 5857 // DXC defaults to standard out when generating assembly. We check this after 5858 // any DXC flags that might specify a file. 5859 if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode()) 5860 return "-"; 5861 5862 bool SpecifiedModuleOutput = 5863 C.getArgs().hasArg(options::OPT_fmodule_output) || 5864 C.getArgs().hasArg(options::OPT_fmodule_output_EQ); 5865 if (MultipleArchs && SpecifiedModuleOutput) 5866 Diag(clang::diag::err_drv_module_output_with_multiple_arch); 5867 5868 // If we're emitting a module output with the specified option 5869 // `-fmodule-output`. 5870 if (!AtTopLevel && isa<PrecompileJobAction>(JA) && 5871 JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput) 5872 return GetModuleOutputPath(C, JA, BaseInput); 5873 5874 // Output to a temporary file? 5875 if ((!AtTopLevel && !isSaveTempsEnabled() && 5876 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 5877 CCGenDiagnostics) { 5878 StringRef Name = llvm::sys::path::filename(BaseInput); 5879 std::pair<StringRef, StringRef> Split = Name.split('.'); 5880 const char *Suffix = 5881 types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode()); 5882 // The non-offloading toolchain on Darwin requires deterministic input 5883 // file name for binaries to be deterministic, therefore it needs unique 5884 // directory. 5885 llvm::Triple Triple(C.getDriver().getTargetTriple()); 5886 bool NeedUniqueDirectory = 5887 (JA.getOffloadingDeviceKind() == Action::OFK_None || 5888 JA.getOffloadingDeviceKind() == Action::OFK_Host) && 5889 Triple.isOSDarwin(); 5890 return CreateTempFile(C, Split.first, Suffix, MultipleArchs, BoundArch, 5891 NeedUniqueDirectory); 5892 } 5893 5894 SmallString<128> BasePath(BaseInput); 5895 SmallString<128> ExternalPath(""); 5896 StringRef BaseName; 5897 5898 // Dsymutil actions should use the full path. 5899 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) { 5900 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue(); 5901 // We use posix style here because the tests (specifically 5902 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable 5903 // even on Windows and if we don't then the similar test covering this 5904 // fails. 5905 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix, 5906 llvm::sys::path::filename(BasePath)); 5907 BaseName = ExternalPath; 5908 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 5909 BaseName = BasePath; 5910 else 5911 BaseName = llvm::sys::path::filename(BasePath); 5912 5913 // Determine what the derived output name should be. 5914 const char *NamedOutput; 5915 5916 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && 5917 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 5918 // The /Fo or /o flag decides the object filename. 5919 StringRef Val = 5920 C.getArgs() 5921 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 5922 ->getValue(); 5923 NamedOutput = 5924 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 5925 } else if (JA.getType() == types::TY_Image && 5926 C.getArgs().hasArg(options::OPT__SLASH_Fe, 5927 options::OPT__SLASH_o)) { 5928 // The /Fe or /o flag names the linked file. 5929 StringRef Val = 5930 C.getArgs() 5931 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 5932 ->getValue(); 5933 NamedOutput = 5934 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 5935 } else if (JA.getType() == types::TY_Image) { 5936 if (IsCLMode()) { 5937 // clang-cl uses BaseName for the executable name. 5938 NamedOutput = 5939 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 5940 } else { 5941 SmallString<128> Output(getDefaultImageName()); 5942 // HIP image for device compilation with -fno-gpu-rdc is per compilation 5943 // unit. 5944 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5945 !C.getArgs().hasFlag(options::OPT_fgpu_rdc, 5946 options::OPT_fno_gpu_rdc, false); 5947 bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(JA); 5948 if (UseOutExtension) { 5949 Output = BaseName; 5950 llvm::sys::path::replace_extension(Output, ""); 5951 } 5952 Output += OffloadingPrefix; 5953 if (MultipleArchs && !BoundArch.empty()) { 5954 Output += "-"; 5955 Output.append(BoundArch); 5956 } 5957 if (UseOutExtension) 5958 Output += ".out"; 5959 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 5960 } 5961 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 5962 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName)); 5963 } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) && 5964 C.getArgs().hasArg(options::OPT__SLASH_o)) { 5965 StringRef Val = 5966 C.getArgs() 5967 .getLastArg(options::OPT__SLASH_o) 5968 ->getValue(); 5969 NamedOutput = 5970 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 5971 } else { 5972 const char *Suffix = 5973 types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode()); 5974 assert(Suffix && "All types used for output should have a suffix."); 5975 5976 std::string::size_type End = std::string::npos; 5977 if (!types::appendSuffixForType(JA.getType())) 5978 End = BaseName.rfind('.'); 5979 SmallString<128> Suffixed(BaseName.substr(0, End)); 5980 Suffixed += OffloadingPrefix; 5981 if (MultipleArchs && !BoundArch.empty()) { 5982 Suffixed += "-"; 5983 Suffixed.append(BoundArch); 5984 } 5985 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 5986 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 5987 // optimized bitcode output. 5988 auto IsAMDRDCInCompilePhase = [](const JobAction &JA, 5989 const llvm::opt::DerivedArgList &Args) { 5990 // The relocatable compilation in HIP and OpenMP implies -emit-llvm. 5991 // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode 5992 // (generated in the compile phase.) 5993 const ToolChain *TC = JA.getOffloadingToolChain(); 5994 return isa<CompileJobAction>(JA) && 5995 ((JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5996 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 5997 false)) || 5998 (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC && 5999 TC->getTriple().isAMDGPU())); 6000 }; 6001 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC && 6002 (C.getArgs().hasArg(options::OPT_emit_llvm) || 6003 IsAMDRDCInCompilePhase(JA, C.getArgs()))) 6004 Suffixed += ".tmp"; 6005 Suffixed += '.'; 6006 Suffixed += Suffix; 6007 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 6008 } 6009 6010 // Prepend object file path if -save-temps=obj 6011 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 6012 JA.getType() != types::TY_PCH) { 6013 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 6014 SmallString<128> TempPath(FinalOutput->getValue()); 6015 llvm::sys::path::remove_filename(TempPath); 6016 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 6017 llvm::sys::path::append(TempPath, OutputFileName); 6018 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 6019 } 6020 6021 // If we're saving temps and the temp file conflicts with the input file, 6022 // then avoid overwriting input file. 6023 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 6024 bool SameFile = false; 6025 SmallString<256> Result; 6026 llvm::sys::fs::current_path(Result); 6027 llvm::sys::path::append(Result, BaseName); 6028 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 6029 // Must share the same path to conflict. 6030 if (SameFile) { 6031 StringRef Name = llvm::sys::path::filename(BaseInput); 6032 std::pair<StringRef, StringRef> Split = Name.split('.'); 6033 std::string TmpName = GetTemporaryPath( 6034 Split.first, 6035 types::getTypeTempSuffix(JA.getType(), IsCLMode() || IsDXCMode())); 6036 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 6037 } 6038 } 6039 6040 // As an annoying special case, PCH generation doesn't strip the pathname. 6041 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 6042 llvm::sys::path::remove_filename(BasePath); 6043 if (BasePath.empty()) 6044 BasePath = NamedOutput; 6045 else 6046 llvm::sys::path::append(BasePath, NamedOutput); 6047 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 6048 } 6049 6050 return C.addResultFile(NamedOutput, &JA); 6051 } 6052 6053 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { 6054 // Search for Name in a list of paths. 6055 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) 6056 -> std::optional<std::string> { 6057 // Respect a limited subset of the '-Bprefix' functionality in GCC by 6058 // attempting to use this prefix when looking for file paths. 6059 for (const auto &Dir : P) { 6060 if (Dir.empty()) 6061 continue; 6062 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 6063 llvm::sys::path::append(P, Name); 6064 if (llvm::sys::fs::exists(Twine(P))) 6065 return std::string(P); 6066 } 6067 return std::nullopt; 6068 }; 6069 6070 if (auto P = SearchPaths(PrefixDirs)) 6071 return *P; 6072 6073 SmallString<128> R(ResourceDir); 6074 llvm::sys::path::append(R, Name); 6075 if (llvm::sys::fs::exists(Twine(R))) 6076 return std::string(R.str()); 6077 6078 SmallString<128> P(TC.getCompilerRTPath()); 6079 llvm::sys::path::append(P, Name); 6080 if (llvm::sys::fs::exists(Twine(P))) 6081 return std::string(P.str()); 6082 6083 SmallString<128> D(Dir); 6084 llvm::sys::path::append(D, "..", Name); 6085 if (llvm::sys::fs::exists(Twine(D))) 6086 return std::string(D.str()); 6087 6088 if (auto P = SearchPaths(TC.getLibraryPaths())) 6089 return *P; 6090 6091 if (auto P = SearchPaths(TC.getFilePaths())) 6092 return *P; 6093 6094 return std::string(Name); 6095 } 6096 6097 void Driver::generatePrefixedToolNames( 6098 StringRef Tool, const ToolChain &TC, 6099 SmallVectorImpl<std::string> &Names) const { 6100 // FIXME: Needs a better variable than TargetTriple 6101 Names.emplace_back((TargetTriple + "-" + Tool).str()); 6102 Names.emplace_back(Tool); 6103 } 6104 6105 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { 6106 llvm::sys::path::append(Dir, Name); 6107 if (llvm::sys::fs::can_execute(Twine(Dir))) 6108 return true; 6109 llvm::sys::path::remove_filename(Dir); 6110 return false; 6111 } 6112 6113 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { 6114 SmallVector<std::string, 2> TargetSpecificExecutables; 6115 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 6116 6117 // Respect a limited subset of the '-Bprefix' functionality in GCC by 6118 // attempting to use this prefix when looking for program paths. 6119 for (const auto &PrefixDir : PrefixDirs) { 6120 if (llvm::sys::fs::is_directory(PrefixDir)) { 6121 SmallString<128> P(PrefixDir); 6122 if (ScanDirForExecutable(P, Name)) 6123 return std::string(P.str()); 6124 } else { 6125 SmallString<128> P((PrefixDir + Name).str()); 6126 if (llvm::sys::fs::can_execute(Twine(P))) 6127 return std::string(P.str()); 6128 } 6129 } 6130 6131 const ToolChain::path_list &List = TC.getProgramPaths(); 6132 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { 6133 // For each possible name of the tool look for it in 6134 // program paths first, then the path. 6135 // Higher priority names will be first, meaning that 6136 // a higher priority name in the path will be found 6137 // instead of a lower priority name in the program path. 6138 // E.g. <triple>-gcc on the path will be found instead 6139 // of gcc in the program path 6140 for (const auto &Path : List) { 6141 SmallString<128> P(Path); 6142 if (ScanDirForExecutable(P, TargetSpecificExecutable)) 6143 return std::string(P.str()); 6144 } 6145 6146 // Fall back to the path 6147 if (llvm::ErrorOr<std::string> P = 6148 llvm::sys::findProgramByName(TargetSpecificExecutable)) 6149 return *P; 6150 } 6151 6152 return std::string(Name); 6153 } 6154 6155 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { 6156 SmallString<128> Path; 6157 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 6158 if (EC) { 6159 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 6160 return ""; 6161 } 6162 6163 return std::string(Path.str()); 6164 } 6165 6166 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { 6167 SmallString<128> Path; 6168 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path); 6169 if (EC) { 6170 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 6171 return ""; 6172 } 6173 6174 return std::string(Path.str()); 6175 } 6176 6177 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 6178 SmallString<128> Output; 6179 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 6180 // FIXME: If anybody needs it, implement this obscure rule: 6181 // "If you specify a directory without a file name, the default file name 6182 // is VCx0.pch., where x is the major version of Visual C++ in use." 6183 Output = FpArg->getValue(); 6184 6185 // "If you do not specify an extension as part of the path name, an 6186 // extension of .pch is assumed. " 6187 if (!llvm::sys::path::has_extension(Output)) 6188 Output += ".pch"; 6189 } else { 6190 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) 6191 Output = YcArg->getValue(); 6192 if (Output.empty()) 6193 Output = BaseName; 6194 llvm::sys::path::replace_extension(Output, ".pch"); 6195 } 6196 return std::string(Output.str()); 6197 } 6198 6199 const ToolChain &Driver::getToolChain(const ArgList &Args, 6200 const llvm::Triple &Target) const { 6201 6202 auto &TC = ToolChains[Target.str()]; 6203 if (!TC) { 6204 switch (Target.getOS()) { 6205 case llvm::Triple::AIX: 6206 TC = std::make_unique<toolchains::AIX>(*this, Target, Args); 6207 break; 6208 case llvm::Triple::Haiku: 6209 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args); 6210 break; 6211 case llvm::Triple::Darwin: 6212 case llvm::Triple::MacOSX: 6213 case llvm::Triple::IOS: 6214 case llvm::Triple::TvOS: 6215 case llvm::Triple::WatchOS: 6216 case llvm::Triple::DriverKit: 6217 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args); 6218 break; 6219 case llvm::Triple::DragonFly: 6220 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args); 6221 break; 6222 case llvm::Triple::OpenBSD: 6223 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args); 6224 break; 6225 case llvm::Triple::NetBSD: 6226 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args); 6227 break; 6228 case llvm::Triple::FreeBSD: 6229 if (Target.isPPC()) 6230 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target, 6231 Args); 6232 else 6233 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args); 6234 break; 6235 case llvm::Triple::Linux: 6236 case llvm::Triple::ELFIAMCU: 6237 if (Target.getArch() == llvm::Triple::hexagon) 6238 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 6239 Args); 6240 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 6241 !Target.hasEnvironment()) 6242 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target, 6243 Args); 6244 else if (Target.isPPC()) 6245 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target, 6246 Args); 6247 else if (Target.getArch() == llvm::Triple::ve) 6248 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 6249 else if (Target.isOHOSFamily()) 6250 TC = std::make_unique<toolchains::OHOS>(*this, Target, Args); 6251 else 6252 TC = std::make_unique<toolchains::Linux>(*this, Target, Args); 6253 break; 6254 case llvm::Triple::NaCl: 6255 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args); 6256 break; 6257 case llvm::Triple::Fuchsia: 6258 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args); 6259 break; 6260 case llvm::Triple::Solaris: 6261 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args); 6262 break; 6263 case llvm::Triple::CUDA: 6264 TC = std::make_unique<toolchains::NVPTXToolChain>(*this, Target, Args); 6265 break; 6266 case llvm::Triple::AMDHSA: 6267 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args); 6268 break; 6269 case llvm::Triple::AMDPAL: 6270 case llvm::Triple::Mesa3D: 6271 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args); 6272 break; 6273 case llvm::Triple::Win32: 6274 switch (Target.getEnvironment()) { 6275 default: 6276 if (Target.isOSBinFormatELF()) 6277 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 6278 else if (Target.isOSBinFormatMachO()) 6279 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 6280 else 6281 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 6282 break; 6283 case llvm::Triple::GNU: 6284 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args); 6285 break; 6286 case llvm::Triple::Itanium: 6287 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target, 6288 Args); 6289 break; 6290 case llvm::Triple::MSVC: 6291 case llvm::Triple::UnknownEnvironment: 6292 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ) 6293 .starts_with_insensitive("bfd")) 6294 TC = std::make_unique<toolchains::CrossWindowsToolChain>( 6295 *this, Target, Args); 6296 else 6297 TC = 6298 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args); 6299 break; 6300 } 6301 break; 6302 case llvm::Triple::PS4: 6303 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args); 6304 break; 6305 case llvm::Triple::PS5: 6306 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args); 6307 break; 6308 case llvm::Triple::Hurd: 6309 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args); 6310 break; 6311 case llvm::Triple::LiteOS: 6312 TC = std::make_unique<toolchains::OHOS>(*this, Target, Args); 6313 break; 6314 case llvm::Triple::ZOS: 6315 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args); 6316 break; 6317 case llvm::Triple::ShaderModel: 6318 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args); 6319 break; 6320 default: 6321 // Of these targets, Hexagon is the only one that might have 6322 // an OS of Linux, in which case it got handled above already. 6323 switch (Target.getArch()) { 6324 case llvm::Triple::tce: 6325 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args); 6326 break; 6327 case llvm::Triple::tcele: 6328 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args); 6329 break; 6330 case llvm::Triple::hexagon: 6331 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 6332 Args); 6333 break; 6334 case llvm::Triple::lanai: 6335 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args); 6336 break; 6337 case llvm::Triple::xcore: 6338 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args); 6339 break; 6340 case llvm::Triple::wasm32: 6341 case llvm::Triple::wasm64: 6342 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args); 6343 break; 6344 case llvm::Triple::avr: 6345 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args); 6346 break; 6347 case llvm::Triple::msp430: 6348 TC = 6349 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args); 6350 break; 6351 case llvm::Triple::riscv32: 6352 case llvm::Triple::riscv64: 6353 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args)) 6354 TC = 6355 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); 6356 else 6357 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 6358 break; 6359 case llvm::Triple::ve: 6360 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 6361 break; 6362 case llvm::Triple::spirv32: 6363 case llvm::Triple::spirv64: 6364 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args); 6365 break; 6366 case llvm::Triple::csky: 6367 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args); 6368 break; 6369 default: 6370 if (toolchains::BareMetal::handlesTarget(Target)) 6371 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 6372 else if (Target.isOSBinFormatELF()) 6373 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 6374 else if (Target.isOSBinFormatMachO()) 6375 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 6376 else 6377 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 6378 } 6379 } 6380 } 6381 6382 return *TC; 6383 } 6384 6385 const ToolChain &Driver::getOffloadingDeviceToolChain( 6386 const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC, 6387 const Action::OffloadKind &TargetDeviceOffloadKind) const { 6388 // Use device / host triples as the key into the ToolChains map because the 6389 // device ToolChain we create depends on both. 6390 auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()]; 6391 if (!TC) { 6392 // Categorized by offload kind > arch rather than OS > arch like 6393 // the normal getToolChain call, as it seems a reasonable way to categorize 6394 // things. 6395 switch (TargetDeviceOffloadKind) { 6396 case Action::OFK_HIP: { 6397 if (Target.getArch() == llvm::Triple::amdgcn && 6398 Target.getVendor() == llvm::Triple::AMD && 6399 Target.getOS() == llvm::Triple::AMDHSA) 6400 TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target, 6401 HostTC, Args); 6402 else if (Target.getArch() == llvm::Triple::spirv64 && 6403 Target.getVendor() == llvm::Triple::UnknownVendor && 6404 Target.getOS() == llvm::Triple::UnknownOS) 6405 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target, 6406 HostTC, Args); 6407 break; 6408 } 6409 default: 6410 break; 6411 } 6412 } 6413 6414 return *TC; 6415 } 6416 6417 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 6418 // Say "no" if there is not exactly one input of a type clang understands. 6419 if (JA.size() != 1 || 6420 !types::isAcceptedByClang((*JA.input_begin())->getType())) 6421 return false; 6422 6423 // And say "no" if this is not a kind of action clang understands. 6424 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 6425 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) && 6426 !isa<ExtractAPIJobAction>(JA)) 6427 return false; 6428 6429 return true; 6430 } 6431 6432 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { 6433 // Say "no" if there is not exactly one input of a type flang understands. 6434 if (JA.size() != 1 || 6435 !types::isAcceptedByFlang((*JA.input_begin())->getType())) 6436 return false; 6437 6438 // And say "no" if this is not a kind of action flang understands. 6439 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && 6440 !isa<BackendJobAction>(JA)) 6441 return false; 6442 6443 return true; 6444 } 6445 6446 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { 6447 // Only emit static library if the flag is set explicitly. 6448 if (Args.hasArg(options::OPT_emit_static_lib)) 6449 return true; 6450 return false; 6451 } 6452 6453 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 6454 /// grouped values as integers. Numbers which are not provided are set to 0. 6455 /// 6456 /// \return True if the entire string was parsed (9.2), or all groups were 6457 /// parsed (10.3.5extrastuff). 6458 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 6459 unsigned &Micro, bool &HadExtra) { 6460 HadExtra = false; 6461 6462 Major = Minor = Micro = 0; 6463 if (Str.empty()) 6464 return false; 6465 6466 if (Str.consumeInteger(10, Major)) 6467 return false; 6468 if (Str.empty()) 6469 return true; 6470 if (Str[0] != '.') 6471 return false; 6472 6473 Str = Str.drop_front(1); 6474 6475 if (Str.consumeInteger(10, Minor)) 6476 return false; 6477 if (Str.empty()) 6478 return true; 6479 if (Str[0] != '.') 6480 return false; 6481 Str = Str.drop_front(1); 6482 6483 if (Str.consumeInteger(10, Micro)) 6484 return false; 6485 if (!Str.empty()) 6486 HadExtra = true; 6487 return true; 6488 } 6489 6490 /// Parse digits from a string \p Str and fulfill \p Digits with 6491 /// the parsed numbers. This method assumes that the max number of 6492 /// digits to look for is equal to Digits.size(). 6493 /// 6494 /// \return True if the entire string was parsed and there are 6495 /// no extra characters remaining at the end. 6496 bool Driver::GetReleaseVersion(StringRef Str, 6497 MutableArrayRef<unsigned> Digits) { 6498 if (Str.empty()) 6499 return false; 6500 6501 unsigned CurDigit = 0; 6502 while (CurDigit < Digits.size()) { 6503 unsigned Digit; 6504 if (Str.consumeInteger(10, Digit)) 6505 return false; 6506 Digits[CurDigit] = Digit; 6507 if (Str.empty()) 6508 return true; 6509 if (Str[0] != '.') 6510 return false; 6511 Str = Str.drop_front(1); 6512 CurDigit++; 6513 } 6514 6515 // More digits than requested, bail out... 6516 return false; 6517 } 6518 6519 llvm::opt::Visibility 6520 Driver::getOptionVisibilityMask(bool UseDriverMode) const { 6521 if (!UseDriverMode) 6522 return llvm::opt::Visibility(options::ClangOption); 6523 if (IsCLMode()) 6524 return llvm::opt::Visibility(options::CLOption); 6525 if (IsDXCMode()) 6526 return llvm::opt::Visibility(options::DXCOption); 6527 if (IsFlangMode()) { 6528 return llvm::opt::Visibility(options::FlangOption); 6529 } 6530 return llvm::opt::Visibility(options::ClangOption); 6531 } 6532 6533 const char *Driver::getExecutableForDriverMode(DriverMode Mode) { 6534 switch (Mode) { 6535 case GCCMode: 6536 return "clang"; 6537 case GXXMode: 6538 return "clang++"; 6539 case CPPMode: 6540 return "clang-cpp"; 6541 case CLMode: 6542 return "clang-cl"; 6543 case FlangMode: 6544 return "flang"; 6545 case DXCMode: 6546 return "clang-dxc"; 6547 } 6548 6549 llvm_unreachable("Unhandled Mode"); 6550 } 6551 6552 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 6553 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 6554 } 6555 6556 bool clang::driver::willEmitRemarks(const ArgList &Args) { 6557 // -fsave-optimization-record enables it. 6558 if (Args.hasFlag(options::OPT_fsave_optimization_record, 6559 options::OPT_fno_save_optimization_record, false)) 6560 return true; 6561 6562 // -fsave-optimization-record=<format> enables it as well. 6563 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ, 6564 options::OPT_fno_save_optimization_record, false)) 6565 return true; 6566 6567 // -foptimization-record-file alone enables it too. 6568 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ, 6569 options::OPT_fno_save_optimization_record, false)) 6570 return true; 6571 6572 // -foptimization-record-passes alone enables it too. 6573 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ, 6574 options::OPT_fno_save_optimization_record, false)) 6575 return true; 6576 return false; 6577 } 6578 6579 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, 6580 ArrayRef<const char *> Args) { 6581 static StringRef OptName = 6582 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName(); 6583 llvm::StringRef Opt; 6584 for (StringRef Arg : Args) { 6585 if (!Arg.starts_with(OptName)) 6586 continue; 6587 Opt = Arg; 6588 } 6589 if (Opt.empty()) 6590 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; 6591 return Opt.consume_front(OptName) ? Opt : ""; 6592 } 6593 6594 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); } 6595 6596 llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args, 6597 bool ClangCLMode, 6598 llvm::BumpPtrAllocator &Alloc, 6599 llvm::vfs::FileSystem *FS) { 6600 // Parse response files using the GNU syntax, unless we're in CL mode. There 6601 // are two ways to put clang in CL compatibility mode: ProgName is either 6602 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal 6603 // command line parsing can't happen until after response file parsing, so we 6604 // have to manually search for a --driver-mode=cl argument the hard way. 6605 // Finally, our -cc1 tools don't care which tokenization mode we use because 6606 // response files written by clang will tokenize the same way in either mode. 6607 enum { Default, POSIX, Windows } RSPQuoting = Default; 6608 for (const char *F : Args) { 6609 if (strcmp(F, "--rsp-quoting=posix") == 0) 6610 RSPQuoting = POSIX; 6611 else if (strcmp(F, "--rsp-quoting=windows") == 0) 6612 RSPQuoting = Windows; 6613 } 6614 6615 // Determines whether we want nullptr markers in Args to indicate response 6616 // files end-of-lines. We only use this for the /LINK driver argument with 6617 // clang-cl.exe on Windows. 6618 bool MarkEOLs = ClangCLMode; 6619 6620 llvm::cl::TokenizerCallback Tokenizer; 6621 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode)) 6622 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine; 6623 else 6624 Tokenizer = &llvm::cl::TokenizeGNUCommandLine; 6625 6626 if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with("-cc1")) 6627 MarkEOLs = false; 6628 6629 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer); 6630 ECtx.setMarkEOLs(MarkEOLs); 6631 if (FS) 6632 ECtx.setVFS(FS); 6633 6634 if (llvm::Error Err = ECtx.expandResponseFiles(Args)) 6635 return Err; 6636 6637 // If -cc1 came from a response file, remove the EOL sentinels. 6638 auto FirstArg = llvm::find_if(llvm::drop_begin(Args), 6639 [](const char *A) { return A != nullptr; }); 6640 if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with("-cc1")) { 6641 // If -cc1 came from a response file, remove the EOL sentinels. 6642 if (MarkEOLs) { 6643 auto newEnd = std::remove(Args.begin(), Args.end(), nullptr); 6644 Args.resize(newEnd - Args.begin()); 6645 } 6646 } 6647 6648 return llvm::Error::success(); 6649 } 6650