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