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