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