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 if (Ty != OldTy) 2441 Diag(clang::diag::warn_drv_treating_input_as_cxx) 2442 << getTypeName(OldTy) << getTypeName(Ty); 2443 } 2444 2445 // If running with -fthinlto-index=, extensions that normally identify 2446 // native object files actually identify LLVM bitcode files. 2447 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) && 2448 Ty == types::TY_Object) 2449 Ty = types::TY_LLVM_BC; 2450 } 2451 2452 // -ObjC and -ObjC++ override the default language, but only for "source 2453 // files". We just treat everything that isn't a linker input as a 2454 // source file. 2455 // 2456 // FIXME: Clean this up if we move the phase sequence into the type. 2457 if (Ty != types::TY_Object) { 2458 if (Args.hasArg(options::OPT_ObjC)) 2459 Ty = types::TY_ObjC; 2460 else if (Args.hasArg(options::OPT_ObjCXX)) 2461 Ty = types::TY_ObjCXX; 2462 } 2463 2464 // Disambiguate headers that are meant to be header units from those 2465 // intended to be PCH. 2466 if (Ty == types::TY_CXXHeader && hasHeaderMode()) 2467 Ty = CXXHeaderUnitType(CXX20HeaderType); 2468 } else { 2469 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 2470 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 2471 // If emulating cl.exe, make sure that /TC and /TP don't affect input 2472 // object files. 2473 const char *Ext = strrchr(Value, '.'); 2474 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 2475 Ty = types::TY_Object; 2476 } 2477 if (Ty == types::TY_INVALID) { 2478 Ty = InputType; 2479 InputTypeArg->claim(); 2480 } 2481 } 2482 2483 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true)) 2484 Inputs.push_back(std::make_pair(Ty, A)); 2485 2486 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 2487 StringRef Value = A->getValue(); 2488 if (DiagnoseInputExistence(Args, Value, types::TY_C, 2489 /*TypoCorrect=*/false)) { 2490 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2491 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 2492 } 2493 A->claim(); 2494 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 2495 StringRef Value = A->getValue(); 2496 if (DiagnoseInputExistence(Args, Value, types::TY_CXX, 2497 /*TypoCorrect=*/false)) { 2498 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 2499 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 2500 } 2501 A->claim(); 2502 } else if (A->getOption().hasFlag(options::LinkerInput)) { 2503 // Just treat as object type, we could make a special type for this if 2504 // necessary. 2505 Inputs.push_back(std::make_pair(types::TY_Object, A)); 2506 2507 } else if (A->getOption().matches(options::OPT_x)) { 2508 InputTypeArg = A; 2509 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 2510 A->claim(); 2511 2512 // Follow gcc behavior and treat as linker input for invalid -x 2513 // options. Its not clear why we shouldn't just revert to unknown; but 2514 // this isn't very important, we might as well be bug compatible. 2515 if (!InputType) { 2516 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 2517 InputType = types::TY_Object; 2518 } 2519 2520 // If the user has put -fmodule-header{,=} then we treat C++ headers as 2521 // header unit inputs. So we 'promote' -xc++-header appropriately. 2522 if (InputType == types::TY_CXXHeader && hasHeaderMode()) 2523 InputType = CXXHeaderUnitType(CXX20HeaderType); 2524 } else if (A->getOption().getID() == options::OPT_U) { 2525 assert(A->getNumValues() == 1 && "The /U option has one value."); 2526 StringRef Val = A->getValue(0); 2527 if (Val.find_first_of("/\\") != StringRef::npos) { 2528 // Warn about e.g. "/Users/me/myfile.c". 2529 Diag(diag::warn_slash_u_filename) << Val; 2530 Diag(diag::note_use_dashdash); 2531 } 2532 } 2533 } 2534 if (CCCIsCPP() && Inputs.empty()) { 2535 // If called as standalone preprocessor, stdin is processed 2536 // if no other input is present. 2537 Arg *A = MakeInputArg(Args, Opts, "-"); 2538 Inputs.push_back(std::make_pair(types::TY_C, A)); 2539 } 2540 } 2541 2542 namespace { 2543 /// Provides a convenient interface for different programming models to generate 2544 /// the required device actions. 2545 class OffloadingActionBuilder final { 2546 /// Flag used to trace errors in the builder. 2547 bool IsValid = false; 2548 2549 /// The compilation that is using this builder. 2550 Compilation &C; 2551 2552 /// Map between an input argument and the offload kinds used to process it. 2553 std::map<const Arg *, unsigned> InputArgToOffloadKindMap; 2554 2555 /// Map between a host action and its originating input argument. 2556 std::map<Action *, const Arg *> HostActionToInputArgMap; 2557 2558 /// Builder interface. It doesn't build anything or keep any state. 2559 class DeviceActionBuilder { 2560 public: 2561 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy; 2562 2563 enum ActionBuilderReturnCode { 2564 // The builder acted successfully on the current action. 2565 ABRT_Success, 2566 // The builder didn't have to act on the current action. 2567 ABRT_Inactive, 2568 // The builder was successful and requested the host action to not be 2569 // generated. 2570 ABRT_Ignore_Host, 2571 }; 2572 2573 protected: 2574 /// Compilation associated with this builder. 2575 Compilation &C; 2576 2577 /// Tool chains associated with this builder. The same programming 2578 /// model may have associated one or more tool chains. 2579 SmallVector<const ToolChain *, 2> ToolChains; 2580 2581 /// The derived arguments associated with this builder. 2582 DerivedArgList &Args; 2583 2584 /// The inputs associated with this builder. 2585 const Driver::InputList &Inputs; 2586 2587 /// The associated offload kind. 2588 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None; 2589 2590 public: 2591 DeviceActionBuilder(Compilation &C, DerivedArgList &Args, 2592 const Driver::InputList &Inputs, 2593 Action::OffloadKind AssociatedOffloadKind) 2594 : C(C), Args(Args), Inputs(Inputs), 2595 AssociatedOffloadKind(AssociatedOffloadKind) {} 2596 virtual ~DeviceActionBuilder() {} 2597 2598 /// Fill up the array \a DA with all the device dependences that should be 2599 /// added to the provided host action \a HostAction. By default it is 2600 /// inactive. 2601 virtual ActionBuilderReturnCode 2602 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2603 phases::ID CurPhase, phases::ID FinalPhase, 2604 PhasesTy &Phases) { 2605 return ABRT_Inactive; 2606 } 2607 2608 /// Update the state to include the provided host action \a HostAction as a 2609 /// dependency of the current device action. By default it is inactive. 2610 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) { 2611 return ABRT_Inactive; 2612 } 2613 2614 /// Append top level actions generated by the builder. 2615 virtual void appendTopLevelActions(ActionList &AL) {} 2616 2617 /// Append linker device actions generated by the builder. 2618 virtual void appendLinkDeviceActions(ActionList &AL) {} 2619 2620 /// Append linker host action generated by the builder. 2621 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; } 2622 2623 /// Append linker actions generated by the builder. 2624 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {} 2625 2626 /// Initialize the builder. Return true if any initialization errors are 2627 /// found. 2628 virtual bool initialize() { return false; } 2629 2630 /// Return true if the builder can use bundling/unbundling. 2631 virtual bool canUseBundlerUnbundler() const { return false; } 2632 2633 /// Return true if this builder is valid. We have a valid builder if we have 2634 /// associated device tool chains. 2635 bool isValid() { return !ToolChains.empty(); } 2636 2637 /// Return the associated offload kind. 2638 Action::OffloadKind getAssociatedOffloadKind() { 2639 return AssociatedOffloadKind; 2640 } 2641 }; 2642 2643 /// Base class for CUDA/HIP action builder. It injects device code in 2644 /// the host backend action. 2645 class CudaActionBuilderBase : public DeviceActionBuilder { 2646 protected: 2647 /// Flags to signal if the user requested host-only or device-only 2648 /// compilation. 2649 bool CompileHostOnly = false; 2650 bool CompileDeviceOnly = false; 2651 bool EmitLLVM = false; 2652 bool EmitAsm = false; 2653 2654 /// ID to identify each device compilation. For CUDA it is simply the 2655 /// GPU arch string. For HIP it is either the GPU arch string or GPU 2656 /// arch string plus feature strings delimited by a plus sign, e.g. 2657 /// gfx906+xnack. 2658 struct TargetID { 2659 /// Target ID string which is persistent throughout the compilation. 2660 const char *ID; 2661 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); } 2662 TargetID(const char *ID) : ID(ID) {} 2663 operator const char *() { return ID; } 2664 operator StringRef() { return StringRef(ID); } 2665 }; 2666 /// List of GPU architectures to use in this compilation. 2667 SmallVector<TargetID, 4> GpuArchList; 2668 2669 /// The CUDA actions for the current input. 2670 ActionList CudaDeviceActions; 2671 2672 /// The CUDA fat binary if it was generated for the current input. 2673 Action *CudaFatBinary = nullptr; 2674 2675 /// Flag that is set to true if this builder acted on the current input. 2676 bool IsActive = false; 2677 2678 /// Flag for -fgpu-rdc. 2679 bool Relocatable = false; 2680 2681 /// Default GPU architecture if there's no one specified. 2682 CudaArch DefaultCudaArch = CudaArch::UNKNOWN; 2683 2684 /// Method to generate compilation unit ID specified by option 2685 /// '-fuse-cuid='. 2686 enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid }; 2687 UseCUIDKind UseCUID = CUID_Hash; 2688 2689 /// Compilation unit ID specified by option '-cuid='. 2690 StringRef FixedCUID; 2691 2692 public: 2693 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args, 2694 const Driver::InputList &Inputs, 2695 Action::OffloadKind OFKind) 2696 : DeviceActionBuilder(C, Args, Inputs, OFKind) {} 2697 2698 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override { 2699 // While generating code for CUDA, we only depend on the host input action 2700 // to trigger the creation of all the CUDA device actions. 2701 2702 // If we are dealing with an input action, replicate it for each GPU 2703 // architecture. If we are in host-only mode we return 'success' so that 2704 // the host uses the CUDA offload kind. 2705 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 2706 assert(!GpuArchList.empty() && 2707 "We should have at least one GPU architecture."); 2708 2709 // If the host input is not CUDA or HIP, we don't need to bother about 2710 // this input. 2711 if (!(IA->getType() == types::TY_CUDA || 2712 IA->getType() == types::TY_HIP || 2713 IA->getType() == types::TY_PP_HIP)) { 2714 // The builder will ignore this input. 2715 IsActive = false; 2716 return ABRT_Inactive; 2717 } 2718 2719 // Set the flag to true, so that the builder acts on the current input. 2720 IsActive = true; 2721 2722 if (CompileHostOnly) 2723 return ABRT_Success; 2724 2725 // Replicate inputs for each GPU architecture. 2726 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE 2727 : types::TY_CUDA_DEVICE; 2728 std::string CUID = FixedCUID.str(); 2729 if (CUID.empty()) { 2730 if (UseCUID == CUID_Random) 2731 CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(), 2732 /*LowerCase=*/true); 2733 else if (UseCUID == CUID_Hash) { 2734 llvm::MD5 Hasher; 2735 llvm::MD5::MD5Result Hash; 2736 SmallString<256> RealPath; 2737 llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath, 2738 /*expand_tilde=*/true); 2739 Hasher.update(RealPath); 2740 for (auto *A : Args) { 2741 if (A->getOption().matches(options::OPT_INPUT)) 2742 continue; 2743 Hasher.update(A->getAsString(Args)); 2744 } 2745 Hasher.final(Hash); 2746 CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true); 2747 } 2748 } 2749 IA->setId(CUID); 2750 2751 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 2752 CudaDeviceActions.push_back( 2753 C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId())); 2754 } 2755 2756 return ABRT_Success; 2757 } 2758 2759 // If this is an unbundling action use it as is for each CUDA toolchain. 2760 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 2761 2762 // If -fgpu-rdc is disabled, should not unbundle since there is no 2763 // device code to link. 2764 if (UA->getType() == types::TY_Object && !Relocatable) 2765 return ABRT_Inactive; 2766 2767 CudaDeviceActions.clear(); 2768 auto *IA = cast<InputAction>(UA->getInputs().back()); 2769 std::string FileName = IA->getInputArg().getAsString(Args); 2770 // Check if the type of the file is the same as the action. Do not 2771 // unbundle it if it is not. Do not unbundle .so files, for example, 2772 // which are not object files. 2773 if (IA->getType() == types::TY_Object && 2774 (!llvm::sys::path::has_extension(FileName) || 2775 types::lookupTypeForExtension( 2776 llvm::sys::path::extension(FileName).drop_front()) != 2777 types::TY_Object)) 2778 return ABRT_Inactive; 2779 2780 for (auto Arch : GpuArchList) { 2781 CudaDeviceActions.push_back(UA); 2782 UA->registerDependentActionInfo(ToolChains[0], Arch, 2783 AssociatedOffloadKind); 2784 } 2785 IsActive = true; 2786 return ABRT_Success; 2787 } 2788 2789 return IsActive ? ABRT_Success : ABRT_Inactive; 2790 } 2791 2792 void appendTopLevelActions(ActionList &AL) override { 2793 // Utility to append actions to the top level list. 2794 auto AddTopLevel = [&](Action *A, TargetID TargetID) { 2795 OffloadAction::DeviceDependences Dep; 2796 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind); 2797 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 2798 }; 2799 2800 // If we have a fat binary, add it to the list. 2801 if (CudaFatBinary) { 2802 AddTopLevel(CudaFatBinary, CudaArch::UNUSED); 2803 CudaDeviceActions.clear(); 2804 CudaFatBinary = nullptr; 2805 return; 2806 } 2807 2808 if (CudaDeviceActions.empty()) 2809 return; 2810 2811 // If we have CUDA actions at this point, that's because we have a have 2812 // partial compilation, so we should have an action for each GPU 2813 // architecture. 2814 assert(CudaDeviceActions.size() == GpuArchList.size() && 2815 "Expecting one action per GPU architecture."); 2816 assert(ToolChains.size() == 1 && 2817 "Expecting to have a single CUDA toolchain."); 2818 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 2819 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]); 2820 2821 CudaDeviceActions.clear(); 2822 } 2823 2824 /// Get canonicalized offload arch option. \returns empty StringRef if the 2825 /// option is invalid. 2826 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0; 2827 2828 virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> 2829 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0; 2830 2831 bool initialize() override { 2832 assert(AssociatedOffloadKind == Action::OFK_Cuda || 2833 AssociatedOffloadKind == Action::OFK_HIP); 2834 2835 // We don't need to support CUDA. 2836 if (AssociatedOffloadKind == Action::OFK_Cuda && 2837 !C.hasOffloadToolChain<Action::OFK_Cuda>()) 2838 return false; 2839 2840 // We don't need to support HIP. 2841 if (AssociatedOffloadKind == Action::OFK_HIP && 2842 !C.hasOffloadToolChain<Action::OFK_HIP>()) 2843 return false; 2844 2845 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc, 2846 options::OPT_fno_gpu_rdc, /*Default=*/false); 2847 2848 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>(); 2849 assert(HostTC && "No toolchain for host compilation."); 2850 if (HostTC->getTriple().isNVPTX() || 2851 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) { 2852 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw 2853 // an error and abort pipeline construction early so we don't trip 2854 // asserts that assume device-side compilation. 2855 C.getDriver().Diag(diag::err_drv_cuda_host_arch) 2856 << HostTC->getTriple().getArchName(); 2857 return true; 2858 } 2859 2860 ToolChains.push_back( 2861 AssociatedOffloadKind == Action::OFK_Cuda 2862 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 2863 : C.getSingleOffloadToolChain<Action::OFK_HIP>()); 2864 2865 Arg *PartialCompilationArg = Args.getLastArg( 2866 options::OPT_cuda_host_only, options::OPT_cuda_device_only, 2867 options::OPT_cuda_compile_host_device); 2868 CompileHostOnly = PartialCompilationArg && 2869 PartialCompilationArg->getOption().matches( 2870 options::OPT_cuda_host_only); 2871 CompileDeviceOnly = PartialCompilationArg && 2872 PartialCompilationArg->getOption().matches( 2873 options::OPT_cuda_device_only); 2874 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm); 2875 EmitAsm = Args.getLastArg(options::OPT_S); 2876 FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ); 2877 if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) { 2878 StringRef UseCUIDStr = A->getValue(); 2879 UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr) 2880 .Case("hash", CUID_Hash) 2881 .Case("random", CUID_Random) 2882 .Case("none", CUID_None) 2883 .Default(CUID_Invalid); 2884 if (UseCUID == CUID_Invalid) { 2885 C.getDriver().Diag(diag::err_drv_invalid_value) 2886 << A->getAsString(Args) << UseCUIDStr; 2887 C.setContainsError(); 2888 return true; 2889 } 2890 } 2891 2892 // --offload and --offload-arch options are mutually exclusive. 2893 if (Args.hasArgNoClaim(options::OPT_offload_EQ) && 2894 Args.hasArgNoClaim(options::OPT_offload_arch_EQ, 2895 options::OPT_no_offload_arch_EQ)) { 2896 C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch" 2897 << "--offload"; 2898 } 2899 2900 // Collect all cuda_gpu_arch parameters, removing duplicates. 2901 std::set<StringRef> GpuArchs; 2902 bool Error = false; 2903 for (Arg *A : Args) { 2904 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) || 2905 A->getOption().matches(options::OPT_no_offload_arch_EQ))) 2906 continue; 2907 A->claim(); 2908 2909 StringRef ArchStr = A->getValue(); 2910 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) && 2911 ArchStr == "all") { 2912 GpuArchs.clear(); 2913 continue; 2914 } 2915 ArchStr = getCanonicalOffloadArch(ArchStr); 2916 if (ArchStr.empty()) { 2917 Error = true; 2918 } else if (A->getOption().matches(options::OPT_offload_arch_EQ)) 2919 GpuArchs.insert(ArchStr); 2920 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ)) 2921 GpuArchs.erase(ArchStr); 2922 else 2923 llvm_unreachable("Unexpected option."); 2924 } 2925 2926 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs); 2927 if (ConflictingArchs) { 2928 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo) 2929 << ConflictingArchs.getValue().first 2930 << ConflictingArchs.getValue().second; 2931 C.setContainsError(); 2932 return true; 2933 } 2934 2935 // Collect list of GPUs remaining in the set. 2936 for (auto Arch : GpuArchs) 2937 GpuArchList.push_back(Arch.data()); 2938 2939 // Default to sm_20 which is the lowest common denominator for 2940 // supported GPUs. sm_20 code should work correctly, if 2941 // suboptimally, on all newer GPUs. 2942 if (GpuArchList.empty()) { 2943 if (ToolChains.front()->getTriple().isSPIRV()) 2944 GpuArchList.push_back(CudaArch::Generic); 2945 else 2946 GpuArchList.push_back(DefaultCudaArch); 2947 } 2948 2949 return Error; 2950 } 2951 }; 2952 2953 /// \brief CUDA action builder. It injects device code in the host backend 2954 /// action. 2955 class CudaActionBuilder final : public CudaActionBuilderBase { 2956 public: 2957 CudaActionBuilder(Compilation &C, DerivedArgList &Args, 2958 const Driver::InputList &Inputs) 2959 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) { 2960 DefaultCudaArch = CudaArch::SM_35; 2961 } 2962 2963 StringRef getCanonicalOffloadArch(StringRef ArchStr) override { 2964 CudaArch Arch = StringToCudaArch(ArchStr); 2965 if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) { 2966 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr; 2967 return StringRef(); 2968 } 2969 return CudaArchToString(Arch); 2970 } 2971 2972 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> 2973 getConflictOffloadArchCombination( 2974 const std::set<StringRef> &GpuArchs) override { 2975 return llvm::None; 2976 } 2977 2978 ActionBuilderReturnCode 2979 getDeviceDependences(OffloadAction::DeviceDependences &DA, 2980 phases::ID CurPhase, phases::ID FinalPhase, 2981 PhasesTy &Phases) override { 2982 if (!IsActive) 2983 return ABRT_Inactive; 2984 2985 // If we don't have more CUDA actions, we don't have any dependences to 2986 // create for the host. 2987 if (CudaDeviceActions.empty()) 2988 return ABRT_Success; 2989 2990 assert(CudaDeviceActions.size() == GpuArchList.size() && 2991 "Expecting one action per GPU architecture."); 2992 assert(!CompileHostOnly && 2993 "Not expecting CUDA actions in host-only compilation."); 2994 2995 // If we are generating code for the device or we are in a backend phase, 2996 // we attempt to generate the fat binary. We compile each arch to ptx and 2997 // assemble to cubin, then feed the cubin *and* the ptx into a device 2998 // "link" action, which uses fatbinary to combine these cubins into one 2999 // fatbin. The fatbin is then an input to the host action if not in 3000 // device-only mode. 3001 if (CompileDeviceOnly || CurPhase == phases::Backend) { 3002 ActionList DeviceActions; 3003 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3004 // Produce the device action from the current phase up to the assemble 3005 // phase. 3006 for (auto Ph : Phases) { 3007 // Skip the phases that were already dealt with. 3008 if (Ph < CurPhase) 3009 continue; 3010 // We have to be consistent with the host final phase. 3011 if (Ph > FinalPhase) 3012 break; 3013 3014 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction( 3015 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda); 3016 3017 if (Ph == phases::Assemble) 3018 break; 3019 } 3020 3021 // If we didn't reach the assemble phase, we can't generate the fat 3022 // binary. We don't need to generate the fat binary if we are not in 3023 // device-only mode. 3024 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) || 3025 CompileDeviceOnly) 3026 continue; 3027 3028 Action *AssembleAction = CudaDeviceActions[I]; 3029 assert(AssembleAction->getType() == types::TY_Object); 3030 assert(AssembleAction->getInputs().size() == 1); 3031 3032 Action *BackendAction = AssembleAction->getInputs()[0]; 3033 assert(BackendAction->getType() == types::TY_PP_Asm); 3034 3035 for (auto &A : {AssembleAction, BackendAction}) { 3036 OffloadAction::DeviceDependences DDep; 3037 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda); 3038 DeviceActions.push_back( 3039 C.MakeAction<OffloadAction>(DDep, A->getType())); 3040 } 3041 } 3042 3043 // We generate the fat binary if we have device input actions. 3044 if (!DeviceActions.empty()) { 3045 CudaFatBinary = 3046 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN); 3047 3048 if (!CompileDeviceOnly) { 3049 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3050 Action::OFK_Cuda); 3051 // Clear the fat binary, it is already a dependence to an host 3052 // action. 3053 CudaFatBinary = nullptr; 3054 } 3055 3056 // Remove the CUDA actions as they are already connected to an host 3057 // action or fat binary. 3058 CudaDeviceActions.clear(); 3059 } 3060 3061 // We avoid creating host action in device-only mode. 3062 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3063 } else if (CurPhase > phases::Backend) { 3064 // If we are past the backend phase and still have a device action, we 3065 // don't have to do anything as this action is already a device 3066 // top-level action. 3067 return ABRT_Success; 3068 } 3069 3070 assert(CurPhase < phases::Backend && "Generating single CUDA " 3071 "instructions should only occur " 3072 "before the backend phase!"); 3073 3074 // By default, we produce an action for each device arch. 3075 for (Action *&A : CudaDeviceActions) 3076 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 3077 3078 return ABRT_Success; 3079 } 3080 }; 3081 /// \brief HIP action builder. It injects device code in the host backend 3082 /// action. 3083 class HIPActionBuilder final : public CudaActionBuilderBase { 3084 /// The linker inputs obtained for each device arch. 3085 SmallVector<ActionList, 8> DeviceLinkerInputs; 3086 // The default bundling behavior depends on the type of output, therefore 3087 // BundleOutput needs to be tri-value: None, true, or false. 3088 // Bundle code objects except --no-gpu-output is specified for device 3089 // only compilation. Bundle other type of output files only if 3090 // --gpu-bundle-output is specified for device only compilation. 3091 Optional<bool> BundleOutput; 3092 3093 public: 3094 HIPActionBuilder(Compilation &C, DerivedArgList &Args, 3095 const Driver::InputList &Inputs) 3096 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) { 3097 DefaultCudaArch = CudaArch::GFX803; 3098 if (Args.hasArg(options::OPT_gpu_bundle_output, 3099 options::OPT_no_gpu_bundle_output)) 3100 BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output, 3101 options::OPT_no_gpu_bundle_output, true); 3102 } 3103 3104 bool canUseBundlerUnbundler() const override { return true; } 3105 3106 StringRef getCanonicalOffloadArch(StringRef IdStr) override { 3107 llvm::StringMap<bool> Features; 3108 // getHIPOffloadTargetTriple() is known to return valid value as it has 3109 // been called successfully in the CreateOffloadingDeviceToolChains(). 3110 auto ArchStr = parseTargetID( 3111 *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr, 3112 &Features); 3113 if (!ArchStr) { 3114 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr; 3115 C.setContainsError(); 3116 return StringRef(); 3117 } 3118 auto CanId = getCanonicalTargetID(ArchStr.getValue(), Features); 3119 return Args.MakeArgStringRef(CanId); 3120 }; 3121 3122 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>> 3123 getConflictOffloadArchCombination( 3124 const std::set<StringRef> &GpuArchs) override { 3125 return getConflictTargetIDCombination(GpuArchs); 3126 } 3127 3128 ActionBuilderReturnCode 3129 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3130 phases::ID CurPhase, phases::ID FinalPhase, 3131 PhasesTy &Phases) override { 3132 if (!IsActive) 3133 return ABRT_Inactive; 3134 3135 // amdgcn does not support linking of object files, therefore we skip 3136 // backend and assemble phases to output LLVM IR. Except for generating 3137 // non-relocatable device code, where we generate fat binary for device 3138 // code and pass to host in Backend phase. 3139 if (CudaDeviceActions.empty()) 3140 return ABRT_Success; 3141 3142 assert(((CurPhase == phases::Link && Relocatable) || 3143 CudaDeviceActions.size() == GpuArchList.size()) && 3144 "Expecting one action per GPU architecture."); 3145 assert(!CompileHostOnly && 3146 "Not expecting HIP actions in host-only compilation."); 3147 3148 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM && 3149 !EmitAsm) { 3150 // If we are in backend phase, we attempt to generate the fat binary. 3151 // We compile each arch to IR and use a link action to generate code 3152 // object containing ISA. Then we use a special "link" action to create 3153 // a fat binary containing all the code objects for different GPU's. 3154 // The fat binary is then an input to the host action. 3155 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3156 if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) { 3157 // When LTO is enabled, skip the backend and assemble phases and 3158 // use lld to link the bitcode. 3159 ActionList AL; 3160 AL.push_back(CudaDeviceActions[I]); 3161 // Create a link action to link device IR with device library 3162 // and generate ISA. 3163 CudaDeviceActions[I] = 3164 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 3165 } else { 3166 // When LTO is not enabled, we follow the conventional 3167 // compiler phases, including backend and assemble phases. 3168 ActionList AL; 3169 Action *BackendAction = nullptr; 3170 if (ToolChains.front()->getTriple().isSPIRV()) { 3171 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain 3172 // (HIPSPVToolChain) runs post-link LLVM IR passes. 3173 types::ID Output = Args.hasArg(options::OPT_S) 3174 ? types::TY_LLVM_IR 3175 : types::TY_LLVM_BC; 3176 BackendAction = 3177 C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output); 3178 } else 3179 BackendAction = C.getDriver().ConstructPhaseAction( 3180 C, Args, phases::Backend, CudaDeviceActions[I], 3181 AssociatedOffloadKind); 3182 auto AssembleAction = C.getDriver().ConstructPhaseAction( 3183 C, Args, phases::Assemble, BackendAction, 3184 AssociatedOffloadKind); 3185 AL.push_back(AssembleAction); 3186 // Create a link action to link device IR with device library 3187 // and generate ISA. 3188 CudaDeviceActions[I] = 3189 C.MakeAction<LinkJobAction>(AL, types::TY_Image); 3190 } 3191 3192 // OffloadingActionBuilder propagates device arch until an offload 3193 // action. Since the next action for creating fatbin does 3194 // not have device arch, whereas the above link action and its input 3195 // have device arch, an offload action is needed to stop the null 3196 // device arch of the next action being propagated to the above link 3197 // action. 3198 OffloadAction::DeviceDependences DDep; 3199 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3200 AssociatedOffloadKind); 3201 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3202 DDep, CudaDeviceActions[I]->getType()); 3203 } 3204 3205 if (!CompileDeviceOnly || !BundleOutput.hasValue() || 3206 BundleOutput.getValue()) { 3207 // Create HIP fat binary with a special "link" action. 3208 CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions, 3209 types::TY_HIP_FATBIN); 3210 3211 if (!CompileDeviceOnly) { 3212 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr, 3213 AssociatedOffloadKind); 3214 // Clear the fat binary, it is already a dependence to an host 3215 // action. 3216 CudaFatBinary = nullptr; 3217 } 3218 3219 // Remove the CUDA actions as they are already connected to an host 3220 // action or fat binary. 3221 CudaDeviceActions.clear(); 3222 } 3223 3224 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3225 } else if (CurPhase == phases::Link) { 3226 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch. 3227 // This happens to each device action originated from each input file. 3228 // Later on, device actions in DeviceLinkerInputs are used to create 3229 // device link actions in appendLinkDependences and the created device 3230 // link actions are passed to the offload action as device dependence. 3231 DeviceLinkerInputs.resize(CudaDeviceActions.size()); 3232 auto LI = DeviceLinkerInputs.begin(); 3233 for (auto *A : CudaDeviceActions) { 3234 LI->push_back(A); 3235 ++LI; 3236 } 3237 3238 // We will pass the device action as a host dependence, so we don't 3239 // need to do anything else with them. 3240 CudaDeviceActions.clear(); 3241 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success; 3242 } 3243 3244 // By default, we produce an action for each device arch. 3245 for (Action *&A : CudaDeviceActions) 3246 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A, 3247 AssociatedOffloadKind); 3248 3249 if (CompileDeviceOnly && CurPhase == FinalPhase && 3250 BundleOutput.hasValue() && BundleOutput.getValue()) { 3251 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 3252 OffloadAction::DeviceDependences DDep; 3253 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I], 3254 AssociatedOffloadKind); 3255 CudaDeviceActions[I] = C.MakeAction<OffloadAction>( 3256 DDep, CudaDeviceActions[I]->getType()); 3257 } 3258 CudaFatBinary = 3259 C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions); 3260 CudaDeviceActions.clear(); 3261 } 3262 3263 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host 3264 : ABRT_Success; 3265 } 3266 3267 void appendLinkDeviceActions(ActionList &AL) override { 3268 if (DeviceLinkerInputs.size() == 0) 3269 return; 3270 3271 assert(DeviceLinkerInputs.size() == GpuArchList.size() && 3272 "Linker inputs and GPU arch list sizes do not match."); 3273 3274 ActionList Actions; 3275 unsigned I = 0; 3276 // Append a new link action for each device. 3277 // Each entry in DeviceLinkerInputs corresponds to a GPU arch. 3278 for (auto &LI : DeviceLinkerInputs) { 3279 3280 types::ID Output = Args.hasArg(options::OPT_emit_llvm) 3281 ? types::TY_LLVM_BC 3282 : types::TY_Image; 3283 3284 auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(LI, Output); 3285 // Linking all inputs for the current GPU arch. 3286 // LI contains all the inputs for the linker. 3287 OffloadAction::DeviceDependences DeviceLinkDeps; 3288 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0], 3289 GpuArchList[I], AssociatedOffloadKind); 3290 Actions.push_back(C.MakeAction<OffloadAction>( 3291 DeviceLinkDeps, DeviceLinkAction->getType())); 3292 ++I; 3293 } 3294 DeviceLinkerInputs.clear(); 3295 3296 // If emitting LLVM, do not generate final host/device compilation action 3297 if (Args.hasArg(options::OPT_emit_llvm)) { 3298 AL.append(Actions); 3299 return; 3300 } 3301 3302 // Create a host object from all the device images by embedding them 3303 // in a fat binary for mixed host-device compilation. For device-only 3304 // compilation, creates a fat binary. 3305 OffloadAction::DeviceDependences DDeps; 3306 if (!CompileDeviceOnly || !BundleOutput.hasValue() || 3307 BundleOutput.getValue()) { 3308 auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>( 3309 Actions, 3310 CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object); 3311 DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr, 3312 AssociatedOffloadKind); 3313 // Offload the host object to the host linker. 3314 AL.push_back( 3315 C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType())); 3316 } else { 3317 AL.append(Actions); 3318 } 3319 } 3320 3321 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); } 3322 3323 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} 3324 }; 3325 3326 /// OpenMP action builder. The host bitcode is passed to the device frontend 3327 /// and all the device linked images are passed to the host link phase. 3328 class OpenMPActionBuilder final : public DeviceActionBuilder { 3329 /// The OpenMP actions for the current input. 3330 ActionList OpenMPDeviceActions; 3331 3332 /// The linker inputs obtained for each toolchain. 3333 SmallVector<ActionList, 8> DeviceLinkerInputs; 3334 3335 public: 3336 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args, 3337 const Driver::InputList &Inputs) 3338 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {} 3339 3340 ActionBuilderReturnCode 3341 getDeviceDependences(OffloadAction::DeviceDependences &DA, 3342 phases::ID CurPhase, phases::ID FinalPhase, 3343 PhasesTy &Phases) override { 3344 if (OpenMPDeviceActions.empty()) 3345 return ABRT_Inactive; 3346 3347 // We should always have an action for each input. 3348 assert(OpenMPDeviceActions.size() == ToolChains.size() && 3349 "Number of OpenMP actions and toolchains do not match."); 3350 3351 // The host only depends on device action in the linking phase, when all 3352 // the device images have to be embedded in the host image. 3353 if (CurPhase == phases::Link) { 3354 assert(ToolChains.size() == DeviceLinkerInputs.size() && 3355 "Toolchains and linker inputs sizes do not match."); 3356 auto LI = DeviceLinkerInputs.begin(); 3357 for (auto *A : OpenMPDeviceActions) { 3358 LI->push_back(A); 3359 ++LI; 3360 } 3361 3362 // We passed the device action as a host dependence, so we don't need to 3363 // do anything else with them. 3364 OpenMPDeviceActions.clear(); 3365 return ABRT_Success; 3366 } 3367 3368 // By default, we produce an action for each device arch. 3369 for (Action *&A : OpenMPDeviceActions) 3370 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A); 3371 3372 return ABRT_Success; 3373 } 3374 3375 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override { 3376 3377 // If this is an input action replicate it for each OpenMP toolchain. 3378 if (auto *IA = dyn_cast<InputAction>(HostAction)) { 3379 OpenMPDeviceActions.clear(); 3380 for (unsigned I = 0; I < ToolChains.size(); ++I) 3381 OpenMPDeviceActions.push_back( 3382 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType())); 3383 return ABRT_Success; 3384 } 3385 3386 // If this is an unbundling action use it as is for each OpenMP toolchain. 3387 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) { 3388 OpenMPDeviceActions.clear(); 3389 auto *IA = cast<InputAction>(UA->getInputs().back()); 3390 std::string FileName = IA->getInputArg().getAsString(Args); 3391 // Check if the type of the file is the same as the action. Do not 3392 // unbundle it if it is not. Do not unbundle .so files, for example, 3393 // which are not object files. 3394 if (IA->getType() == types::TY_Object && 3395 (!llvm::sys::path::has_extension(FileName) || 3396 types::lookupTypeForExtension( 3397 llvm::sys::path::extension(FileName).drop_front()) != 3398 types::TY_Object)) 3399 return ABRT_Inactive; 3400 for (unsigned I = 0; I < ToolChains.size(); ++I) { 3401 OpenMPDeviceActions.push_back(UA); 3402 UA->registerDependentActionInfo( 3403 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP); 3404 } 3405 return ABRT_Success; 3406 } 3407 3408 // When generating code for OpenMP we use the host compile phase result as 3409 // a dependence to the device compile phase so that it can learn what 3410 // declarations should be emitted. However, this is not the only use for 3411 // the host action, so we prevent it from being collapsed. 3412 if (isa<CompileJobAction>(HostAction)) { 3413 HostAction->setCannotBeCollapsedWithNextDependentAction(); 3414 assert(ToolChains.size() == OpenMPDeviceActions.size() && 3415 "Toolchains and device action sizes do not match."); 3416 OffloadAction::HostDependence HDep( 3417 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3418 /*BoundArch=*/nullptr, Action::OFK_OpenMP); 3419 auto TC = ToolChains.begin(); 3420 for (Action *&A : OpenMPDeviceActions) { 3421 assert(isa<CompileJobAction>(A)); 3422 OffloadAction::DeviceDependences DDep; 3423 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 3424 A = C.MakeAction<OffloadAction>(HDep, DDep); 3425 ++TC; 3426 } 3427 } 3428 return ABRT_Success; 3429 } 3430 3431 void appendTopLevelActions(ActionList &AL) override { 3432 if (OpenMPDeviceActions.empty()) 3433 return; 3434 3435 // We should always have an action for each input. 3436 assert(OpenMPDeviceActions.size() == ToolChains.size() && 3437 "Number of OpenMP actions and toolchains do not match."); 3438 3439 // Append all device actions followed by the proper offload action. 3440 auto TI = ToolChains.begin(); 3441 for (auto *A : OpenMPDeviceActions) { 3442 OffloadAction::DeviceDependences Dep; 3443 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP); 3444 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType())); 3445 ++TI; 3446 } 3447 // We no longer need the action stored in this builder. 3448 OpenMPDeviceActions.clear(); 3449 } 3450 3451 void appendLinkDeviceActions(ActionList &AL) override { 3452 assert(ToolChains.size() == DeviceLinkerInputs.size() && 3453 "Toolchains and linker inputs sizes do not match."); 3454 3455 // Append a new link action for each device. 3456 auto TC = ToolChains.begin(); 3457 for (auto &LI : DeviceLinkerInputs) { 3458 auto *DeviceLinkAction = 3459 C.MakeAction<LinkJobAction>(LI, types::TY_Image); 3460 OffloadAction::DeviceDependences DeviceLinkDeps; 3461 DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr, 3462 Action::OFK_OpenMP); 3463 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps, 3464 DeviceLinkAction->getType())); 3465 ++TC; 3466 } 3467 DeviceLinkerInputs.clear(); 3468 } 3469 3470 Action* appendLinkHostActions(ActionList &AL) override { 3471 // Create wrapper bitcode from the result of device link actions and compile 3472 // it to an object which will be added to the host link command. 3473 auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC); 3474 auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm); 3475 return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object); 3476 } 3477 3478 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {} 3479 3480 bool initialize() override { 3481 // Get the OpenMP toolchains. If we don't get any, the action builder will 3482 // know there is nothing to do related to OpenMP offloading. 3483 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); 3484 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE; 3485 ++TI) 3486 ToolChains.push_back(TI->second); 3487 3488 DeviceLinkerInputs.resize(ToolChains.size()); 3489 return false; 3490 } 3491 3492 bool canUseBundlerUnbundler() const override { 3493 // OpenMP should use bundled files whenever possible. 3494 return true; 3495 } 3496 }; 3497 3498 /// 3499 /// TODO: Add the implementation for other specialized builders here. 3500 /// 3501 3502 /// Specialized builders being used by this offloading action builder. 3503 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders; 3504 3505 /// Flag set to true if all valid builders allow file bundling/unbundling. 3506 bool CanUseBundler; 3507 3508 public: 3509 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args, 3510 const Driver::InputList &Inputs) 3511 : C(C) { 3512 // Create a specialized builder for each device toolchain. 3513 3514 IsValid = true; 3515 3516 // Create a specialized builder for CUDA. 3517 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs)); 3518 3519 // Create a specialized builder for HIP. 3520 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs)); 3521 3522 // Create a specialized builder for OpenMP. 3523 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs)); 3524 3525 // 3526 // TODO: Build other specialized builders here. 3527 // 3528 3529 // Initialize all the builders, keeping track of errors. If all valid 3530 // builders agree that we can use bundling, set the flag to true. 3531 unsigned ValidBuilders = 0u; 3532 unsigned ValidBuildersSupportingBundling = 0u; 3533 for (auto *SB : SpecializedBuilders) { 3534 IsValid = IsValid && !SB->initialize(); 3535 3536 // Update the counters if the builder is valid. 3537 if (SB->isValid()) { 3538 ++ValidBuilders; 3539 if (SB->canUseBundlerUnbundler()) 3540 ++ValidBuildersSupportingBundling; 3541 } 3542 } 3543 CanUseBundler = 3544 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling; 3545 } 3546 3547 ~OffloadingActionBuilder() { 3548 for (auto *SB : SpecializedBuilders) 3549 delete SB; 3550 } 3551 3552 /// Record a host action and its originating input argument. 3553 void recordHostAction(Action *HostAction, const Arg *InputArg) { 3554 assert(HostAction && "Invalid host action"); 3555 assert(InputArg && "Invalid input argument"); 3556 auto Loc = HostActionToInputArgMap.find(HostAction); 3557 if (Loc == HostActionToInputArgMap.end()) 3558 HostActionToInputArgMap[HostAction] = InputArg; 3559 assert(HostActionToInputArgMap[HostAction] == InputArg && 3560 "host action mapped to multiple input arguments"); 3561 } 3562 3563 /// Generate an action that adds device dependences (if any) to a host action. 3564 /// If no device dependence actions exist, just return the host action \a 3565 /// HostAction. If an error is found or if no builder requires the host action 3566 /// to be generated, return nullptr. 3567 Action * 3568 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg, 3569 phases::ID CurPhase, phases::ID FinalPhase, 3570 DeviceActionBuilder::PhasesTy &Phases) { 3571 if (!IsValid) 3572 return nullptr; 3573 3574 if (SpecializedBuilders.empty()) 3575 return HostAction; 3576 3577 assert(HostAction && "Invalid host action!"); 3578 recordHostAction(HostAction, InputArg); 3579 3580 OffloadAction::DeviceDependences DDeps; 3581 // Check if all the programming models agree we should not emit the host 3582 // action. Also, keep track of the offloading kinds employed. 3583 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3584 unsigned InactiveBuilders = 0u; 3585 unsigned IgnoringBuilders = 0u; 3586 for (auto *SB : SpecializedBuilders) { 3587 if (!SB->isValid()) { 3588 ++InactiveBuilders; 3589 continue; 3590 } 3591 3592 auto RetCode = 3593 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases); 3594 3595 // If the builder explicitly says the host action should be ignored, 3596 // we need to increment the variable that tracks the builders that request 3597 // the host object to be ignored. 3598 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host) 3599 ++IgnoringBuilders; 3600 3601 // Unless the builder was inactive for this action, we have to record the 3602 // offload kind because the host will have to use it. 3603 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3604 OffloadKind |= SB->getAssociatedOffloadKind(); 3605 } 3606 3607 // If all builders agree that the host object should be ignored, just return 3608 // nullptr. 3609 if (IgnoringBuilders && 3610 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders)) 3611 return nullptr; 3612 3613 if (DDeps.getActions().empty()) 3614 return HostAction; 3615 3616 // We have dependences we need to bundle together. We use an offload action 3617 // for that. 3618 OffloadAction::HostDependence HDep( 3619 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3620 /*BoundArch=*/nullptr, DDeps); 3621 return C.MakeAction<OffloadAction>(HDep, DDeps); 3622 } 3623 3624 /// Generate an action that adds a host dependence to a device action. The 3625 /// results will be kept in this action builder. Return true if an error was 3626 /// found. 3627 bool addHostDependenceToDeviceActions(Action *&HostAction, 3628 const Arg *InputArg) { 3629 if (!IsValid) 3630 return true; 3631 3632 recordHostAction(HostAction, InputArg); 3633 3634 // If we are supporting bundling/unbundling and the current action is an 3635 // input action of non-source file, we replace the host action by the 3636 // unbundling action. The bundler tool has the logic to detect if an input 3637 // is a bundle or not and if the input is not a bundle it assumes it is a 3638 // host file. Therefore it is safe to create an unbundling action even if 3639 // the input is not a bundle. 3640 if (CanUseBundler && isa<InputAction>(HostAction) && 3641 InputArg->getOption().getKind() == llvm::opt::Option::InputClass && 3642 (!types::isSrcFile(HostAction->getType()) || 3643 HostAction->getType() == types::TY_PP_HIP)) { 3644 auto UnbundlingHostAction = 3645 C.MakeAction<OffloadUnbundlingJobAction>(HostAction); 3646 UnbundlingHostAction->registerDependentActionInfo( 3647 C.getSingleOffloadToolChain<Action::OFK_Host>(), 3648 /*BoundArch=*/StringRef(), Action::OFK_Host); 3649 HostAction = UnbundlingHostAction; 3650 recordHostAction(HostAction, InputArg); 3651 } 3652 3653 assert(HostAction && "Invalid host action!"); 3654 3655 // Register the offload kinds that are used. 3656 auto &OffloadKind = InputArgToOffloadKindMap[InputArg]; 3657 for (auto *SB : SpecializedBuilders) { 3658 if (!SB->isValid()) 3659 continue; 3660 3661 auto RetCode = SB->addDeviceDepences(HostAction); 3662 3663 // Host dependences for device actions are not compatible with that same 3664 // action being ignored. 3665 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host && 3666 "Host dependence not expected to be ignored.!"); 3667 3668 // Unless the builder was inactive for this action, we have to record the 3669 // offload kind because the host will have to use it. 3670 if (RetCode != DeviceActionBuilder::ABRT_Inactive) 3671 OffloadKind |= SB->getAssociatedOffloadKind(); 3672 } 3673 3674 // Do not use unbundler if the Host does not depend on device action. 3675 if (OffloadKind == Action::OFK_None && CanUseBundler) 3676 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) 3677 HostAction = UA->getInputs().back(); 3678 3679 return false; 3680 } 3681 3682 /// Add the offloading top level actions to the provided action list. This 3683 /// function can replace the host action by a bundling action if the 3684 /// programming models allow it. 3685 bool appendTopLevelActions(ActionList &AL, Action *HostAction, 3686 const Arg *InputArg) { 3687 if (HostAction) 3688 recordHostAction(HostAction, InputArg); 3689 3690 // Get the device actions to be appended. 3691 ActionList OffloadAL; 3692 for (auto *SB : SpecializedBuilders) { 3693 if (!SB->isValid()) 3694 continue; 3695 SB->appendTopLevelActions(OffloadAL); 3696 } 3697 3698 // If we can use the bundler, replace the host action by the bundling one in 3699 // the resulting list. Otherwise, just append the device actions. For 3700 // device only compilation, HostAction is a null pointer, therefore only do 3701 // this when HostAction is not a null pointer. 3702 if (CanUseBundler && HostAction && 3703 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) { 3704 // Add the host action to the list in order to create the bundling action. 3705 OffloadAL.push_back(HostAction); 3706 3707 // We expect that the host action was just appended to the action list 3708 // before this method was called. 3709 assert(HostAction == AL.back() && "Host action not in the list??"); 3710 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL); 3711 recordHostAction(HostAction, InputArg); 3712 AL.back() = HostAction; 3713 } else 3714 AL.append(OffloadAL.begin(), OffloadAL.end()); 3715 3716 // Propagate to the current host action (if any) the offload information 3717 // associated with the current input. 3718 if (HostAction) 3719 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg], 3720 /*BoundArch=*/nullptr); 3721 return false; 3722 } 3723 3724 void appendDeviceLinkActions(ActionList &AL) { 3725 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3726 if (!SB->isValid()) 3727 continue; 3728 SB->appendLinkDeviceActions(AL); 3729 } 3730 } 3731 3732 Action *makeHostLinkAction() { 3733 // Build a list of device linking actions. 3734 ActionList DeviceAL; 3735 appendDeviceLinkActions(DeviceAL); 3736 if (DeviceAL.empty()) 3737 return nullptr; 3738 3739 // Let builders add host linking actions. 3740 Action* HA = nullptr; 3741 for (DeviceActionBuilder *SB : SpecializedBuilders) { 3742 if (!SB->isValid()) 3743 continue; 3744 HA = SB->appendLinkHostActions(DeviceAL); 3745 // This created host action has no originating input argument, therefore 3746 // needs to set its offloading kind directly. 3747 if (HA) 3748 HA->propagateHostOffloadInfo(SB->getAssociatedOffloadKind(), 3749 /*BoundArch=*/nullptr); 3750 } 3751 return HA; 3752 } 3753 3754 /// Processes the host linker action. This currently consists of replacing it 3755 /// with an offload action if there are device link objects and propagate to 3756 /// the host action all the offload kinds used in the current compilation. The 3757 /// resulting action is returned. 3758 Action *processHostLinkAction(Action *HostAction) { 3759 // Add all the dependences from the device linking actions. 3760 OffloadAction::DeviceDependences DDeps; 3761 for (auto *SB : SpecializedBuilders) { 3762 if (!SB->isValid()) 3763 continue; 3764 3765 SB->appendLinkDependences(DDeps); 3766 } 3767 3768 // Calculate all the offload kinds used in the current compilation. 3769 unsigned ActiveOffloadKinds = 0u; 3770 for (auto &I : InputArgToOffloadKindMap) 3771 ActiveOffloadKinds |= I.second; 3772 3773 // If we don't have device dependencies, we don't have to create an offload 3774 // action. 3775 if (DDeps.getActions().empty()) { 3776 // Set all the active offloading kinds to the link action. Given that it 3777 // is a link action it is assumed to depend on all actions generated so 3778 // far. 3779 HostAction->setHostOffloadInfo(ActiveOffloadKinds, 3780 /*BoundArch=*/nullptr); 3781 // Propagate active offloading kinds for each input to the link action. 3782 // Each input may have different active offloading kind. 3783 for (auto A : HostAction->inputs()) { 3784 auto ArgLoc = HostActionToInputArgMap.find(A); 3785 if (ArgLoc == HostActionToInputArgMap.end()) 3786 continue; 3787 auto OFKLoc = InputArgToOffloadKindMap.find(ArgLoc->second); 3788 if (OFKLoc == InputArgToOffloadKindMap.end()) 3789 continue; 3790 A->propagateHostOffloadInfo(OFKLoc->second, /*BoundArch=*/nullptr); 3791 } 3792 return HostAction; 3793 } 3794 3795 // Create the offload action with all dependences. When an offload action 3796 // is created the kinds are propagated to the host action, so we don't have 3797 // to do that explicitly here. 3798 OffloadAction::HostDependence HDep( 3799 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 3800 /*BoundArch*/ nullptr, ActiveOffloadKinds); 3801 return C.MakeAction<OffloadAction>(HDep, DDeps); 3802 } 3803 }; 3804 } // anonymous namespace. 3805 3806 void Driver::handleArguments(Compilation &C, DerivedArgList &Args, 3807 const InputList &Inputs, 3808 ActionList &Actions) const { 3809 3810 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames. 3811 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 3812 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 3813 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 3814 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 3815 Args.eraseArg(options::OPT__SLASH_Yc); 3816 Args.eraseArg(options::OPT__SLASH_Yu); 3817 YcArg = YuArg = nullptr; 3818 } 3819 if (YcArg && Inputs.size() > 1) { 3820 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 3821 Args.eraseArg(options::OPT__SLASH_Yc); 3822 YcArg = nullptr; 3823 } 3824 3825 Arg *FinalPhaseArg; 3826 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 3827 3828 if (FinalPhase == phases::Link) { 3829 // Emitting LLVM while linking disabled except in HIPAMD Toolchain 3830 if (Args.hasArg(options::OPT_emit_llvm) && !Args.hasArg(options::OPT_hip_link)) 3831 Diag(clang::diag::err_drv_emit_llvm_link); 3832 if (IsCLMode() && LTOMode != LTOK_None && 3833 !Args.getLastArgValue(options::OPT_fuse_ld_EQ) 3834 .equals_insensitive("lld")) 3835 Diag(clang::diag::err_drv_lto_without_lld); 3836 } 3837 3838 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) { 3839 // If only preprocessing or /Y- is used, all pch handling is disabled. 3840 // Rather than check for it everywhere, just remove clang-cl pch-related 3841 // flags here. 3842 Args.eraseArg(options::OPT__SLASH_Fp); 3843 Args.eraseArg(options::OPT__SLASH_Yc); 3844 Args.eraseArg(options::OPT__SLASH_Yu); 3845 YcArg = YuArg = nullptr; 3846 } 3847 3848 unsigned LastPLSize = 0; 3849 for (auto &I : Inputs) { 3850 types::ID InputType = I.first; 3851 const Arg *InputArg = I.second; 3852 3853 auto PL = types::getCompilationPhases(InputType); 3854 LastPLSize = PL.size(); 3855 3856 // If the first step comes after the final phase we are doing as part of 3857 // this compilation, warn the user about it. 3858 phases::ID InitialPhase = PL[0]; 3859 if (InitialPhase > FinalPhase) { 3860 if (InputArg->isClaimed()) 3861 continue; 3862 3863 // Claim here to avoid the more general unused warning. 3864 InputArg->claim(); 3865 3866 // Suppress all unused style warnings with -Qunused-arguments 3867 if (Args.hasArg(options::OPT_Qunused_arguments)) 3868 continue; 3869 3870 // Special case when final phase determined by binary name, rather than 3871 // by a command-line argument with a corresponding Arg. 3872 if (CCCIsCPP()) 3873 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 3874 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 3875 // Special case '-E' warning on a previously preprocessed file to make 3876 // more sense. 3877 else if (InitialPhase == phases::Compile && 3878 (Args.getLastArg(options::OPT__SLASH_EP, 3879 options::OPT__SLASH_P) || 3880 Args.getLastArg(options::OPT_E) || 3881 Args.getLastArg(options::OPT_M, options::OPT_MM)) && 3882 getPreprocessedType(InputType) == types::TY_INVALID) 3883 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 3884 << InputArg->getAsString(Args) << !!FinalPhaseArg 3885 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 3886 else 3887 Diag(clang::diag::warn_drv_input_file_unused) 3888 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 3889 << !!FinalPhaseArg 3890 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 3891 continue; 3892 } 3893 3894 if (YcArg) { 3895 // Add a separate precompile phase for the compile phase. 3896 if (FinalPhase >= phases::Compile) { 3897 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType); 3898 // Build the pipeline for the pch file. 3899 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType); 3900 for (phases::ID Phase : types::getCompilationPhases(HeaderType)) 3901 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 3902 assert(ClangClPch); 3903 Actions.push_back(ClangClPch); 3904 // The driver currently exits after the first failed command. This 3905 // relies on that behavior, to make sure if the pch generation fails, 3906 // the main compilation won't run. 3907 // FIXME: If the main compilation fails, the PCH generation should 3908 // probably not be considered successful either. 3909 } 3910 } 3911 } 3912 3913 // If we are linking, claim any options which are obviously only used for 3914 // compilation. 3915 // FIXME: Understand why the last Phase List length is used here. 3916 if (FinalPhase == phases::Link && LastPLSize == 1) { 3917 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 3918 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 3919 } 3920 } 3921 3922 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 3923 const InputList &Inputs, ActionList &Actions) const { 3924 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 3925 3926 if (!SuppressMissingInputWarning && Inputs.empty()) { 3927 Diag(clang::diag::err_drv_no_input_files); 3928 return; 3929 } 3930 3931 // Reject -Z* at the top level, these options should never have been exposed 3932 // by gcc. 3933 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 3934 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 3935 3936 // Diagnose misuse of /Fo. 3937 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 3938 StringRef V = A->getValue(); 3939 if (Inputs.size() > 1 && !V.empty() && 3940 !llvm::sys::path::is_separator(V.back())) { 3941 // Check whether /Fo tries to name an output file for multiple inputs. 3942 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 3943 << A->getSpelling() << V; 3944 Args.eraseArg(options::OPT__SLASH_Fo); 3945 } 3946 } 3947 3948 // Diagnose misuse of /Fa. 3949 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 3950 StringRef V = A->getValue(); 3951 if (Inputs.size() > 1 && !V.empty() && 3952 !llvm::sys::path::is_separator(V.back())) { 3953 // Check whether /Fa tries to name an asm file for multiple inputs. 3954 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 3955 << A->getSpelling() << V; 3956 Args.eraseArg(options::OPT__SLASH_Fa); 3957 } 3958 } 3959 3960 // Diagnose misuse of /o. 3961 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 3962 if (A->getValue()[0] == '\0') { 3963 // It has to have a value. 3964 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 3965 Args.eraseArg(options::OPT__SLASH_o); 3966 } 3967 } 3968 3969 handleArguments(C, Args, Inputs, Actions); 3970 3971 // Builder to be used to build offloading actions. 3972 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs); 3973 3974 // Construct the actions to perform. 3975 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr; 3976 ExtractAPIJobAction *ExtractAPIAction = nullptr; 3977 ActionList LinkerInputs; 3978 ActionList MergerInputs; 3979 3980 bool UseNewOffloadingDriver = 3981 C.isOffloadingHostKind(Action::OFK_OpenMP) && 3982 !Args.hasArg(options::OPT_fno_openmp_new_driver); 3983 3984 for (auto &I : Inputs) { 3985 types::ID InputType = I.first; 3986 const Arg *InputArg = I.second; 3987 3988 auto PL = types::getCompilationPhases(*this, Args, InputType); 3989 if (PL.empty()) 3990 continue; 3991 3992 auto FullPL = types::getCompilationPhases(InputType); 3993 3994 // Build the pipeline for this file. 3995 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 3996 3997 // Use the current host action in any of the offloading actions, if 3998 // required. 3999 if (!UseNewOffloadingDriver) 4000 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 4001 break; 4002 4003 for (phases::ID Phase : PL) { 4004 4005 // Add any offload action the host action depends on. 4006 if (!UseNewOffloadingDriver) 4007 Current = OffloadBuilder.addDeviceDependencesToHostAction( 4008 Current, InputArg, Phase, PL.back(), FullPL); 4009 if (!Current) 4010 break; 4011 4012 // Queue linker inputs. 4013 if (Phase == phases::Link) { 4014 assert(Phase == PL.back() && "linking must be final compilation step."); 4015 // We don't need to generate additional link commands if emitting AMD bitcode 4016 if (!(C.getInputArgs().hasArg(options::OPT_hip_link) && 4017 (C.getInputArgs().hasArg(options::OPT_emit_llvm)))) 4018 LinkerInputs.push_back(Current); 4019 Current = nullptr; 4020 break; 4021 } 4022 4023 // TODO: Consider removing this because the merged may not end up being 4024 // the final Phase in the pipeline. Perhaps the merged could just merge 4025 // and then pass an artifact of some sort to the Link Phase. 4026 // Queue merger inputs. 4027 if (Phase == phases::IfsMerge) { 4028 assert(Phase == PL.back() && "merging must be final compilation step."); 4029 MergerInputs.push_back(Current); 4030 Current = nullptr; 4031 break; 4032 } 4033 4034 // Each precompiled header file after a module file action is a module 4035 // header of that same module file, rather than being compiled to a 4036 // separate PCH. 4037 if (Phase == phases::Precompile && HeaderModuleAction && 4038 getPrecompiledType(InputType) == types::TY_PCH) { 4039 HeaderModuleAction->addModuleHeaderInput(Current); 4040 Current = nullptr; 4041 break; 4042 } 4043 4044 if (Phase == phases::Precompile && ExtractAPIAction) { 4045 ExtractAPIAction->addHeaderInput(Current); 4046 Current = nullptr; 4047 break; 4048 } 4049 4050 // Try to build the offloading actions and add the result as a dependency 4051 // to the host. 4052 if (UseNewOffloadingDriver) 4053 Current = BuildOffloadingActions(C, Args, I, Current); 4054 4055 // FIXME: Should we include any prior module file outputs as inputs of 4056 // later actions in the same command line? 4057 4058 // Otherwise construct the appropriate action. 4059 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current); 4060 4061 // We didn't create a new action, so we will just move to the next phase. 4062 if (NewCurrent == Current) 4063 continue; 4064 4065 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent)) 4066 HeaderModuleAction = HMA; 4067 else if (auto *EAA = dyn_cast<ExtractAPIJobAction>(NewCurrent)) 4068 ExtractAPIAction = EAA; 4069 4070 Current = NewCurrent; 4071 4072 // Use the current host action in any of the offloading actions, if 4073 // required. 4074 if (!UseNewOffloadingDriver) 4075 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg)) 4076 break; 4077 4078 if (Current->getType() == types::TY_Nothing) 4079 break; 4080 } 4081 4082 // If we ended with something, add to the output list. 4083 if (Current) 4084 Actions.push_back(Current); 4085 4086 // Add any top level actions generated for offloading. 4087 if (!UseNewOffloadingDriver) 4088 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg); 4089 else if (Current) 4090 Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(), 4091 /*BoundArch=*/nullptr); 4092 } 4093 4094 // Add a link action if necessary. 4095 4096 if (LinkerInputs.empty()) { 4097 Arg *FinalPhaseArg; 4098 if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link) 4099 if (!UseNewOffloadingDriver) 4100 OffloadBuilder.appendDeviceLinkActions(Actions); 4101 } 4102 4103 if (!LinkerInputs.empty()) { 4104 if (!UseNewOffloadingDriver) 4105 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction()) 4106 LinkerInputs.push_back(Wrapper); 4107 Action *LA; 4108 // Check if this Linker Job should emit a static library. 4109 if (ShouldEmitStaticLibrary(Args)) { 4110 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image); 4111 } else if (UseNewOffloadingDriver && 4112 C.getActiveOffloadKinds() != Action::OFK_None) { 4113 LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image); 4114 LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(), 4115 /*BoundArch=*/nullptr); 4116 } else { 4117 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image); 4118 } 4119 if (!UseNewOffloadingDriver) 4120 LA = OffloadBuilder.processHostLinkAction(LA); 4121 Actions.push_back(LA); 4122 } 4123 4124 // Add an interface stubs merge action if necessary. 4125 if (!MergerInputs.empty()) 4126 Actions.push_back( 4127 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4128 4129 if (Args.hasArg(options::OPT_emit_interface_stubs)) { 4130 auto PhaseList = types::getCompilationPhases( 4131 types::TY_IFS_CPP, 4132 Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge); 4133 4134 ActionList MergerInputs; 4135 4136 for (auto &I : Inputs) { 4137 types::ID InputType = I.first; 4138 const Arg *InputArg = I.second; 4139 4140 // Currently clang and the llvm assembler do not support generating symbol 4141 // stubs from assembly, so we skip the input on asm files. For ifs files 4142 // we rely on the normal pipeline setup in the pipeline setup code above. 4143 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm || 4144 InputType == types::TY_Asm) 4145 continue; 4146 4147 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 4148 4149 for (auto Phase : PhaseList) { 4150 switch (Phase) { 4151 default: 4152 llvm_unreachable( 4153 "IFS Pipeline can only consist of Compile followed by IfsMerge."); 4154 case phases::Compile: { 4155 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs 4156 // files where the .o file is located. The compile action can not 4157 // handle this. 4158 if (InputType == types::TY_Object) 4159 break; 4160 4161 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP); 4162 break; 4163 } 4164 case phases::IfsMerge: { 4165 assert(Phase == PhaseList.back() && 4166 "merging must be final compilation step."); 4167 MergerInputs.push_back(Current); 4168 Current = nullptr; 4169 break; 4170 } 4171 } 4172 } 4173 4174 // If we ended with something, add to the output list. 4175 if (Current) 4176 Actions.push_back(Current); 4177 } 4178 4179 // Add an interface stubs merge action if necessary. 4180 if (!MergerInputs.empty()) 4181 Actions.push_back( 4182 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image)); 4183 } 4184 4185 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom 4186 // Compile phase that prints out supported cpu models and quits. 4187 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) { 4188 // Use the -mcpu=? flag as the dummy input to cc1. 4189 Actions.clear(); 4190 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C); 4191 Actions.push_back( 4192 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing)); 4193 for (auto &I : Inputs) 4194 I.second->claim(); 4195 } 4196 4197 // Claim ignored clang-cl options. 4198 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 4199 4200 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 4201 // to non-CUDA compilations and should not trigger warnings there. 4202 Args.ClaimAllArgs(options::OPT_cuda_host_only); 4203 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 4204 } 4205 4206 Action *Driver::BuildOffloadingActions(Compilation &C, 4207 llvm::opt::DerivedArgList &Args, 4208 const InputTy &Input, 4209 Action *HostAction) const { 4210 if (!isa<CompileJobAction>(HostAction)) 4211 return HostAction; 4212 4213 OffloadAction::DeviceDependences DDeps; 4214 4215 types::ID InputType = Input.first; 4216 const Arg *InputArg = Input.second; 4217 4218 const Action::OffloadKind OffloadKinds[] = {Action::OFK_OpenMP}; 4219 4220 for (Action::OffloadKind Kind : OffloadKinds) { 4221 SmallVector<const ToolChain *, 2> ToolChains; 4222 ActionList DeviceActions; 4223 4224 auto TCRange = C.getOffloadToolChains(Kind); 4225 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI) 4226 ToolChains.push_back(TI->second); 4227 4228 if (ToolChains.empty()) 4229 continue; 4230 4231 for (unsigned I = 0; I < ToolChains.size(); ++I) 4232 DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType)); 4233 4234 if (DeviceActions.empty()) 4235 return HostAction; 4236 4237 auto PL = types::getCompilationPhases(*this, Args, InputType); 4238 4239 for (phases::ID Phase : PL) { 4240 if (Phase == phases::Link) { 4241 assert(Phase == PL.back() && "linking must be final compilation step."); 4242 break; 4243 } 4244 4245 auto TC = ToolChains.begin(); 4246 for (Action *&A : DeviceActions) { 4247 A = ConstructPhaseAction(C, Args, Phase, A, Kind); 4248 4249 if (isa<CompileJobAction>(A) && Kind == Action::OFK_OpenMP) { 4250 HostAction->setCannotBeCollapsedWithNextDependentAction(); 4251 OffloadAction::HostDependence HDep( 4252 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4253 /*BourdArch=*/nullptr, Action::OFK_OpenMP); 4254 OffloadAction::DeviceDependences DDep; 4255 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Kind); 4256 A = C.MakeAction<OffloadAction>(HDep, DDep); 4257 } 4258 ++TC; 4259 } 4260 } 4261 4262 auto TC = ToolChains.begin(); 4263 for (Action *A : DeviceActions) { 4264 DDeps.add(*A, **TC, /*BoundArch=*/nullptr, Kind); 4265 TC++; 4266 } 4267 } 4268 4269 OffloadAction::HostDependence HDep( 4270 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(), 4271 /*BoundArch=*/nullptr, DDeps); 4272 return C.MakeAction<OffloadAction>(HDep, DDeps); 4273 } 4274 4275 Action *Driver::ConstructPhaseAction( 4276 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input, 4277 Action::OffloadKind TargetDeviceOffloadKind) const { 4278 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 4279 4280 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 4281 // encode this in the steps because the intermediate type depends on 4282 // arguments. Just special case here. 4283 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm) 4284 return Input; 4285 4286 // Build the appropriate action. 4287 switch (Phase) { 4288 case phases::Link: 4289 llvm_unreachable("link action invalid here."); 4290 case phases::IfsMerge: 4291 llvm_unreachable("ifsmerge action invalid here."); 4292 case phases::Preprocess: { 4293 types::ID OutputTy; 4294 // -M and -MM specify the dependency file name by altering the output type, 4295 // -if -MD and -MMD are not specified. 4296 if (Args.hasArg(options::OPT_M, options::OPT_MM) && 4297 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) { 4298 OutputTy = types::TY_Dependencies; 4299 } else { 4300 OutputTy = Input->getType(); 4301 if (!Args.hasFlag(options::OPT_frewrite_includes, 4302 options::OPT_fno_rewrite_includes, false) && 4303 !Args.hasFlag(options::OPT_frewrite_imports, 4304 options::OPT_fno_rewrite_imports, false) && 4305 !CCGenDiagnostics) 4306 OutputTy = types::getPreprocessedType(OutputTy); 4307 assert(OutputTy != types::TY_INVALID && 4308 "Cannot preprocess this input type!"); 4309 } 4310 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 4311 } 4312 case phases::Precompile: { 4313 // API extraction should not generate an actual precompilation action. 4314 if (Args.hasArg(options::OPT_extract_api)) 4315 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO); 4316 4317 types::ID OutputTy = getPrecompiledType(Input->getType()); 4318 assert(OutputTy != types::TY_INVALID && 4319 "Cannot precompile this input type!"); 4320 4321 // If we're given a module name, precompile header file inputs as a 4322 // module, not as a precompiled header. 4323 const char *ModName = nullptr; 4324 if (OutputTy == types::TY_PCH) { 4325 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ)) 4326 ModName = A->getValue(); 4327 if (ModName) 4328 OutputTy = types::TY_ModuleFile; 4329 } 4330 4331 if (Args.hasArg(options::OPT_fsyntax_only)) { 4332 // Syntax checks should not emit a PCH file 4333 OutputTy = types::TY_Nothing; 4334 } 4335 4336 if (ModName) 4337 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy, 4338 ModName); 4339 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 4340 } 4341 case phases::Compile: { 4342 if (Args.hasArg(options::OPT_fsyntax_only)) 4343 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 4344 if (Args.hasArg(options::OPT_rewrite_objc)) 4345 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 4346 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 4347 return C.MakeAction<CompileJobAction>(Input, 4348 types::TY_RewrittenLegacyObjC); 4349 if (Args.hasArg(options::OPT__analyze)) 4350 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 4351 if (Args.hasArg(options::OPT__migrate)) 4352 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 4353 if (Args.hasArg(options::OPT_emit_ast)) 4354 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 4355 if (Args.hasArg(options::OPT_module_file_info)) 4356 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 4357 if (Args.hasArg(options::OPT_verify_pch)) 4358 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 4359 if (Args.hasArg(options::OPT_extract_api)) 4360 return C.MakeAction<ExtractAPIJobAction>(Input, types::TY_API_INFO); 4361 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 4362 } 4363 case phases::Backend: { 4364 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) { 4365 types::ID Output = 4366 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 4367 return C.MakeAction<BackendJobAction>(Input, Output); 4368 } 4369 if (isUsingLTO(/* IsOffload */ true) && 4370 TargetDeviceOffloadKind == Action::OFK_OpenMP) { 4371 types::ID Output = 4372 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 4373 return C.MakeAction<BackendJobAction>(Input, Output); 4374 } 4375 if (Args.hasArg(options::OPT_emit_llvm) || 4376 (TargetDeviceOffloadKind == Action::OFK_HIP && 4377 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 4378 false))) { 4379 types::ID Output = 4380 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 4381 return C.MakeAction<BackendJobAction>(Input, Output); 4382 } 4383 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 4384 } 4385 case phases::Assemble: 4386 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 4387 } 4388 4389 llvm_unreachable("invalid phase in ConstructPhaseAction"); 4390 } 4391 4392 void Driver::BuildJobs(Compilation &C) const { 4393 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4394 4395 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 4396 4397 // It is an error to provide a -o option if we are making multiple output 4398 // files. There are exceptions: 4399 // 4400 // IfsMergeJob: when generating interface stubs enabled we want to be able to 4401 // generate the stub file at the same time that we generate the real 4402 // library/a.out. So when a .o, .so, etc are the output, with clang interface 4403 // stubs there will also be a .ifs and .ifso at the same location. 4404 // 4405 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled 4406 // and -c is passed, we still want to be able to generate a .ifs file while 4407 // we are also generating .o files. So we allow more than one output file in 4408 // this case as well. 4409 // 4410 if (FinalOutput) { 4411 unsigned NumOutputs = 0; 4412 unsigned NumIfsOutputs = 0; 4413 for (const Action *A : C.getActions()) 4414 if (A->getType() != types::TY_Nothing && 4415 !(A->getKind() == Action::IfsMergeJobClass || 4416 (A->getType() == clang::driver::types::TY_IFS_CPP && 4417 A->getKind() == clang::driver::Action::CompileJobClass && 4418 0 == NumIfsOutputs++) || 4419 (A->getKind() == Action::BindArchClass && A->getInputs().size() && 4420 A->getInputs().front()->getKind() == Action::IfsMergeJobClass))) 4421 ++NumOutputs; 4422 4423 if (NumOutputs > 1) { 4424 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 4425 FinalOutput = nullptr; 4426 } 4427 } 4428 4429 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple(); 4430 if (RawTriple.isOSAIX()) { 4431 if (Arg *A = C.getArgs().getLastArg(options::OPT_G)) 4432 Diag(diag::err_drv_unsupported_opt_for_target) 4433 << A->getSpelling() << RawTriple.str(); 4434 if (LTOMode == LTOK_Thin) 4435 Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX"; 4436 } 4437 4438 // Collect the list of architectures. 4439 llvm::StringSet<> ArchNames; 4440 if (RawTriple.isOSBinFormatMachO()) 4441 for (const Arg *A : C.getArgs()) 4442 if (A->getOption().matches(options::OPT_arch)) 4443 ArchNames.insert(A->getValue()); 4444 4445 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 4446 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults; 4447 for (Action *A : C.getActions()) { 4448 // If we are linking an image for multiple archs then the linker wants 4449 // -arch_multiple and -final_output <final image name>. Unfortunately, this 4450 // doesn't fit in cleanly because we have to pass this information down. 4451 // 4452 // FIXME: This is a hack; find a cleaner way to integrate this into the 4453 // process. 4454 const char *LinkingOutput = nullptr; 4455 if (isa<LipoJobAction>(A)) { 4456 if (FinalOutput) 4457 LinkingOutput = FinalOutput->getValue(); 4458 else 4459 LinkingOutput = getDefaultImageName(); 4460 } 4461 4462 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 4463 /*BoundArch*/ StringRef(), 4464 /*AtTopLevel*/ true, 4465 /*MultipleArchs*/ ArchNames.size() > 1, 4466 /*LinkingOutput*/ LinkingOutput, CachedResults, 4467 /*TargetDeviceOffloadKind*/ Action::OFK_None); 4468 } 4469 4470 // If we have more than one job, then disable integrated-cc1 for now. Do this 4471 // also when we need to report process execution statistics. 4472 if (C.getJobs().size() > 1 || CCPrintProcessStats) 4473 for (auto &J : C.getJobs()) 4474 J.InProcess = false; 4475 4476 if (CCPrintProcessStats) { 4477 C.setPostCallback([=](const Command &Cmd, int Res) { 4478 Optional<llvm::sys::ProcessStatistics> ProcStat = 4479 Cmd.getProcessStatistics(); 4480 if (!ProcStat) 4481 return; 4482 4483 const char *LinkingOutput = nullptr; 4484 if (FinalOutput) 4485 LinkingOutput = FinalOutput->getValue(); 4486 else if (!Cmd.getOutputFilenames().empty()) 4487 LinkingOutput = Cmd.getOutputFilenames().front().c_str(); 4488 else 4489 LinkingOutput = getDefaultImageName(); 4490 4491 if (CCPrintStatReportFilename.empty()) { 4492 using namespace llvm; 4493 // Human readable output. 4494 outs() << sys::path::filename(Cmd.getExecutable()) << ": " 4495 << "output=" << LinkingOutput; 4496 outs() << ", total=" 4497 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms" 4498 << ", user=" 4499 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms" 4500 << ", mem=" << ProcStat->PeakMemory << " Kb\n"; 4501 } else { 4502 // CSV format. 4503 std::string Buffer; 4504 llvm::raw_string_ostream Out(Buffer); 4505 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()), 4506 /*Quote*/ true); 4507 Out << ','; 4508 llvm::sys::printArg(Out, LinkingOutput, true); 4509 Out << ',' << ProcStat->TotalTime.count() << ',' 4510 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory 4511 << '\n'; 4512 Out.flush(); 4513 std::error_code EC; 4514 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC, 4515 llvm::sys::fs::OF_Append | 4516 llvm::sys::fs::OF_Text); 4517 if (EC) 4518 return; 4519 auto L = OS.lock(); 4520 if (!L) { 4521 llvm::errs() << "ERROR: Cannot lock file " 4522 << CCPrintStatReportFilename << ": " 4523 << toString(L.takeError()) << "\n"; 4524 return; 4525 } 4526 OS << Buffer; 4527 OS.flush(); 4528 } 4529 }); 4530 } 4531 4532 // If the user passed -Qunused-arguments or there were errors, don't warn 4533 // about any unused arguments. 4534 if (Diags.hasErrorOccurred() || 4535 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 4536 return; 4537 4538 // Claim -### here. 4539 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 4540 4541 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 4542 (void)C.getArgs().hasArg(options::OPT_driver_mode); 4543 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 4544 4545 for (Arg *A : C.getArgs()) { 4546 // FIXME: It would be nice to be able to send the argument to the 4547 // DiagnosticsEngine, so that extra values, position, and so on could be 4548 // printed. 4549 if (!A->isClaimed()) { 4550 if (A->getOption().hasFlag(options::NoArgumentUnused)) 4551 continue; 4552 4553 // Suppress the warning automatically if this is just a flag, and it is an 4554 // instance of an argument we already claimed. 4555 const Option &Opt = A->getOption(); 4556 if (Opt.getKind() == Option::FlagClass) { 4557 bool DuplicateClaimed = false; 4558 4559 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 4560 if (AA->isClaimed()) { 4561 DuplicateClaimed = true; 4562 break; 4563 } 4564 } 4565 4566 if (DuplicateClaimed) 4567 continue; 4568 } 4569 4570 // In clang-cl, don't mention unknown arguments here since they have 4571 // already been warned about. 4572 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 4573 Diag(clang::diag::warn_drv_unused_argument) 4574 << A->getAsString(C.getArgs()); 4575 } 4576 } 4577 } 4578 4579 namespace { 4580 /// Utility class to control the collapse of dependent actions and select the 4581 /// tools accordingly. 4582 class ToolSelector final { 4583 /// The tool chain this selector refers to. 4584 const ToolChain &TC; 4585 4586 /// The compilation this selector refers to. 4587 const Compilation &C; 4588 4589 /// The base action this selector refers to. 4590 const JobAction *BaseAction; 4591 4592 /// Set to true if the current toolchain refers to host actions. 4593 bool IsHostSelector; 4594 4595 /// Set to true if save-temps and embed-bitcode functionalities are active. 4596 bool SaveTemps; 4597 bool EmbedBitcode; 4598 4599 /// Get previous dependent action or null if that does not exist. If 4600 /// \a CanBeCollapsed is false, that action must be legal to collapse or 4601 /// null will be returned. 4602 const JobAction *getPrevDependentAction(const ActionList &Inputs, 4603 ActionList &SavedOffloadAction, 4604 bool CanBeCollapsed = true) { 4605 // An option can be collapsed only if it has a single input. 4606 if (Inputs.size() != 1) 4607 return nullptr; 4608 4609 Action *CurAction = *Inputs.begin(); 4610 if (CanBeCollapsed && 4611 !CurAction->isCollapsingWithNextDependentActionLegal()) 4612 return nullptr; 4613 4614 // If the input action is an offload action. Look through it and save any 4615 // offload action that can be dropped in the event of a collapse. 4616 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) { 4617 // If the dependent action is a device action, we will attempt to collapse 4618 // only with other device actions. Otherwise, we would do the same but 4619 // with host actions only. 4620 if (!IsHostSelector) { 4621 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) { 4622 CurAction = 4623 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true); 4624 if (CanBeCollapsed && 4625 !CurAction->isCollapsingWithNextDependentActionLegal()) 4626 return nullptr; 4627 SavedOffloadAction.push_back(OA); 4628 return dyn_cast<JobAction>(CurAction); 4629 } 4630 } else if (OA->hasHostDependence()) { 4631 CurAction = OA->getHostDependence(); 4632 if (CanBeCollapsed && 4633 !CurAction->isCollapsingWithNextDependentActionLegal()) 4634 return nullptr; 4635 SavedOffloadAction.push_back(OA); 4636 return dyn_cast<JobAction>(CurAction); 4637 } 4638 return nullptr; 4639 } 4640 4641 return dyn_cast<JobAction>(CurAction); 4642 } 4643 4644 /// Return true if an assemble action can be collapsed. 4645 bool canCollapseAssembleAction() const { 4646 return TC.useIntegratedAs() && !SaveTemps && 4647 !C.getArgs().hasArg(options::OPT_via_file_asm) && 4648 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 4649 !C.getArgs().hasArg(options::OPT__SLASH_Fa); 4650 } 4651 4652 /// Return true if a preprocessor action can be collapsed. 4653 bool canCollapsePreprocessorAction() const { 4654 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 4655 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 4656 !C.getArgs().hasArg(options::OPT_rewrite_objc); 4657 } 4658 4659 /// Struct that relates an action with the offload actions that would be 4660 /// collapsed with it. 4661 struct JobActionInfo final { 4662 /// The action this info refers to. 4663 const JobAction *JA = nullptr; 4664 /// The offload actions we need to take care off if this action is 4665 /// collapsed. 4666 ActionList SavedOffloadAction; 4667 }; 4668 4669 /// Append collapsed offload actions from the give nnumber of elements in the 4670 /// action info array. 4671 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction, 4672 ArrayRef<JobActionInfo> &ActionInfo, 4673 unsigned ElementNum) { 4674 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements."); 4675 for (unsigned I = 0; I < ElementNum; ++I) 4676 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(), 4677 ActionInfo[I].SavedOffloadAction.end()); 4678 } 4679 4680 /// Functions that attempt to perform the combining. They detect if that is 4681 /// legal, and if so they update the inputs \a Inputs and the offload action 4682 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with 4683 /// the combined action is returned. If the combining is not legal or if the 4684 /// tool does not exist, null is returned. 4685 /// Currently three kinds of collapsing are supported: 4686 /// - Assemble + Backend + Compile; 4687 /// - Assemble + Backend ; 4688 /// - Backend + Compile. 4689 const Tool * 4690 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 4691 ActionList &Inputs, 4692 ActionList &CollapsedOffloadAction) { 4693 if (ActionInfo.size() < 3 || !canCollapseAssembleAction()) 4694 return nullptr; 4695 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 4696 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 4697 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA); 4698 if (!AJ || !BJ || !CJ) 4699 return nullptr; 4700 4701 // Get compiler tool. 4702 const Tool *T = TC.SelectTool(*CJ); 4703 if (!T) 4704 return nullptr; 4705 4706 // Can't collapse if we don't have codegen support unless we are 4707 // emitting LLVM IR. 4708 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 4709 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 4710 return nullptr; 4711 4712 // When using -fembed-bitcode, it is required to have the same tool (clang) 4713 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 4714 if (EmbedBitcode) { 4715 const Tool *BT = TC.SelectTool(*BJ); 4716 if (BT == T) 4717 return nullptr; 4718 } 4719 4720 if (!T->hasIntegratedAssembler()) 4721 return nullptr; 4722 4723 Inputs = CJ->getInputs(); 4724 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4725 /*NumElements=*/3); 4726 return T; 4727 } 4728 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo, 4729 ActionList &Inputs, 4730 ActionList &CollapsedOffloadAction) { 4731 if (ActionInfo.size() < 2 || !canCollapseAssembleAction()) 4732 return nullptr; 4733 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA); 4734 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA); 4735 if (!AJ || !BJ) 4736 return nullptr; 4737 4738 // Get backend tool. 4739 const Tool *T = TC.SelectTool(*BJ); 4740 if (!T) 4741 return nullptr; 4742 4743 if (!T->hasIntegratedAssembler()) 4744 return nullptr; 4745 4746 Inputs = BJ->getInputs(); 4747 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4748 /*NumElements=*/2); 4749 return T; 4750 } 4751 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo, 4752 ActionList &Inputs, 4753 ActionList &CollapsedOffloadAction) { 4754 if (ActionInfo.size() < 2) 4755 return nullptr; 4756 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA); 4757 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA); 4758 if (!BJ || !CJ) 4759 return nullptr; 4760 4761 // Check if the initial input (to the compile job or its predessor if one 4762 // exists) is LLVM bitcode. In that case, no preprocessor step is required 4763 // and we can still collapse the compile and backend jobs when we have 4764 // -save-temps. I.e. there is no need for a separate compile job just to 4765 // emit unoptimized bitcode. 4766 bool InputIsBitcode = true; 4767 for (size_t i = 1; i < ActionInfo.size(); i++) 4768 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC && 4769 ActionInfo[i].JA->getType() != types::TY_LTO_BC) { 4770 InputIsBitcode = false; 4771 break; 4772 } 4773 if (!InputIsBitcode && !canCollapsePreprocessorAction()) 4774 return nullptr; 4775 4776 // Get compiler tool. 4777 const Tool *T = TC.SelectTool(*CJ); 4778 if (!T) 4779 return nullptr; 4780 4781 // Can't collapse if we don't have codegen support unless we are 4782 // emitting LLVM IR. 4783 bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType()); 4784 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR())) 4785 return nullptr; 4786 4787 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode)) 4788 return nullptr; 4789 4790 Inputs = CJ->getInputs(); 4791 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo, 4792 /*NumElements=*/2); 4793 return T; 4794 } 4795 4796 /// Updates the inputs if the obtained tool supports combining with 4797 /// preprocessor action, and the current input is indeed a preprocessor 4798 /// action. If combining results in the collapse of offloading actions, those 4799 /// are appended to \a CollapsedOffloadAction. 4800 void combineWithPreprocessor(const Tool *T, ActionList &Inputs, 4801 ActionList &CollapsedOffloadAction) { 4802 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP()) 4803 return; 4804 4805 // Attempt to get a preprocessor action dependence. 4806 ActionList PreprocessJobOffloadActions; 4807 ActionList NewInputs; 4808 for (Action *A : Inputs) { 4809 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions); 4810 if (!PJ || !isa<PreprocessJobAction>(PJ)) { 4811 NewInputs.push_back(A); 4812 continue; 4813 } 4814 4815 // This is legal to combine. Append any offload action we found and add the 4816 // current input to preprocessor inputs. 4817 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(), 4818 PreprocessJobOffloadActions.end()); 4819 NewInputs.append(PJ->input_begin(), PJ->input_end()); 4820 } 4821 Inputs = NewInputs; 4822 } 4823 4824 public: 4825 ToolSelector(const JobAction *BaseAction, const ToolChain &TC, 4826 const Compilation &C, bool SaveTemps, bool EmbedBitcode) 4827 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps), 4828 EmbedBitcode(EmbedBitcode) { 4829 assert(BaseAction && "Invalid base action."); 4830 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None; 4831 } 4832 4833 /// Check if a chain of actions can be combined and return the tool that can 4834 /// handle the combination of actions. The pointer to the current inputs \a 4835 /// Inputs and the list of offload actions \a CollapsedOffloadActions 4836 /// connected to collapsed actions are updated accordingly. The latter enables 4837 /// the caller of the selector to process them afterwards instead of just 4838 /// dropping them. If no suitable tool is found, null will be returned. 4839 const Tool *getTool(ActionList &Inputs, 4840 ActionList &CollapsedOffloadAction) { 4841 // 4842 // Get the largest chain of actions that we could combine. 4843 // 4844 4845 SmallVector<JobActionInfo, 5> ActionChain(1); 4846 ActionChain.back().JA = BaseAction; 4847 while (ActionChain.back().JA) { 4848 const Action *CurAction = ActionChain.back().JA; 4849 4850 // Grow the chain by one element. 4851 ActionChain.resize(ActionChain.size() + 1); 4852 JobActionInfo &AI = ActionChain.back(); 4853 4854 // Attempt to fill it with the 4855 AI.JA = 4856 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction); 4857 } 4858 4859 // Pop the last action info as it could not be filled. 4860 ActionChain.pop_back(); 4861 4862 // 4863 // Attempt to combine actions. If all combining attempts failed, just return 4864 // the tool of the provided action. At the end we attempt to combine the 4865 // action with any preprocessor action it may depend on. 4866 // 4867 4868 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs, 4869 CollapsedOffloadAction); 4870 if (!T) 4871 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction); 4872 if (!T) 4873 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction); 4874 if (!T) { 4875 Inputs = BaseAction->getInputs(); 4876 T = TC.SelectTool(*BaseAction); 4877 } 4878 4879 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction); 4880 return T; 4881 } 4882 }; 4883 } 4884 4885 /// Return a string that uniquely identifies the result of a job. The bound arch 4886 /// is not necessarily represented in the toolchain's triple -- for example, 4887 /// armv7 and armv7s both map to the same triple -- so we need both in our map. 4888 /// Also, we need to add the offloading device kind, as the same tool chain can 4889 /// be used for host and device for some programming models, e.g. OpenMP. 4890 static std::string GetTriplePlusArchString(const ToolChain *TC, 4891 StringRef BoundArch, 4892 Action::OffloadKind OffloadKind) { 4893 std::string TriplePlusArch = TC->getTriple().normalize(); 4894 if (!BoundArch.empty()) { 4895 TriplePlusArch += "-"; 4896 TriplePlusArch += BoundArch; 4897 } 4898 TriplePlusArch += "-"; 4899 TriplePlusArch += Action::GetOffloadKindName(OffloadKind); 4900 return TriplePlusArch; 4901 } 4902 4903 InputInfoList Driver::BuildJobsForAction( 4904 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 4905 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 4906 std::map<std::pair<const Action *, std::string>, InputInfoList> 4907 &CachedResults, 4908 Action::OffloadKind TargetDeviceOffloadKind) const { 4909 std::pair<const Action *, std::string> ActionTC = { 4910 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 4911 auto CachedResult = CachedResults.find(ActionTC); 4912 if (CachedResult != CachedResults.end()) { 4913 return CachedResult->second; 4914 } 4915 InputInfoList Result = BuildJobsForActionNoCache( 4916 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput, 4917 CachedResults, TargetDeviceOffloadKind); 4918 CachedResults[ActionTC] = Result; 4919 return Result; 4920 } 4921 4922 InputInfoList Driver::BuildJobsForActionNoCache( 4923 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 4924 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 4925 std::map<std::pair<const Action *, std::string>, InputInfoList> 4926 &CachedResults, 4927 Action::OffloadKind TargetDeviceOffloadKind) const { 4928 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 4929 4930 InputInfoList OffloadDependencesInputInfo; 4931 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None; 4932 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) { 4933 // The 'Darwin' toolchain is initialized only when its arguments are 4934 // computed. Get the default arguments for OFK_None to ensure that 4935 // initialization is performed before processing the offload action. 4936 // FIXME: Remove when darwin's toolchain is initialized during construction. 4937 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None); 4938 4939 // The offload action is expected to be used in four different situations. 4940 // 4941 // a) Set a toolchain/architecture/kind for a host action: 4942 // Host Action 1 -> OffloadAction -> Host Action 2 4943 // 4944 // b) Set a toolchain/architecture/kind for a device action; 4945 // Device Action 1 -> OffloadAction -> Device Action 2 4946 // 4947 // c) Specify a device dependence to a host action; 4948 // Device Action 1 _ 4949 // \ 4950 // Host Action 1 ---> OffloadAction -> Host Action 2 4951 // 4952 // d) Specify a host dependence to a device action. 4953 // Host Action 1 _ 4954 // \ 4955 // Device Action 1 ---> OffloadAction -> Device Action 2 4956 // 4957 // For a) and b), we just return the job generated for the dependence. For 4958 // c) and d) we override the current action with the host/device dependence 4959 // if the current toolchain is host/device and set the offload dependences 4960 // info with the jobs obtained from the device/host dependence(s). 4961 4962 // If there is a single device option, just generate the job for it. 4963 if (OA->hasSingleDeviceDependence()) { 4964 InputInfoList DevA; 4965 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC, 4966 const char *DepBoundArch) { 4967 DevA = 4968 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel, 4969 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, 4970 CachedResults, DepA->getOffloadingDeviceKind()); 4971 }); 4972 return DevA; 4973 } 4974 4975 // If 'Action 2' is host, we generate jobs for the device dependences and 4976 // override the current action with the host dependence. Otherwise, we 4977 // generate the host dependences and override the action with the device 4978 // dependence. The dependences can't therefore be a top-level action. 4979 OA->doOnEachDependence( 4980 /*IsHostDependence=*/BuildingForOffloadDevice, 4981 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 4982 OffloadDependencesInputInfo.append(BuildJobsForAction( 4983 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false, 4984 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults, 4985 DepA->getOffloadingDeviceKind())); 4986 }); 4987 4988 A = BuildingForOffloadDevice 4989 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true) 4990 : OA->getHostDependence(); 4991 4992 // We may have already built this action as a part of the offloading 4993 // toolchain, return the cached input if so. 4994 std::pair<const Action *, std::string> ActionTC = { 4995 OA->getHostDependence(), 4996 GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 4997 if (CachedResults.find(ActionTC) != CachedResults.end()) { 4998 InputInfoList Inputs = CachedResults[ActionTC]; 4999 Inputs.append(OffloadDependencesInputInfo); 5000 return Inputs; 5001 } 5002 } 5003 5004 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 5005 // FIXME: It would be nice to not claim this here; maybe the old scheme of 5006 // just using Args was better? 5007 const Arg &Input = IA->getInputArg(); 5008 Input.claim(); 5009 if (Input.getOption().matches(options::OPT_INPUT)) { 5010 const char *Name = Input.getValue(); 5011 return {InputInfo(A, Name, /* _BaseInput = */ Name)}; 5012 } 5013 return {InputInfo(A, &Input, /* _BaseInput = */ "")}; 5014 } 5015 5016 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 5017 const ToolChain *TC; 5018 StringRef ArchName = BAA->getArchName(); 5019 5020 if (!ArchName.empty()) 5021 TC = &getToolChain(C.getArgs(), 5022 computeTargetTriple(*this, TargetTriple, 5023 C.getArgs(), ArchName)); 5024 else 5025 TC = &C.getDefaultToolChain(); 5026 5027 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 5028 MultipleArchs, LinkingOutput, CachedResults, 5029 TargetDeviceOffloadKind); 5030 } 5031 5032 5033 ActionList Inputs = A->getInputs(); 5034 5035 const JobAction *JA = cast<JobAction>(A); 5036 ActionList CollapsedOffloadActions; 5037 5038 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), 5039 embedBitcodeInObject() && !isUsingLTO()); 5040 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions); 5041 5042 if (!T) 5043 return {InputInfo()}; 5044 5045 if (BuildingForOffloadDevice && 5046 A->getOffloadingDeviceKind() == Action::OFK_OpenMP) { 5047 if (TC->getTriple().isAMDGCN()) { 5048 // AMDGCN treats backend and assemble actions as no-op because 5049 // linker does not support object files. 5050 if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) { 5051 return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch, 5052 AtTopLevel, MultipleArchs, LinkingOutput, 5053 CachedResults, TargetDeviceOffloadKind); 5054 } 5055 5056 if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) { 5057 return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch, 5058 AtTopLevel, MultipleArchs, LinkingOutput, 5059 CachedResults, TargetDeviceOffloadKind); 5060 } 5061 } 5062 } 5063 5064 // If we've collapsed action list that contained OffloadAction we 5065 // need to build jobs for host/device-side inputs it may have held. 5066 for (const auto *OA : CollapsedOffloadActions) 5067 cast<OffloadAction>(OA)->doOnEachDependence( 5068 /*IsHostDependence=*/BuildingForOffloadDevice, 5069 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) { 5070 OffloadDependencesInputInfo.append(BuildJobsForAction( 5071 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false, 5072 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults, 5073 DepA->getOffloadingDeviceKind())); 5074 }); 5075 5076 // Only use pipes when there is exactly one input. 5077 InputInfoList InputInfos; 5078 for (const Action *Input : Inputs) { 5079 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 5080 // shouldn't get temporary output names. 5081 // FIXME: Clean this up. 5082 bool SubJobAtTopLevel = 5083 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 5084 InputInfos.append(BuildJobsForAction( 5085 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput, 5086 CachedResults, A->getOffloadingDeviceKind())); 5087 } 5088 5089 // Always use the first file input as the base input. 5090 const char *BaseInput = InputInfos[0].getBaseInput(); 5091 for (auto &Info : InputInfos) { 5092 if (Info.isFilename()) { 5093 BaseInput = Info.getBaseInput(); 5094 break; 5095 } 5096 } 5097 5098 // ... except dsymutil actions, which use their actual input as the base 5099 // input. 5100 if (JA->getType() == types::TY_dSYM) 5101 BaseInput = InputInfos[0].getFilename(); 5102 5103 // ... and in header module compilations, which use the module name. 5104 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA)) 5105 BaseInput = ModuleJA->getModuleName(); 5106 5107 // Append outputs of offload device jobs to the input list 5108 if (!OffloadDependencesInputInfo.empty()) 5109 InputInfos.append(OffloadDependencesInputInfo.begin(), 5110 OffloadDependencesInputInfo.end()); 5111 5112 // Set the effective triple of the toolchain for the duration of this job. 5113 llvm::Triple EffectiveTriple; 5114 const ToolChain &ToolTC = T->getToolChain(); 5115 const ArgList &Args = 5116 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind()); 5117 if (InputInfos.size() != 1) { 5118 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args)); 5119 } else { 5120 // Pass along the input type if it can be unambiguously determined. 5121 EffectiveTriple = llvm::Triple( 5122 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType())); 5123 } 5124 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple); 5125 5126 // Determine the place to write output to, if any. 5127 InputInfo Result; 5128 InputInfoList UnbundlingResults; 5129 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) { 5130 // If we have an unbundling job, we need to create results for all the 5131 // outputs. We also update the results cache so that other actions using 5132 // this unbundling action can get the right results. 5133 for (auto &UI : UA->getDependentActionsInfo()) { 5134 assert(UI.DependentOffloadKind != Action::OFK_None && 5135 "Unbundling with no offloading??"); 5136 5137 // Unbundling actions are never at the top level. When we generate the 5138 // offloading prefix, we also do that for the host file because the 5139 // unbundling action does not change the type of the output which can 5140 // cause a overwrite. 5141 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5142 UI.DependentOffloadKind, 5143 UI.DependentToolChain->getTriple().normalize(), 5144 /*CreatePrefixForHost=*/true); 5145 auto CurI = InputInfo( 5146 UA, 5147 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch, 5148 /*AtTopLevel=*/false, 5149 MultipleArchs || 5150 UI.DependentOffloadKind == Action::OFK_HIP, 5151 OffloadingPrefix), 5152 BaseInput); 5153 // Save the unbundling result. 5154 UnbundlingResults.push_back(CurI); 5155 5156 // Get the unique string identifier for this dependence and cache the 5157 // result. 5158 StringRef Arch; 5159 if (TargetDeviceOffloadKind == Action::OFK_HIP) { 5160 if (UI.DependentOffloadKind == Action::OFK_Host) 5161 Arch = StringRef(); 5162 else 5163 Arch = UI.DependentBoundArch; 5164 } else 5165 Arch = BoundArch; 5166 5167 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch, 5168 UI.DependentOffloadKind)}] = { 5169 CurI}; 5170 } 5171 5172 // Now that we have all the results generated, select the one that should be 5173 // returned for the current depending action. 5174 std::pair<const Action *, std::string> ActionTC = { 5175 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)}; 5176 assert(CachedResults.find(ActionTC) != CachedResults.end() && 5177 "Result does not exist??"); 5178 Result = CachedResults[ActionTC].front(); 5179 } else if (JA->getType() == types::TY_Nothing) 5180 Result = {InputInfo(A, BaseInput)}; 5181 else { 5182 // We only have to generate a prefix for the host if this is not a top-level 5183 // action. 5184 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix( 5185 A->getOffloadingDeviceKind(), TC->getTriple().normalize(), 5186 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() && 5187 !AtTopLevel); 5188 if (isa<OffloadWrapperJobAction>(JA)) { 5189 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 5190 BaseInput = FinalOutput->getValue(); 5191 else 5192 BaseInput = getDefaultImageName(); 5193 BaseInput = 5194 C.getArgs().MakeArgString(std::string(BaseInput) + "-wrapper"); 5195 } 5196 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 5197 AtTopLevel, MultipleArchs, 5198 OffloadingPrefix), 5199 BaseInput); 5200 } 5201 5202 if (CCCPrintBindings && !CCGenDiagnostics) { 5203 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 5204 << " - \"" << T->getName() << "\", inputs: ["; 5205 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 5206 llvm::errs() << InputInfos[i].getAsString(); 5207 if (i + 1 != e) 5208 llvm::errs() << ", "; 5209 } 5210 if (UnbundlingResults.empty()) 5211 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 5212 else { 5213 llvm::errs() << "], outputs: ["; 5214 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) { 5215 llvm::errs() << UnbundlingResults[i].getAsString(); 5216 if (i + 1 != e) 5217 llvm::errs() << ", "; 5218 } 5219 llvm::errs() << "] \n"; 5220 } 5221 } else { 5222 if (UnbundlingResults.empty()) 5223 T->ConstructJob( 5224 C, *JA, Result, InputInfos, 5225 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5226 LinkingOutput); 5227 else 5228 T->ConstructJobMultipleOutputs( 5229 C, *JA, UnbundlingResults, InputInfos, 5230 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()), 5231 LinkingOutput); 5232 } 5233 return {Result}; 5234 } 5235 5236 const char *Driver::getDefaultImageName() const { 5237 llvm::Triple Target(llvm::Triple::normalize(TargetTriple)); 5238 return Target.isOSWindows() ? "a.exe" : "a.out"; 5239 } 5240 5241 /// Create output filename based on ArgValue, which could either be a 5242 /// full filename, filename without extension, or a directory. If ArgValue 5243 /// does not provide a filename, then use BaseName, and use the extension 5244 /// suitable for FileType. 5245 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 5246 StringRef BaseName, 5247 types::ID FileType) { 5248 SmallString<128> Filename = ArgValue; 5249 5250 if (ArgValue.empty()) { 5251 // If the argument is empty, output to BaseName in the current dir. 5252 Filename = BaseName; 5253 } else if (llvm::sys::path::is_separator(Filename.back())) { 5254 // If the argument is a directory, output to BaseName in that dir. 5255 llvm::sys::path::append(Filename, BaseName); 5256 } 5257 5258 if (!llvm::sys::path::has_extension(ArgValue)) { 5259 // If the argument didn't provide an extension, then set it. 5260 const char *Extension = types::getTypeTempSuffix(FileType, true); 5261 5262 if (FileType == types::TY_Image && 5263 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 5264 // The output file is a dll. 5265 Extension = "dll"; 5266 } 5267 5268 llvm::sys::path::replace_extension(Filename, Extension); 5269 } 5270 5271 return Args.MakeArgString(Filename.c_str()); 5272 } 5273 5274 static bool HasPreprocessOutput(const Action &JA) { 5275 if (isa<PreprocessJobAction>(JA)) 5276 return true; 5277 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0])) 5278 return true; 5279 if (isa<OffloadBundlingJobAction>(JA) && 5280 HasPreprocessOutput(*(JA.getInputs()[0]))) 5281 return true; 5282 return false; 5283 } 5284 5285 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 5286 const char *BaseInput, 5287 StringRef OrigBoundArch, bool AtTopLevel, 5288 bool MultipleArchs, 5289 StringRef OffloadingPrefix) const { 5290 std::string BoundArch = OrigBoundArch.str(); 5291 if (is_style_windows(llvm::sys::path::Style::native)) { 5292 // BoundArch may contains ':', which is invalid in file names on Windows, 5293 // therefore replace it with '%'. 5294 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@'); 5295 } 5296 5297 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 5298 // Output to a user requested destination? 5299 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 5300 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 5301 return C.addResultFile(FinalOutput->getValue(), &JA); 5302 } 5303 5304 // For /P, preprocess to file named after BaseInput. 5305 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 5306 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 5307 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5308 StringRef NameArg; 5309 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 5310 NameArg = A->getValue(); 5311 return C.addResultFile( 5312 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 5313 &JA); 5314 } 5315 5316 // Default to writing to stdout? 5317 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) { 5318 return "-"; 5319 } 5320 5321 if (JA.getType() == types::TY_ModuleFile && 5322 C.getArgs().getLastArg(options::OPT_module_file_info)) { 5323 return "-"; 5324 } 5325 5326 // Is this the assembly listing for /FA? 5327 if (JA.getType() == types::TY_PP_Asm && 5328 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 5329 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 5330 // Use /Fa and the input filename to determine the asm file name. 5331 StringRef BaseName = llvm::sys::path::filename(BaseInput); 5332 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 5333 return C.addResultFile( 5334 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 5335 &JA); 5336 } 5337 5338 // Output to a temporary file? 5339 if ((!AtTopLevel && !isSaveTempsEnabled() && 5340 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 5341 CCGenDiagnostics) { 5342 StringRef Name = llvm::sys::path::filename(BaseInput); 5343 std::pair<StringRef, StringRef> Split = Name.split('.'); 5344 SmallString<128> TmpName; 5345 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 5346 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir); 5347 if (CCGenDiagnostics && A) { 5348 SmallString<128> CrashDirectory(A->getValue()); 5349 if (!getVFS().exists(CrashDirectory)) 5350 llvm::sys::fs::create_directories(CrashDirectory); 5351 llvm::sys::path::append(CrashDirectory, Split.first); 5352 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%"; 5353 std::error_code EC = llvm::sys::fs::createUniqueFile( 5354 CrashDirectory + Middle + Suffix, TmpName); 5355 if (EC) { 5356 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5357 return ""; 5358 } 5359 } else { 5360 if (MultipleArchs && !BoundArch.empty()) { 5361 TmpName = GetTemporaryDirectory(Split.first); 5362 llvm::sys::path::append(TmpName, 5363 Split.first + "-" + BoundArch + "." + Suffix); 5364 } else { 5365 TmpName = GetTemporaryPath(Split.first, Suffix); 5366 } 5367 } 5368 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5369 } 5370 5371 SmallString<128> BasePath(BaseInput); 5372 SmallString<128> ExternalPath(""); 5373 StringRef BaseName; 5374 5375 // Dsymutil actions should use the full path. 5376 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) { 5377 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue(); 5378 // We use posix style here because the tests (specifically 5379 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable 5380 // even on Windows and if we don't then the similar test covering this 5381 // fails. 5382 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix, 5383 llvm::sys::path::filename(BasePath)); 5384 BaseName = ExternalPath; 5385 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 5386 BaseName = BasePath; 5387 else 5388 BaseName = llvm::sys::path::filename(BasePath); 5389 5390 // Determine what the derived output name should be. 5391 const char *NamedOutput; 5392 5393 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) && 5394 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 5395 // The /Fo or /o flag decides the object filename. 5396 StringRef Val = 5397 C.getArgs() 5398 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 5399 ->getValue(); 5400 NamedOutput = 5401 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 5402 } else if (JA.getType() == types::TY_Image && 5403 C.getArgs().hasArg(options::OPT__SLASH_Fe, 5404 options::OPT__SLASH_o)) { 5405 // The /Fe or /o flag names the linked file. 5406 StringRef Val = 5407 C.getArgs() 5408 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 5409 ->getValue(); 5410 NamedOutput = 5411 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 5412 } else if (JA.getType() == types::TY_Image) { 5413 if (IsCLMode()) { 5414 // clang-cl uses BaseName for the executable name. 5415 NamedOutput = 5416 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 5417 } else { 5418 SmallString<128> Output(getDefaultImageName()); 5419 // HIP image for device compilation with -fno-gpu-rdc is per compilation 5420 // unit. 5421 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5422 !C.getArgs().hasFlag(options::OPT_fgpu_rdc, 5423 options::OPT_fno_gpu_rdc, false); 5424 if (IsHIPNoRDC) { 5425 Output = BaseName; 5426 llvm::sys::path::replace_extension(Output, ""); 5427 } 5428 Output += OffloadingPrefix; 5429 if (MultipleArchs && !BoundArch.empty()) { 5430 Output += "-"; 5431 Output.append(BoundArch); 5432 } 5433 if (IsHIPNoRDC) 5434 Output += ".out"; 5435 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 5436 } 5437 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 5438 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName)); 5439 } else { 5440 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 5441 assert(Suffix && "All types used for output should have a suffix."); 5442 5443 std::string::size_type End = std::string::npos; 5444 if (!types::appendSuffixForType(JA.getType())) 5445 End = BaseName.rfind('.'); 5446 SmallString<128> Suffixed(BaseName.substr(0, End)); 5447 Suffixed += OffloadingPrefix; 5448 if (MultipleArchs && !BoundArch.empty()) { 5449 Suffixed += "-"; 5450 Suffixed.append(BoundArch); 5451 } 5452 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 5453 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 5454 // optimized bitcode output. 5455 auto IsHIPRDCInCompilePhase = [](const JobAction &JA, 5456 const llvm::opt::DerivedArgList &Args) { 5457 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a 5458 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile 5459 // phase.) 5460 return isa<CompileJobAction>(JA) && 5461 JA.getOffloadingDeviceKind() == Action::OFK_HIP && 5462 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, 5463 false); 5464 }; 5465 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC && 5466 (C.getArgs().hasArg(options::OPT_emit_llvm) || 5467 IsHIPRDCInCompilePhase(JA, C.getArgs()))) 5468 Suffixed += ".tmp"; 5469 Suffixed += '.'; 5470 Suffixed += Suffix; 5471 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 5472 } 5473 5474 // Prepend object file path if -save-temps=obj 5475 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 5476 JA.getType() != types::TY_PCH) { 5477 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 5478 SmallString<128> TempPath(FinalOutput->getValue()); 5479 llvm::sys::path::remove_filename(TempPath); 5480 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 5481 llvm::sys::path::append(TempPath, OutputFileName); 5482 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 5483 } 5484 5485 // If we're saving temps and the temp file conflicts with the input file, 5486 // then avoid overwriting input file. 5487 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 5488 bool SameFile = false; 5489 SmallString<256> Result; 5490 llvm::sys::fs::current_path(Result); 5491 llvm::sys::path::append(Result, BaseName); 5492 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 5493 // Must share the same path to conflict. 5494 if (SameFile) { 5495 StringRef Name = llvm::sys::path::filename(BaseInput); 5496 std::pair<StringRef, StringRef> Split = Name.split('.'); 5497 std::string TmpName = GetTemporaryPath( 5498 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 5499 return C.addTempFile(C.getArgs().MakeArgString(TmpName)); 5500 } 5501 } 5502 5503 // As an annoying special case, PCH generation doesn't strip the pathname. 5504 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 5505 llvm::sys::path::remove_filename(BasePath); 5506 if (BasePath.empty()) 5507 BasePath = NamedOutput; 5508 else 5509 llvm::sys::path::append(BasePath, NamedOutput); 5510 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 5511 } else { 5512 return C.addResultFile(NamedOutput, &JA); 5513 } 5514 } 5515 5516 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const { 5517 // Search for Name in a list of paths. 5518 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P) 5519 -> llvm::Optional<std::string> { 5520 // Respect a limited subset of the '-Bprefix' functionality in GCC by 5521 // attempting to use this prefix when looking for file paths. 5522 for (const auto &Dir : P) { 5523 if (Dir.empty()) 5524 continue; 5525 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 5526 llvm::sys::path::append(P, Name); 5527 if (llvm::sys::fs::exists(Twine(P))) 5528 return std::string(P); 5529 } 5530 return None; 5531 }; 5532 5533 if (auto P = SearchPaths(PrefixDirs)) 5534 return *P; 5535 5536 SmallString<128> R(ResourceDir); 5537 llvm::sys::path::append(R, Name); 5538 if (llvm::sys::fs::exists(Twine(R))) 5539 return std::string(R.str()); 5540 5541 SmallString<128> P(TC.getCompilerRTPath()); 5542 llvm::sys::path::append(P, Name); 5543 if (llvm::sys::fs::exists(Twine(P))) 5544 return std::string(P.str()); 5545 5546 SmallString<128> D(Dir); 5547 llvm::sys::path::append(D, "..", Name); 5548 if (llvm::sys::fs::exists(Twine(D))) 5549 return std::string(D.str()); 5550 5551 if (auto P = SearchPaths(TC.getLibraryPaths())) 5552 return *P; 5553 5554 if (auto P = SearchPaths(TC.getFilePaths())) 5555 return *P; 5556 5557 return std::string(Name); 5558 } 5559 5560 void Driver::generatePrefixedToolNames( 5561 StringRef Tool, const ToolChain &TC, 5562 SmallVectorImpl<std::string> &Names) const { 5563 // FIXME: Needs a better variable than TargetTriple 5564 Names.emplace_back((TargetTriple + "-" + Tool).str()); 5565 Names.emplace_back(Tool); 5566 } 5567 5568 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) { 5569 llvm::sys::path::append(Dir, Name); 5570 if (llvm::sys::fs::can_execute(Twine(Dir))) 5571 return true; 5572 llvm::sys::path::remove_filename(Dir); 5573 return false; 5574 } 5575 5576 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const { 5577 SmallVector<std::string, 2> TargetSpecificExecutables; 5578 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 5579 5580 // Respect a limited subset of the '-Bprefix' functionality in GCC by 5581 // attempting to use this prefix when looking for program paths. 5582 for (const auto &PrefixDir : PrefixDirs) { 5583 if (llvm::sys::fs::is_directory(PrefixDir)) { 5584 SmallString<128> P(PrefixDir); 5585 if (ScanDirForExecutable(P, Name)) 5586 return std::string(P.str()); 5587 } else { 5588 SmallString<128> P((PrefixDir + Name).str()); 5589 if (llvm::sys::fs::can_execute(Twine(P))) 5590 return std::string(P.str()); 5591 } 5592 } 5593 5594 const ToolChain::path_list &List = TC.getProgramPaths(); 5595 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) { 5596 // For each possible name of the tool look for it in 5597 // program paths first, then the path. 5598 // Higher priority names will be first, meaning that 5599 // a higher priority name in the path will be found 5600 // instead of a lower priority name in the program path. 5601 // E.g. <triple>-gcc on the path will be found instead 5602 // of gcc in the program path 5603 for (const auto &Path : List) { 5604 SmallString<128> P(Path); 5605 if (ScanDirForExecutable(P, TargetSpecificExecutable)) 5606 return std::string(P.str()); 5607 } 5608 5609 // Fall back to the path 5610 if (llvm::ErrorOr<std::string> P = 5611 llvm::sys::findProgramByName(TargetSpecificExecutable)) 5612 return *P; 5613 } 5614 5615 return std::string(Name); 5616 } 5617 5618 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const { 5619 SmallString<128> Path; 5620 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 5621 if (EC) { 5622 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5623 return ""; 5624 } 5625 5626 return std::string(Path.str()); 5627 } 5628 5629 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const { 5630 SmallString<128> Path; 5631 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path); 5632 if (EC) { 5633 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 5634 return ""; 5635 } 5636 5637 return std::string(Path.str()); 5638 } 5639 5640 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 5641 SmallString<128> Output; 5642 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 5643 // FIXME: If anybody needs it, implement this obscure rule: 5644 // "If you specify a directory without a file name, the default file name 5645 // is VCx0.pch., where x is the major version of Visual C++ in use." 5646 Output = FpArg->getValue(); 5647 5648 // "If you do not specify an extension as part of the path name, an 5649 // extension of .pch is assumed. " 5650 if (!llvm::sys::path::has_extension(Output)) 5651 Output += ".pch"; 5652 } else { 5653 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) 5654 Output = YcArg->getValue(); 5655 if (Output.empty()) 5656 Output = BaseName; 5657 llvm::sys::path::replace_extension(Output, ".pch"); 5658 } 5659 return std::string(Output.str()); 5660 } 5661 5662 const ToolChain &Driver::getToolChain(const ArgList &Args, 5663 const llvm::Triple &Target) const { 5664 5665 auto &TC = ToolChains[Target.str()]; 5666 if (!TC) { 5667 switch (Target.getOS()) { 5668 case llvm::Triple::AIX: 5669 TC = std::make_unique<toolchains::AIX>(*this, Target, Args); 5670 break; 5671 case llvm::Triple::Haiku: 5672 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args); 5673 break; 5674 case llvm::Triple::Ananas: 5675 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args); 5676 break; 5677 case llvm::Triple::CloudABI: 5678 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args); 5679 break; 5680 case llvm::Triple::Darwin: 5681 case llvm::Triple::MacOSX: 5682 case llvm::Triple::IOS: 5683 case llvm::Triple::TvOS: 5684 case llvm::Triple::WatchOS: 5685 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args); 5686 break; 5687 case llvm::Triple::DragonFly: 5688 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args); 5689 break; 5690 case llvm::Triple::OpenBSD: 5691 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args); 5692 break; 5693 case llvm::Triple::NetBSD: 5694 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args); 5695 break; 5696 case llvm::Triple::FreeBSD: 5697 if (Target.isPPC()) 5698 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target, 5699 Args); 5700 else 5701 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args); 5702 break; 5703 case llvm::Triple::Minix: 5704 TC = std::make_unique<toolchains::Minix>(*this, Target, Args); 5705 break; 5706 case llvm::Triple::Linux: 5707 case llvm::Triple::ELFIAMCU: 5708 if (Target.getArch() == llvm::Triple::hexagon) 5709 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 5710 Args); 5711 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 5712 !Target.hasEnvironment()) 5713 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target, 5714 Args); 5715 else if (Target.isPPC()) 5716 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target, 5717 Args); 5718 else if (Target.getArch() == llvm::Triple::ve) 5719 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 5720 5721 else 5722 TC = std::make_unique<toolchains::Linux>(*this, Target, Args); 5723 break; 5724 case llvm::Triple::NaCl: 5725 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args); 5726 break; 5727 case llvm::Triple::Fuchsia: 5728 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args); 5729 break; 5730 case llvm::Triple::Solaris: 5731 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args); 5732 break; 5733 case llvm::Triple::AMDHSA: 5734 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args); 5735 break; 5736 case llvm::Triple::AMDPAL: 5737 case llvm::Triple::Mesa3D: 5738 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args); 5739 break; 5740 case llvm::Triple::Win32: 5741 switch (Target.getEnvironment()) { 5742 default: 5743 if (Target.isOSBinFormatELF()) 5744 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 5745 else if (Target.isOSBinFormatMachO()) 5746 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 5747 else 5748 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 5749 break; 5750 case llvm::Triple::GNU: 5751 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args); 5752 break; 5753 case llvm::Triple::Itanium: 5754 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target, 5755 Args); 5756 break; 5757 case llvm::Triple::MSVC: 5758 case llvm::Triple::UnknownEnvironment: 5759 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ) 5760 .startswith_insensitive("bfd")) 5761 TC = std::make_unique<toolchains::CrossWindowsToolChain>( 5762 *this, Target, Args); 5763 else 5764 TC = 5765 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args); 5766 break; 5767 } 5768 break; 5769 case llvm::Triple::PS4: 5770 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args); 5771 break; 5772 case llvm::Triple::PS5: 5773 TC = std::make_unique<toolchains::PS5CPU>(*this, Target, Args); 5774 break; 5775 case llvm::Triple::Contiki: 5776 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args); 5777 break; 5778 case llvm::Triple::Hurd: 5779 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args); 5780 break; 5781 case llvm::Triple::ZOS: 5782 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args); 5783 break; 5784 case llvm::Triple::ShaderModel: 5785 TC = std::make_unique<toolchains::HLSLToolChain>(*this, Target, Args); 5786 break; 5787 default: 5788 // Of these targets, Hexagon is the only one that might have 5789 // an OS of Linux, in which case it got handled above already. 5790 switch (Target.getArch()) { 5791 case llvm::Triple::tce: 5792 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args); 5793 break; 5794 case llvm::Triple::tcele: 5795 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args); 5796 break; 5797 case llvm::Triple::hexagon: 5798 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target, 5799 Args); 5800 break; 5801 case llvm::Triple::lanai: 5802 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args); 5803 break; 5804 case llvm::Triple::xcore: 5805 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args); 5806 break; 5807 case llvm::Triple::wasm32: 5808 case llvm::Triple::wasm64: 5809 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args); 5810 break; 5811 case llvm::Triple::avr: 5812 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args); 5813 break; 5814 case llvm::Triple::msp430: 5815 TC = 5816 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args); 5817 break; 5818 case llvm::Triple::riscv32: 5819 case llvm::Triple::riscv64: 5820 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args)) 5821 TC = 5822 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args); 5823 else 5824 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 5825 break; 5826 case llvm::Triple::ve: 5827 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args); 5828 break; 5829 case llvm::Triple::spirv32: 5830 case llvm::Triple::spirv64: 5831 TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args); 5832 break; 5833 case llvm::Triple::csky: 5834 TC = std::make_unique<toolchains::CSKYToolChain>(*this, Target, Args); 5835 break; 5836 default: 5837 if (Target.getVendor() == llvm::Triple::Myriad) 5838 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target, 5839 Args); 5840 else if (toolchains::BareMetal::handlesTarget(Target)) 5841 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args); 5842 else if (Target.isOSBinFormatELF()) 5843 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args); 5844 else if (Target.isOSBinFormatMachO()) 5845 TC = std::make_unique<toolchains::MachO>(*this, Target, Args); 5846 else 5847 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args); 5848 } 5849 } 5850 } 5851 5852 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA 5853 // compiles always need two toolchains, the CUDA toolchain and the host 5854 // toolchain. So the only valid way to create a CUDA toolchain is via 5855 // CreateOffloadingDeviceToolChains. 5856 5857 return *TC; 5858 } 5859 5860 const ToolChain &Driver::getOffloadingDeviceToolChain( 5861 const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC, 5862 const Action::OffloadKind &TargetDeviceOffloadKind) const { 5863 // Use device / host triples as the key into the ToolChains map because the 5864 // device ToolChain we create depends on both. 5865 auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()]; 5866 if (!TC) { 5867 // Categorized by offload kind > arch rather than OS > arch like 5868 // the normal getToolChain call, as it seems a reasonable way to categorize 5869 // things. 5870 switch (TargetDeviceOffloadKind) { 5871 case Action::OFK_HIP: { 5872 if (Target.getArch() == llvm::Triple::amdgcn && 5873 Target.getVendor() == llvm::Triple::AMD && 5874 Target.getOS() == llvm::Triple::AMDHSA) 5875 TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target, 5876 HostTC, Args); 5877 else if (Target.getArch() == llvm::Triple::spirv64 && 5878 Target.getVendor() == llvm::Triple::UnknownVendor && 5879 Target.getOS() == llvm::Triple::UnknownOS) 5880 TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target, 5881 HostTC, Args); 5882 break; 5883 } 5884 default: 5885 break; 5886 } 5887 } 5888 5889 return *TC; 5890 } 5891 5892 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 5893 // Say "no" if there is not exactly one input of a type clang understands. 5894 if (JA.size() != 1 || 5895 !types::isAcceptedByClang((*JA.input_begin())->getType())) 5896 return false; 5897 5898 // And say "no" if this is not a kind of action clang understands. 5899 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 5900 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA) && 5901 !isa<ExtractAPIJobAction>(JA)) 5902 return false; 5903 5904 return true; 5905 } 5906 5907 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const { 5908 // Say "no" if there is not exactly one input of a type flang understands. 5909 if (JA.size() != 1 || 5910 !types::isFortran((*JA.input_begin())->getType())) 5911 return false; 5912 5913 // And say "no" if this is not a kind of action flang understands. 5914 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 5915 return false; 5916 5917 return true; 5918 } 5919 5920 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const { 5921 // Only emit static library if the flag is set explicitly. 5922 if (Args.hasArg(options::OPT_emit_static_lib)) 5923 return true; 5924 return false; 5925 } 5926 5927 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 5928 /// grouped values as integers. Numbers which are not provided are set to 0. 5929 /// 5930 /// \return True if the entire string was parsed (9.2), or all groups were 5931 /// parsed (10.3.5extrastuff). 5932 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 5933 unsigned &Micro, bool &HadExtra) { 5934 HadExtra = false; 5935 5936 Major = Minor = Micro = 0; 5937 if (Str.empty()) 5938 return false; 5939 5940 if (Str.consumeInteger(10, Major)) 5941 return false; 5942 if (Str.empty()) 5943 return true; 5944 if (Str[0] != '.') 5945 return false; 5946 5947 Str = Str.drop_front(1); 5948 5949 if (Str.consumeInteger(10, Minor)) 5950 return false; 5951 if (Str.empty()) 5952 return true; 5953 if (Str[0] != '.') 5954 return false; 5955 Str = Str.drop_front(1); 5956 5957 if (Str.consumeInteger(10, Micro)) 5958 return false; 5959 if (!Str.empty()) 5960 HadExtra = true; 5961 return true; 5962 } 5963 5964 /// Parse digits from a string \p Str and fulfill \p Digits with 5965 /// the parsed numbers. This method assumes that the max number of 5966 /// digits to look for is equal to Digits.size(). 5967 /// 5968 /// \return True if the entire string was parsed and there are 5969 /// no extra characters remaining at the end. 5970 bool Driver::GetReleaseVersion(StringRef Str, 5971 MutableArrayRef<unsigned> Digits) { 5972 if (Str.empty()) 5973 return false; 5974 5975 unsigned CurDigit = 0; 5976 while (CurDigit < Digits.size()) { 5977 unsigned Digit; 5978 if (Str.consumeInteger(10, Digit)) 5979 return false; 5980 Digits[CurDigit] = Digit; 5981 if (Str.empty()) 5982 return true; 5983 if (Str[0] != '.') 5984 return false; 5985 Str = Str.drop_front(1); 5986 CurDigit++; 5987 } 5988 5989 // More digits than requested, bail out... 5990 return false; 5991 } 5992 5993 std::pair<unsigned, unsigned> 5994 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const { 5995 unsigned IncludedFlagsBitmask = 0; 5996 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 5997 5998 if (IsClCompatMode) { 5999 // Include CL and Core options. 6000 IncludedFlagsBitmask |= options::CLOption; 6001 IncludedFlagsBitmask |= options::CoreOption; 6002 } else { 6003 ExcludedFlagsBitmask |= options::CLOption; 6004 } 6005 if (IsDXCMode()) { 6006 // Include DXC and Core options. 6007 IncludedFlagsBitmask |= options::DXCOption; 6008 IncludedFlagsBitmask |= options::CoreOption; 6009 } else { 6010 ExcludedFlagsBitmask |= options::DXCOption; 6011 } 6012 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 6013 } 6014 6015 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 6016 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 6017 } 6018 6019 bool clang::driver::willEmitRemarks(const ArgList &Args) { 6020 // -fsave-optimization-record enables it. 6021 if (Args.hasFlag(options::OPT_fsave_optimization_record, 6022 options::OPT_fno_save_optimization_record, false)) 6023 return true; 6024 6025 // -fsave-optimization-record=<format> enables it as well. 6026 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ, 6027 options::OPT_fno_save_optimization_record, false)) 6028 return true; 6029 6030 // -foptimization-record-file alone enables it too. 6031 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ, 6032 options::OPT_fno_save_optimization_record, false)) 6033 return true; 6034 6035 // -foptimization-record-passes alone enables it too. 6036 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ, 6037 options::OPT_fno_save_optimization_record, false)) 6038 return true; 6039 return false; 6040 } 6041 6042 llvm::StringRef clang::driver::getDriverMode(StringRef ProgName, 6043 ArrayRef<const char *> Args) { 6044 static const std::string OptName = 6045 getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName(); 6046 llvm::StringRef Opt; 6047 for (StringRef Arg : Args) { 6048 if (!Arg.startswith(OptName)) 6049 continue; 6050 Opt = Arg; 6051 } 6052 if (Opt.empty()) 6053 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode; 6054 return Opt.consume_front(OptName) ? Opt : ""; 6055 } 6056 6057 bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); } 6058