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