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