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