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