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