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