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