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