1 //===- ToolChain.cpp - Collections of tools for one platform --------------===// 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/ToolChain.h" 10 #include "InputInfo.h" 11 #include "ToolChains/Arch/ARM.h" 12 #include "ToolChains/Clang.h" 13 #include "ToolChains/InterfaceStubs.h" 14 #include "ToolChains/Flang.h" 15 #include "clang/Basic/ObjCRuntime.h" 16 #include "clang/Basic/Sanitizers.h" 17 #include "clang/Config/config.h" 18 #include "clang/Driver/Action.h" 19 #include "clang/Driver/Driver.h" 20 #include "clang/Driver/DriverDiagnostic.h" 21 #include "clang/Driver/Job.h" 22 #include "clang/Driver/Options.h" 23 #include "clang/Driver/SanitizerArgs.h" 24 #include "clang/Driver/XRayArgs.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Config/llvm-config.h" 31 #include "llvm/MC/MCTargetOptions.h" 32 #include "llvm/Option/Arg.h" 33 #include "llvm/Option/ArgList.h" 34 #include "llvm/Option/OptTable.h" 35 #include "llvm/Option/Option.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/TargetParser.h" 40 #include "llvm/Support/TargetRegistry.h" 41 #include "llvm/Support/VersionTuple.h" 42 #include "llvm/Support/VirtualFileSystem.h" 43 #include <cassert> 44 #include <cstddef> 45 #include <cstring> 46 #include <string> 47 48 using namespace clang; 49 using namespace driver; 50 using namespace tools; 51 using namespace llvm; 52 using namespace llvm::opt; 53 54 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) { 55 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext, 56 options::OPT_fno_rtti, options::OPT_frtti); 57 } 58 59 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, 60 const llvm::Triple &Triple, 61 const Arg *CachedRTTIArg) { 62 // Explicit rtti/no-rtti args 63 if (CachedRTTIArg) { 64 if (CachedRTTIArg->getOption().matches(options::OPT_frtti)) 65 return ToolChain::RM_Enabled; 66 else 67 return ToolChain::RM_Disabled; 68 } 69 70 // -frtti is default, except for the PS4 CPU. 71 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled; 72 } 73 74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T, 75 const ArgList &Args) 76 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)), 77 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) { 78 if (D.CCCIsCXX()) { 79 if (auto CXXStdlibPath = getCXXStdlibPath()) 80 getFilePaths().push_back(*CXXStdlibPath); 81 } 82 83 if (auto RuntimePath = getRuntimePath()) 84 getLibraryPaths().push_back(*RuntimePath); 85 86 std::string CandidateLibPath = getArchSpecificLibPath(); 87 if (getVFS().exists(CandidateLibPath)) 88 getFilePaths().push_back(CandidateLibPath); 89 } 90 91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) { 92 Triple.setEnvironment(Env); 93 if (EffectiveTriple != llvm::Triple()) 94 EffectiveTriple.setEnvironment(Env); 95 } 96 97 ToolChain::~ToolChain() = default; 98 99 llvm::vfs::FileSystem &ToolChain::getVFS() const { 100 return getDriver().getVFS(); 101 } 102 103 bool ToolChain::useIntegratedAs() const { 104 return Args.hasFlag(options::OPT_fintegrated_as, 105 options::OPT_fno_integrated_as, 106 IsIntegratedAssemblerDefault()); 107 } 108 109 bool ToolChain::useRelaxRelocations() const { 110 return ENABLE_X86_RELAX_RELOCATIONS; 111 } 112 113 bool ToolChain::isNoExecStackDefault() const { 114 return false; 115 } 116 117 const SanitizerArgs& ToolChain::getSanitizerArgs() const { 118 if (!SanitizerArguments.get()) 119 SanitizerArguments.reset(new SanitizerArgs(*this, Args)); 120 return *SanitizerArguments.get(); 121 } 122 123 const XRayArgs& ToolChain::getXRayArgs() const { 124 if (!XRayArguments.get()) 125 XRayArguments.reset(new XRayArgs(*this, Args)); 126 return *XRayArguments.get(); 127 } 128 129 namespace { 130 131 struct DriverSuffix { 132 const char *Suffix; 133 const char *ModeFlag; 134 }; 135 136 } // namespace 137 138 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { 139 // A list of known driver suffixes. Suffixes are compared against the 140 // program name in order. If there is a match, the frontend type is updated as 141 // necessary by applying the ModeFlag. 142 static const DriverSuffix DriverSuffixes[] = { 143 {"clang", nullptr}, 144 {"clang++", "--driver-mode=g++"}, 145 {"clang-c++", "--driver-mode=g++"}, 146 {"clang-cc", nullptr}, 147 {"clang-cpp", "--driver-mode=cpp"}, 148 {"clang-g++", "--driver-mode=g++"}, 149 {"clang-gcc", nullptr}, 150 {"clang-cl", "--driver-mode=cl"}, 151 {"cc", nullptr}, 152 {"cpp", "--driver-mode=cpp"}, 153 {"cl", "--driver-mode=cl"}, 154 {"++", "--driver-mode=g++"}, 155 {"flang", "--driver-mode=flang"}, 156 }; 157 158 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) { 159 StringRef Suffix(DriverSuffixes[i].Suffix); 160 if (ProgName.endswith(Suffix)) { 161 Pos = ProgName.size() - Suffix.size(); 162 return &DriverSuffixes[i]; 163 } 164 } 165 return nullptr; 166 } 167 168 /// Normalize the program name from argv[0] by stripping the file extension if 169 /// present and lower-casing the string on Windows. 170 static std::string normalizeProgramName(llvm::StringRef Argv0) { 171 std::string ProgName = std::string(llvm::sys::path::stem(Argv0)); 172 #ifdef _WIN32 173 // Transform to lowercase for case insensitive file systems. 174 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower); 175 #endif 176 return ProgName; 177 } 178 179 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { 180 // Try to infer frontend type and default target from the program name by 181 // comparing it against DriverSuffixes in order. 182 183 // If there is a match, the function tries to identify a target as prefix. 184 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target 185 // prefix "x86_64-linux". If such a target prefix is found, it may be 186 // added via -target as implicit first argument. 187 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); 188 189 if (!DS) { 190 // Try again after stripping any trailing version number: 191 // clang++3.5 -> clang++ 192 ProgName = ProgName.rtrim("0123456789."); 193 DS = FindDriverSuffix(ProgName, Pos); 194 } 195 196 if (!DS) { 197 // Try again after stripping trailing -component. 198 // clang++-tot -> clang++ 199 ProgName = ProgName.slice(0, ProgName.rfind('-')); 200 DS = FindDriverSuffix(ProgName, Pos); 201 } 202 return DS; 203 } 204 205 ParsedClangName 206 ToolChain::getTargetAndModeFromProgramName(StringRef PN) { 207 std::string ProgName = normalizeProgramName(PN); 208 size_t SuffixPos; 209 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos); 210 if (!DS) 211 return {}; 212 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix); 213 214 size_t LastComponent = ProgName.rfind('-', SuffixPos); 215 if (LastComponent == std::string::npos) 216 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag); 217 std::string ModeSuffix = ProgName.substr(LastComponent + 1, 218 SuffixEnd - LastComponent - 1); 219 220 // Infer target from the prefix. 221 StringRef Prefix(ProgName); 222 Prefix = Prefix.slice(0, LastComponent); 223 std::string IgnoredError; 224 bool IsRegistered = 225 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError); 226 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag, 227 IsRegistered}; 228 } 229 230 StringRef ToolChain::getDefaultUniversalArchName() const { 231 // In universal driver terms, the arch name accepted by -arch isn't exactly 232 // the same as the ones that appear in the triple. Roughly speaking, this is 233 // an inverse of the darwin::getArchTypeForDarwinArchName() function. 234 switch (Triple.getArch()) { 235 case llvm::Triple::aarch64: { 236 if (getTriple().isArm64e()) 237 return "arm64e"; 238 return "arm64"; 239 } 240 case llvm::Triple::aarch64_32: 241 return "arm64_32"; 242 case llvm::Triple::ppc: 243 return "ppc"; 244 case llvm::Triple::ppcle: 245 return "ppcle"; 246 case llvm::Triple::ppc64: 247 return "ppc64"; 248 case llvm::Triple::ppc64le: 249 return "ppc64le"; 250 default: 251 return Triple.getArchName(); 252 } 253 } 254 255 std::string ToolChain::getInputFilename(const InputInfo &Input) const { 256 return Input.getFilename(); 257 } 258 259 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const { 260 return false; 261 } 262 263 Tool *ToolChain::getClang() const { 264 if (!Clang) 265 Clang.reset(new tools::Clang(*this)); 266 return Clang.get(); 267 } 268 269 Tool *ToolChain::getFlang() const { 270 if (!Flang) 271 Flang.reset(new tools::Flang(*this)); 272 return Flang.get(); 273 } 274 275 Tool *ToolChain::buildAssembler() const { 276 return new tools::ClangAs(*this); 277 } 278 279 Tool *ToolChain::buildLinker() const { 280 llvm_unreachable("Linking is not supported by this toolchain"); 281 } 282 283 Tool *ToolChain::buildStaticLibTool() const { 284 llvm_unreachable("Creating static lib is not supported by this toolchain"); 285 } 286 287 Tool *ToolChain::getAssemble() const { 288 if (!Assemble) 289 Assemble.reset(buildAssembler()); 290 return Assemble.get(); 291 } 292 293 Tool *ToolChain::getClangAs() const { 294 if (!Assemble) 295 Assemble.reset(new tools::ClangAs(*this)); 296 return Assemble.get(); 297 } 298 299 Tool *ToolChain::getLink() const { 300 if (!Link) 301 Link.reset(buildLinker()); 302 return Link.get(); 303 } 304 305 Tool *ToolChain::getStaticLibTool() const { 306 if (!StaticLibTool) 307 StaticLibTool.reset(buildStaticLibTool()); 308 return StaticLibTool.get(); 309 } 310 311 Tool *ToolChain::getIfsMerge() const { 312 if (!IfsMerge) 313 IfsMerge.reset(new tools::ifstool::Merger(*this)); 314 return IfsMerge.get(); 315 } 316 317 Tool *ToolChain::getOffloadBundler() const { 318 if (!OffloadBundler) 319 OffloadBundler.reset(new tools::OffloadBundler(*this)); 320 return OffloadBundler.get(); 321 } 322 323 Tool *ToolChain::getOffloadWrapper() const { 324 if (!OffloadWrapper) 325 OffloadWrapper.reset(new tools::OffloadWrapper(*this)); 326 return OffloadWrapper.get(); 327 } 328 329 Tool *ToolChain::getTool(Action::ActionClass AC) const { 330 switch (AC) { 331 case Action::AssembleJobClass: 332 return getAssemble(); 333 334 case Action::IfsMergeJobClass: 335 return getIfsMerge(); 336 337 case Action::LinkJobClass: 338 return getLink(); 339 340 case Action::StaticLibJobClass: 341 return getStaticLibTool(); 342 343 case Action::InputClass: 344 case Action::BindArchClass: 345 case Action::OffloadClass: 346 case Action::LipoJobClass: 347 case Action::DsymutilJobClass: 348 case Action::VerifyDebugInfoJobClass: 349 llvm_unreachable("Invalid tool kind."); 350 351 case Action::CompileJobClass: 352 case Action::PrecompileJobClass: 353 case Action::HeaderModulePrecompileJobClass: 354 case Action::PreprocessJobClass: 355 case Action::AnalyzeJobClass: 356 case Action::MigrateJobClass: 357 case Action::VerifyPCHJobClass: 358 case Action::BackendJobClass: 359 return getClang(); 360 361 case Action::OffloadBundlingJobClass: 362 case Action::OffloadUnbundlingJobClass: 363 return getOffloadBundler(); 364 365 case Action::OffloadWrapperJobClass: 366 return getOffloadWrapper(); 367 } 368 369 llvm_unreachable("Invalid tool kind."); 370 } 371 372 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, 373 const ArgList &Args) { 374 const llvm::Triple &Triple = TC.getTriple(); 375 bool IsWindows = Triple.isOSWindows(); 376 377 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) 378 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) 379 ? "armhf" 380 : "arm"; 381 382 // For historic reasons, Android library is using i686 instead of i386. 383 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) 384 return "i686"; 385 386 return llvm::Triple::getArchTypeName(TC.getArch()); 387 } 388 389 StringRef ToolChain::getOSLibName() const { 390 switch (Triple.getOS()) { 391 case llvm::Triple::FreeBSD: 392 return "freebsd"; 393 case llvm::Triple::NetBSD: 394 return "netbsd"; 395 case llvm::Triple::OpenBSD: 396 return "openbsd"; 397 case llvm::Triple::Solaris: 398 return "sunos"; 399 case llvm::Triple::AIX: 400 return "aix"; 401 default: 402 return getOS(); 403 } 404 } 405 406 std::string ToolChain::getCompilerRTPath() const { 407 SmallString<128> Path(getDriver().ResourceDir); 408 if (Triple.isOSUnknown()) { 409 llvm::sys::path::append(Path, "lib"); 410 } else { 411 llvm::sys::path::append(Path, "lib", getOSLibName()); 412 } 413 return std::string(Path.str()); 414 } 415 416 std::string ToolChain::getCompilerRTBasename(const ArgList &Args, 417 StringRef Component, 418 FileType Type) const { 419 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type); 420 return llvm::sys::path::filename(CRTAbsolutePath).str(); 421 } 422 423 std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args, 424 StringRef Component, 425 FileType Type, 426 bool AddArch) const { 427 const llvm::Triple &TT = getTriple(); 428 bool IsITANMSVCWindows = 429 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); 430 431 const char *Prefix = 432 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib"; 433 const char *Suffix; 434 switch (Type) { 435 case ToolChain::FT_Object: 436 Suffix = IsITANMSVCWindows ? ".obj" : ".o"; 437 break; 438 case ToolChain::FT_Static: 439 Suffix = IsITANMSVCWindows ? ".lib" : ".a"; 440 break; 441 case ToolChain::FT_Shared: 442 Suffix = TT.isOSWindows() 443 ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib") 444 : ".so"; 445 break; 446 } 447 448 std::string ArchAndEnv; 449 if (AddArch) { 450 StringRef Arch = getArchNameForCompilerRTLib(*this, Args); 451 const char *Env = TT.isAndroid() ? "-android" : ""; 452 ArchAndEnv = ("-" + Arch + Env).str(); 453 } 454 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str(); 455 } 456 457 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, 458 FileType Type) const { 459 // Check for runtime files in the new layout without the architecture first. 460 std::string CRTBasename = 461 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false); 462 for (const auto &LibPath : getLibraryPaths()) { 463 SmallString<128> P(LibPath); 464 llvm::sys::path::append(P, CRTBasename); 465 if (getVFS().exists(P)) 466 return std::string(P.str()); 467 } 468 469 // Fall back to the old expected compiler-rt name if the new one does not 470 // exist. 471 CRTBasename = 472 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true); 473 SmallString<128> Path(getCompilerRTPath()); 474 llvm::sys::path::append(Path, CRTBasename); 475 return std::string(Path.str()); 476 } 477 478 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, 479 StringRef Component, 480 FileType Type) const { 481 return Args.MakeArgString(getCompilerRT(Args, Component, Type)); 482 } 483 484 485 Optional<std::string> ToolChain::getRuntimePath() const { 486 SmallString<128> P; 487 488 // First try the triple passed to driver as --target=<triple>. 489 P.assign(D.ResourceDir); 490 llvm::sys::path::append(P, "lib", D.getTargetTriple()); 491 if (getVFS().exists(P)) 492 return llvm::Optional<std::string>(std::string(P.str())); 493 494 // Second try the normalized triple. 495 P.assign(D.ResourceDir); 496 llvm::sys::path::append(P, "lib", Triple.str()); 497 if (getVFS().exists(P)) 498 return llvm::Optional<std::string>(std::string(P.str())); 499 500 return None; 501 } 502 503 Optional<std::string> ToolChain::getCXXStdlibPath() const { 504 SmallString<128> P; 505 506 // First try the triple passed to driver as --target=<triple>. 507 P.assign(D.Dir); 508 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++"); 509 if (getVFS().exists(P)) 510 return llvm::Optional<std::string>(std::string(P.str())); 511 512 // Second try the normalized triple. 513 P.assign(D.Dir); 514 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++"); 515 if (getVFS().exists(P)) 516 return llvm::Optional<std::string>(std::string(P.str())); 517 518 return None; 519 } 520 521 std::string ToolChain::getArchSpecificLibPath() const { 522 SmallString<128> Path(getDriver().ResourceDir); 523 llvm::sys::path::append(Path, "lib", getOSLibName(), 524 llvm::Triple::getArchTypeName(getArch())); 525 return std::string(Path.str()); 526 } 527 528 bool ToolChain::needsProfileRT(const ArgList &Args) { 529 if (Args.hasArg(options::OPT_noprofilelib)) 530 return false; 531 532 return Args.hasArg(options::OPT_fprofile_generate) || 533 Args.hasArg(options::OPT_fprofile_generate_EQ) || 534 Args.hasArg(options::OPT_fcs_profile_generate) || 535 Args.hasArg(options::OPT_fcs_profile_generate_EQ) || 536 Args.hasArg(options::OPT_fprofile_instr_generate) || 537 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || 538 Args.hasArg(options::OPT_fcreate_profile) || 539 Args.hasArg(options::OPT_forder_file_instrumentation); 540 } 541 542 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) { 543 return Args.hasArg(options::OPT_coverage) || 544 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 545 false); 546 } 547 548 Tool *ToolChain::SelectTool(const JobAction &JA) const { 549 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang(); 550 if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); 551 Action::ActionClass AC = JA.getKind(); 552 if (AC == Action::AssembleJobClass && useIntegratedAs()) 553 return getClangAs(); 554 return getTool(AC); 555 } 556 557 std::string ToolChain::GetFilePath(const char *Name) const { 558 return D.GetFilePath(Name, *this); 559 } 560 561 std::string ToolChain::GetProgramPath(const char *Name) const { 562 return D.GetProgramPath(Name, *this); 563 } 564 565 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD, 566 bool *LinkerIsLLDDarwinNew) const { 567 if (LinkerIsLLD) 568 *LinkerIsLLD = false; 569 if (LinkerIsLLDDarwinNew) 570 *LinkerIsLLDDarwinNew = false; 571 572 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is 573 // considered as the linker flavor, e.g. "bfd", "gold", or "lld". 574 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); 575 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; 576 577 // --ld-path= takes precedence over -fuse-ld= and specifies the executable 578 // name. -B, COMPILER_PATH and PATH and consulted if the value does not 579 // contain a path component separator. 580 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) { 581 std::string Path(A->getValue()); 582 if (!Path.empty()) { 583 if (llvm::sys::path::parent_path(Path).empty()) 584 Path = GetProgramPath(A->getValue()); 585 if (llvm::sys::fs::can_execute(Path)) 586 return std::string(Path); 587 } 588 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 589 return GetProgramPath(getDefaultLinker()); 590 } 591 // If we're passed -fuse-ld= with no argument, or with the argument ld, 592 // then use whatever the default system linker is. 593 if (UseLinker.empty() || UseLinker == "ld") { 594 const char *DefaultLinker = getDefaultLinker(); 595 if (llvm::sys::path::is_absolute(DefaultLinker)) 596 return std::string(DefaultLinker); 597 else 598 return GetProgramPath(DefaultLinker); 599 } 600 601 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking 602 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64." 603 // to a relative path is surprising. This is more complex due to priorities 604 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead. 605 if (UseLinker.find('/') != StringRef::npos) 606 getDriver().Diag(diag::warn_drv_fuse_ld_path); 607 608 if (llvm::sys::path::is_absolute(UseLinker)) { 609 // If we're passed what looks like an absolute path, don't attempt to 610 // second-guess that. 611 if (llvm::sys::fs::can_execute(UseLinker)) 612 return std::string(UseLinker); 613 } else { 614 llvm::SmallString<8> LinkerName; 615 if (Triple.isOSDarwin()) 616 LinkerName.append("ld64."); 617 else 618 LinkerName.append("ld."); 619 LinkerName.append(UseLinker); 620 621 std::string LinkerPath(GetProgramPath(LinkerName.c_str())); 622 if (llvm::sys::fs::can_execute(LinkerPath)) { 623 // FIXME: Remove LinkerIsLLDDarwinNew once there's only one MachO lld. 624 if (LinkerIsLLD) 625 *LinkerIsLLD = UseLinker == "lld" || UseLinker == "lld.darwinold"; 626 if (LinkerIsLLDDarwinNew) 627 *LinkerIsLLDDarwinNew = UseLinker == "lld"; 628 return LinkerPath; 629 } 630 } 631 632 if (A) 633 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 634 635 return GetProgramPath(getDefaultLinker()); 636 } 637 638 std::string ToolChain::GetStaticLibToolPath() const { 639 // TODO: Add support for static lib archiving on Windows 640 return GetProgramPath("llvm-ar"); 641 } 642 643 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { 644 types::ID id = types::lookupTypeForExtension(Ext); 645 646 // Flang always runs the preprocessor and has no notion of "preprocessed 647 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating 648 // them differently. 649 if (D.IsFlangMode() && id == types::TY_PP_Fortran) 650 id = types::TY_Fortran; 651 652 return id; 653 } 654 655 bool ToolChain::HasNativeLLVMSupport() const { 656 return false; 657 } 658 659 bool ToolChain::isCrossCompiling() const { 660 llvm::Triple HostTriple(LLVM_HOST_TRIPLE); 661 switch (HostTriple.getArch()) { 662 // The A32/T32/T16 instruction sets are not separate architectures in this 663 // context. 664 case llvm::Triple::arm: 665 case llvm::Triple::armeb: 666 case llvm::Triple::thumb: 667 case llvm::Triple::thumbeb: 668 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && 669 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; 670 default: 671 return HostTriple.getArch() != getArch(); 672 } 673 } 674 675 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { 676 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, 677 VersionTuple()); 678 } 679 680 llvm::ExceptionHandling 681 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const { 682 return llvm::ExceptionHandling::None; 683 } 684 685 bool ToolChain::isThreadModelSupported(const StringRef Model) const { 686 if (Model == "single") { 687 // FIXME: 'single' is only supported on ARM and WebAssembly so far. 688 return Triple.getArch() == llvm::Triple::arm || 689 Triple.getArch() == llvm::Triple::armeb || 690 Triple.getArch() == llvm::Triple::thumb || 691 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm(); 692 } else if (Model == "posix") 693 return true; 694 695 return false; 696 } 697 698 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 699 types::ID InputType) const { 700 switch (getTriple().getArch()) { 701 default: 702 return getTripleString(); 703 704 case llvm::Triple::x86_64: { 705 llvm::Triple Triple = getTriple(); 706 if (!Triple.isOSBinFormatMachO()) 707 return getTripleString(); 708 709 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { 710 // x86_64h goes in the triple. Other -march options just use the 711 // vanilla triple we already have. 712 StringRef MArch = A->getValue(); 713 if (MArch == "x86_64h") 714 Triple.setArchName(MArch); 715 } 716 return Triple.getTriple(); 717 } 718 case llvm::Triple::aarch64: { 719 llvm::Triple Triple = getTriple(); 720 if (!Triple.isOSBinFormatMachO()) 721 return getTripleString(); 722 723 if (Triple.isArm64e()) 724 return getTripleString(); 725 726 // FIXME: older versions of ld64 expect the "arm64" component in the actual 727 // triple string and query it to determine whether an LTO file can be 728 // handled. Remove this when we don't care any more. 729 Triple.setArchName("arm64"); 730 return Triple.getTriple(); 731 } 732 case llvm::Triple::aarch64_32: 733 return getTripleString(); 734 case llvm::Triple::arm: 735 case llvm::Triple::armeb: 736 case llvm::Triple::thumb: 737 case llvm::Triple::thumbeb: { 738 llvm::Triple Triple = getTriple(); 739 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple); 740 tools::arm::setFloatABIInTriple(getDriver(), Args, Triple); 741 return Triple.getTriple(); 742 } 743 } 744 } 745 746 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 747 types::ID InputType) const { 748 return ComputeLLVMTriple(Args, InputType); 749 } 750 751 std::string ToolChain::computeSysRoot() const { 752 return D.SysRoot; 753 } 754 755 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 756 ArgStringList &CC1Args) const { 757 // Each toolchain should provide the appropriate include flags. 758 } 759 760 void ToolChain::addClangTargetOptions( 761 const ArgList &DriverArgs, ArgStringList &CC1Args, 762 Action::OffloadKind DeviceOffloadKind) const {} 763 764 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} 765 766 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, 767 llvm::opt::ArgStringList &CmdArgs) const { 768 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args)) 769 return; 770 771 CmdArgs.push_back(getCompilerRTArgString(Args, "profile")); 772 } 773 774 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( 775 const ArgList &Args) const { 776 if (runtimeLibType) 777 return *runtimeLibType; 778 779 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); 780 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; 781 782 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! 783 if (LibName == "compiler-rt") 784 runtimeLibType = ToolChain::RLT_CompilerRT; 785 else if (LibName == "libgcc") 786 runtimeLibType = ToolChain::RLT_Libgcc; 787 else if (LibName == "platform") 788 runtimeLibType = GetDefaultRuntimeLibType(); 789 else { 790 if (A) 791 getDriver().Diag(diag::err_drv_invalid_rtlib_name) 792 << A->getAsString(Args); 793 794 runtimeLibType = GetDefaultRuntimeLibType(); 795 } 796 797 return *runtimeLibType; 798 } 799 800 ToolChain::UnwindLibType ToolChain::GetUnwindLibType( 801 const ArgList &Args) const { 802 if (unwindLibType) 803 return *unwindLibType; 804 805 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ); 806 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB; 807 808 if (LibName == "none") 809 unwindLibType = ToolChain::UNW_None; 810 else if (LibName == "platform" || LibName == "") { 811 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args); 812 if (RtLibType == ToolChain::RLT_CompilerRT) { 813 if (getTriple().isAndroid()) 814 unwindLibType = ToolChain::UNW_CompilerRT; 815 else 816 unwindLibType = ToolChain::UNW_None; 817 } else if (RtLibType == ToolChain::RLT_Libgcc) 818 unwindLibType = ToolChain::UNW_Libgcc; 819 } else if (LibName == "libunwind") { 820 if (GetRuntimeLibType(Args) == RLT_Libgcc) 821 getDriver().Diag(diag::err_drv_incompatible_unwindlib); 822 unwindLibType = ToolChain::UNW_CompilerRT; 823 } else if (LibName == "libgcc") 824 unwindLibType = ToolChain::UNW_Libgcc; 825 else { 826 if (A) 827 getDriver().Diag(diag::err_drv_invalid_unwindlib_name) 828 << A->getAsString(Args); 829 830 unwindLibType = GetDefaultUnwindLibType(); 831 } 832 833 return *unwindLibType; 834 } 835 836 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ 837 if (cxxStdlibType) 838 return *cxxStdlibType; 839 840 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 841 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; 842 843 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! 844 if (LibName == "libc++") 845 cxxStdlibType = ToolChain::CST_Libcxx; 846 else if (LibName == "libstdc++") 847 cxxStdlibType = ToolChain::CST_Libstdcxx; 848 else if (LibName == "platform") 849 cxxStdlibType = GetDefaultCXXStdlibType(); 850 else { 851 if (A) 852 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 853 << A->getAsString(Args); 854 855 cxxStdlibType = GetDefaultCXXStdlibType(); 856 } 857 858 return *cxxStdlibType; 859 } 860 861 /// Utility function to add a system include directory to CC1 arguments. 862 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, 863 ArgStringList &CC1Args, 864 const Twine &Path) { 865 CC1Args.push_back("-internal-isystem"); 866 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 867 } 868 869 /// Utility function to add a system include directory with extern "C" 870 /// semantics to CC1 arguments. 871 /// 872 /// Note that this should be used rarely, and only for directories that 873 /// historically and for legacy reasons are treated as having implicit extern 874 /// "C" semantics. These semantics are *ignored* by and large today, but its 875 /// important to preserve the preprocessor changes resulting from the 876 /// classification. 877 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, 878 ArgStringList &CC1Args, 879 const Twine &Path) { 880 CC1Args.push_back("-internal-externc-isystem"); 881 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 882 } 883 884 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, 885 ArgStringList &CC1Args, 886 const Twine &Path) { 887 if (llvm::sys::fs::exists(Path)) 888 addExternCSystemInclude(DriverArgs, CC1Args, Path); 889 } 890 891 /// Utility function to add a list of system include directories to CC1. 892 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, 893 ArgStringList &CC1Args, 894 ArrayRef<StringRef> Paths) { 895 for (const auto &Path : Paths) { 896 CC1Args.push_back("-internal-isystem"); 897 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 898 } 899 } 900 901 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const { 902 std::error_code EC; 903 int MaxVersion = 0; 904 std::string MaxVersionString; 905 SmallString<128> Path(IncludePath); 906 llvm::sys::path::append(Path, "c++"); 907 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE; 908 !EC && LI != LE; LI = LI.increment(EC)) { 909 StringRef VersionText = llvm::sys::path::filename(LI->path()); 910 int Version; 911 if (VersionText[0] == 'v' && 912 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) { 913 if (Version > MaxVersion) { 914 MaxVersion = Version; 915 MaxVersionString = std::string(VersionText); 916 } 917 } 918 } 919 if (!MaxVersion) 920 return ""; 921 return MaxVersionString; 922 } 923 924 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 925 ArgStringList &CC1Args) const { 926 // Header search paths should be handled by each of the subclasses. 927 // Historically, they have not been, and instead have been handled inside of 928 // the CC1-layer frontend. As the logic is hoisted out, this generic function 929 // will slowly stop being called. 930 // 931 // While it is being called, replicate a bit of a hack to propagate the 932 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ 933 // header search paths with it. Once all systems are overriding this 934 // function, the CC1 flag and this line can be removed. 935 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); 936 } 937 938 void ToolChain::AddClangCXXStdlibIsystemArgs( 939 const llvm::opt::ArgList &DriverArgs, 940 llvm::opt::ArgStringList &CC1Args) const { 941 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem); 942 if (!DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx, 943 options::OPT_nostdlibinc)) 944 for (const auto &P : 945 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem)) 946 addSystemInclude(DriverArgs, CC1Args, P); 947 } 948 949 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { 950 return getDriver().CCCIsCXX() && 951 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 952 options::OPT_nostdlibxx); 953 } 954 955 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 956 ArgStringList &CmdArgs) const { 957 assert(!Args.hasArg(options::OPT_nostdlibxx) && 958 "should not have called this"); 959 CXXStdlibType Type = GetCXXStdlibType(Args); 960 961 switch (Type) { 962 case ToolChain::CST_Libcxx: 963 CmdArgs.push_back("-lc++"); 964 break; 965 966 case ToolChain::CST_Libstdcxx: 967 CmdArgs.push_back("-lstdc++"); 968 break; 969 } 970 } 971 972 void ToolChain::AddFilePathLibArgs(const ArgList &Args, 973 ArgStringList &CmdArgs) const { 974 for (const auto &LibPath : getFilePaths()) 975 if(LibPath.length() > 0) 976 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath)); 977 } 978 979 void ToolChain::AddCCKextLibArgs(const ArgList &Args, 980 ArgStringList &CmdArgs) const { 981 CmdArgs.push_back("-lcc_kext"); 982 } 983 984 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args, 985 std::string &Path) const { 986 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed 987 // (to keep the linker options consistent with gcc and clang itself). 988 if (!isOptimizationLevelFast(Args)) { 989 // Check if -ffast-math or -funsafe-math. 990 Arg *A = 991 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, 992 options::OPT_funsafe_math_optimizations, 993 options::OPT_fno_unsafe_math_optimizations); 994 995 if (!A || A->getOption().getID() == options::OPT_fno_fast_math || 996 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) 997 return false; 998 } 999 // If crtfastmath.o exists add it to the arguments. 1000 Path = GetFilePath("crtfastmath.o"); 1001 return (Path != "crtfastmath.o"); // Not found. 1002 } 1003 1004 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args, 1005 ArgStringList &CmdArgs) const { 1006 std::string Path; 1007 if (isFastMathRuntimeAvailable(Args, Path)) { 1008 CmdArgs.push_back(Args.MakeArgString(Path)); 1009 return true; 1010 } 1011 1012 return false; 1013 } 1014 1015 SanitizerMask ToolChain::getSupportedSanitizers() const { 1016 // Return sanitizers which don't require runtime support and are not 1017 // platform dependent. 1018 1019 SanitizerMask Res = 1020 (SanitizerKind::Undefined & ~SanitizerKind::Vptr & 1021 ~SanitizerKind::Function) | 1022 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) | 1023 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero | 1024 SanitizerKind::UnsignedIntegerOverflow | 1025 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion | 1026 SanitizerKind::Nullability | SanitizerKind::LocalBounds; 1027 if (getTriple().getArch() == llvm::Triple::x86 || 1028 getTriple().getArch() == llvm::Triple::x86_64 || 1029 getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() || 1030 getTriple().isAArch64()) 1031 Res |= SanitizerKind::CFIICall; 1032 if (getTriple().getArch() == llvm::Triple::x86_64 || 1033 getTriple().isAArch64(64) || getTriple().isRISCV()) 1034 Res |= SanitizerKind::ShadowCallStack; 1035 if (getTriple().isAArch64(64)) 1036 Res |= SanitizerKind::MemTag; 1037 return Res; 1038 } 1039 1040 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 1041 ArgStringList &CC1Args) const {} 1042 1043 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs, 1044 ArgStringList &CC1Args) const {} 1045 1046 llvm::SmallVector<std::string, 12> 1047 ToolChain::getHIPDeviceLibs(const ArgList &DriverArgs) const { 1048 return {}; 1049 } 1050 1051 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, 1052 ArgStringList &CC1Args) const {} 1053 1054 static VersionTuple separateMSVCFullVersion(unsigned Version) { 1055 if (Version < 100) 1056 return VersionTuple(Version); 1057 1058 if (Version < 10000) 1059 return VersionTuple(Version / 100, Version % 100); 1060 1061 unsigned Build = 0, Factor = 1; 1062 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) 1063 Build = Build + (Version % 10) * Factor; 1064 return VersionTuple(Version / 100, Version % 100, Build); 1065 } 1066 1067 VersionTuple 1068 ToolChain::computeMSVCVersion(const Driver *D, 1069 const llvm::opt::ArgList &Args) const { 1070 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); 1071 const Arg *MSCompatibilityVersion = 1072 Args.getLastArg(options::OPT_fms_compatibility_version); 1073 1074 if (MSCVersion && MSCompatibilityVersion) { 1075 if (D) 1076 D->Diag(diag::err_drv_argument_not_allowed_with) 1077 << MSCVersion->getAsString(Args) 1078 << MSCompatibilityVersion->getAsString(Args); 1079 return VersionTuple(); 1080 } 1081 1082 if (MSCompatibilityVersion) { 1083 VersionTuple MSVT; 1084 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) { 1085 if (D) 1086 D->Diag(diag::err_drv_invalid_value) 1087 << MSCompatibilityVersion->getAsString(Args) 1088 << MSCompatibilityVersion->getValue(); 1089 } else { 1090 return MSVT; 1091 } 1092 } 1093 1094 if (MSCVersion) { 1095 unsigned Version = 0; 1096 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) { 1097 if (D) 1098 D->Diag(diag::err_drv_invalid_value) 1099 << MSCVersion->getAsString(Args) << MSCVersion->getValue(); 1100 } else { 1101 return separateMSVCFullVersion(Version); 1102 } 1103 } 1104 1105 return VersionTuple(); 1106 } 1107 1108 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( 1109 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, 1110 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { 1111 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 1112 const OptTable &Opts = getDriver().getOpts(); 1113 bool Modified = false; 1114 1115 // Handle -Xopenmp-target flags 1116 for (auto *A : Args) { 1117 // Exclude flags which may only apply to the host toolchain. 1118 // Do not exclude flags when the host triple (AuxTriple) 1119 // matches the current toolchain triple. If it is not present 1120 // at all, target and host share a toolchain. 1121 if (A->getOption().matches(options::OPT_m_Group)) { 1122 if (SameTripleAsHost) 1123 DAL->append(A); 1124 else 1125 Modified = true; 1126 continue; 1127 } 1128 1129 unsigned Index; 1130 unsigned Prev; 1131 bool XOpenMPTargetNoTriple = 1132 A->getOption().matches(options::OPT_Xopenmp_target); 1133 1134 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { 1135 // Passing device args: -Xopenmp-target=<triple> -opt=val. 1136 if (A->getValue(0) == getTripleString()) 1137 Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 1138 else 1139 continue; 1140 } else if (XOpenMPTargetNoTriple) { 1141 // Passing device args: -Xopenmp-target -opt=val. 1142 Index = Args.getBaseArgs().MakeIndex(A->getValue(0)); 1143 } else { 1144 DAL->append(A); 1145 continue; 1146 } 1147 1148 // Parse the argument to -Xopenmp-target. 1149 Prev = Index; 1150 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); 1151 if (!XOpenMPTargetArg || Index > Prev + 1) { 1152 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) 1153 << A->getAsString(Args); 1154 continue; 1155 } 1156 if (XOpenMPTargetNoTriple && XOpenMPTargetArg && 1157 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) { 1158 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); 1159 continue; 1160 } 1161 XOpenMPTargetArg->setBaseArg(A); 1162 A = XOpenMPTargetArg.release(); 1163 AllocatedArgs.push_back(A); 1164 DAL->append(A); 1165 Modified = true; 1166 } 1167 1168 if (Modified) 1169 return DAL; 1170 1171 delete DAL; 1172 return nullptr; 1173 } 1174 1175 // TODO: Currently argument values separated by space e.g. 1176 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be 1177 // fixed. 1178 void ToolChain::TranslateXarchArgs( 1179 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, 1180 llvm::opt::DerivedArgList *DAL, 1181 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { 1182 const OptTable &Opts = getDriver().getOpts(); 1183 unsigned ValuePos = 1; 1184 if (A->getOption().matches(options::OPT_Xarch_device) || 1185 A->getOption().matches(options::OPT_Xarch_host)) 1186 ValuePos = 0; 1187 1188 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos)); 1189 unsigned Prev = Index; 1190 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index)); 1191 1192 // If the argument parsing failed or more than one argument was 1193 // consumed, the -Xarch_ argument's parameter tried to consume 1194 // extra arguments. Emit an error and ignore. 1195 // 1196 // We also want to disallow any options which would alter the 1197 // driver behavior; that isn't going to work in our model. We 1198 // use options::NoXarchOption to control this. 1199 if (!XarchArg || Index > Prev + 1) { 1200 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) 1201 << A->getAsString(Args); 1202 return; 1203 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) { 1204 auto &Diags = getDriver().getDiags(); 1205 unsigned DiagID = 1206 Diags.getCustomDiagID(DiagnosticsEngine::Error, 1207 "invalid Xarch argument: '%0', not all driver " 1208 "options can be forwared via Xarch argument"); 1209 Diags.Report(DiagID) << A->getAsString(Args); 1210 return; 1211 } 1212 XarchArg->setBaseArg(A); 1213 A = XarchArg.release(); 1214 if (!AllocatedArgs) 1215 DAL->AddSynthesizedArg(A); 1216 else 1217 AllocatedArgs->push_back(A); 1218 } 1219 1220 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs( 1221 const llvm::opt::DerivedArgList &Args, StringRef BoundArch, 1222 Action::OffloadKind OFK, 1223 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { 1224 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 1225 bool Modified = false; 1226 1227 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP; 1228 for (Arg *A : Args) { 1229 bool NeedTrans = false; 1230 bool Skip = false; 1231 if (A->getOption().matches(options::OPT_Xarch_device)) { 1232 NeedTrans = IsGPU; 1233 Skip = !IsGPU; 1234 } else if (A->getOption().matches(options::OPT_Xarch_host)) { 1235 NeedTrans = !IsGPU; 1236 Skip = IsGPU; 1237 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) { 1238 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since 1239 // they may need special translation. 1240 // Skip this argument unless the architecture matches BoundArch 1241 if (BoundArch.empty() || A->getValue(0) != BoundArch) 1242 Skip = true; 1243 else 1244 NeedTrans = true; 1245 } 1246 if (NeedTrans || Skip) 1247 Modified = true; 1248 if (NeedTrans) 1249 TranslateXarchArgs(Args, A, DAL, AllocatedArgs); 1250 if (!Skip) 1251 DAL->append(A); 1252 } 1253 1254 if (Modified) 1255 return DAL; 1256 1257 delete DAL; 1258 return nullptr; 1259 } 1260