[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / clang / lib / Driver / ToolChain.cpp
blob3434b5c1998929629704dc9dd5e19b70b2b76af3
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 //===----------------------------------------------------------------------===//
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>
48 using namespace clang;
49 using namespace driver;
50 using namespace tools;
51 using namespace llvm;
52 using namespace llvm::opt;
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);
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;
70 // -frtti is default, except for the PS4/PS5 and DriverKit.
71 bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
72 return NoRTTI ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
75 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
76 const ArgList &Args)
77 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
78 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
79 auto addIfExists = [this](path_list &List, const std::string &Path) {
80 if (getVFS().exists(Path))
81 List.push_back(Path);
84 for (const auto &Path : getRuntimePaths())
85 addIfExists(getLibraryPaths(), Path);
86 for (const auto &Path : getStdlibPaths())
87 addIfExists(getFilePaths(), Path);
88 addIfExists(getFilePaths(), getArchSpecificLibPath());
91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
92 Triple.setEnvironment(Env);
93 if (EffectiveTriple != llvm::Triple())
94 EffectiveTriple.setEnvironment(Env);
97 ToolChain::~ToolChain() = default;
99 llvm::vfs::FileSystem &ToolChain::getVFS() const {
100 return getDriver().getVFS();
103 bool ToolChain::useIntegratedAs() const {
104 return Args.hasFlag(options::OPT_fintegrated_as,
105 options::OPT_fno_integrated_as,
106 IsIntegratedAssemblerDefault());
109 bool ToolChain::useIntegratedBackend() const {
110 assert(
111 ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) ||
112 (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) &&
113 "(Non-)integrated backend set incorrectly!");
115 bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
116 options::OPT_fno_integrated_objemitter,
117 IsIntegratedBackendDefault());
119 // Diagnose when integrated-objemitter options are not supported by this
120 // toolchain.
121 unsigned DiagID;
122 if ((IBackend && !IsIntegratedBackendSupported()) ||
123 (!IBackend && !IsNonIntegratedBackendSupported()))
124 DiagID = clang::diag::err_drv_unsupported_opt_for_target;
125 else
126 DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
127 Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
128 if (A && !IsNonIntegratedBackendSupported())
129 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
130 A = Args.getLastArg(options::OPT_fintegrated_objemitter);
131 if (A && !IsIntegratedBackendSupported())
132 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
134 return IBackend;
137 bool ToolChain::useRelaxRelocations() const {
138 return ENABLE_X86_RELAX_RELOCATIONS;
141 bool ToolChain::defaultToIEEELongDouble() const {
142 return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
145 SanitizerArgs
146 ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const {
147 SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked);
148 SanitizerArgsChecked = true;
149 return SanArgs;
152 const XRayArgs& ToolChain::getXRayArgs() const {
153 if (!XRayArguments.get())
154 XRayArguments.reset(new XRayArgs(*this, Args));
155 return *XRayArguments.get();
158 namespace {
160 struct DriverSuffix {
161 const char *Suffix;
162 const char *ModeFlag;
165 } // namespace
167 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
168 // A list of known driver suffixes. Suffixes are compared against the
169 // program name in order. If there is a match, the frontend type is updated as
170 // necessary by applying the ModeFlag.
171 static const DriverSuffix DriverSuffixes[] = {
172 {"clang", nullptr},
173 {"clang++", "--driver-mode=g++"},
174 {"clang-c++", "--driver-mode=g++"},
175 {"clang-cc", nullptr},
176 {"clang-cpp", "--driver-mode=cpp"},
177 {"clang-g++", "--driver-mode=g++"},
178 {"clang-gcc", nullptr},
179 {"clang-cl", "--driver-mode=cl"},
180 {"cc", nullptr},
181 {"cpp", "--driver-mode=cpp"},
182 {"cl", "--driver-mode=cl"},
183 {"++", "--driver-mode=g++"},
184 {"flang", "--driver-mode=flang"},
185 {"clang-dxc", "--driver-mode=dxc"},
188 for (const auto &DS : DriverSuffixes) {
189 StringRef Suffix(DS.Suffix);
190 if (ProgName.endswith(Suffix)) {
191 Pos = ProgName.size() - Suffix.size();
192 return &DS;
195 return nullptr;
198 /// Normalize the program name from argv[0] by stripping the file extension if
199 /// present and lower-casing the string on Windows.
200 static std::string normalizeProgramName(llvm::StringRef Argv0) {
201 std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
202 if (is_style_windows(llvm::sys::path::Style::native)) {
203 // Transform to lowercase for case insensitive file systems.
204 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
205 ::tolower);
207 return ProgName;
210 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
211 // Try to infer frontend type and default target from the program name by
212 // comparing it against DriverSuffixes in order.
214 // If there is a match, the function tries to identify a target as prefix.
215 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
216 // prefix "x86_64-linux". If such a target prefix is found, it may be
217 // added via -target as implicit first argument.
218 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
220 if (!DS) {
221 // Try again after stripping any trailing version number:
222 // clang++3.5 -> clang++
223 ProgName = ProgName.rtrim("0123456789.");
224 DS = FindDriverSuffix(ProgName, Pos);
227 if (!DS) {
228 // Try again after stripping trailing -component.
229 // clang++-tot -> clang++
230 ProgName = ProgName.slice(0, ProgName.rfind('-'));
231 DS = FindDriverSuffix(ProgName, Pos);
233 return DS;
236 ParsedClangName
237 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
238 std::string ProgName = normalizeProgramName(PN);
239 size_t SuffixPos;
240 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
241 if (!DS)
242 return {};
243 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
245 size_t LastComponent = ProgName.rfind('-', SuffixPos);
246 if (LastComponent == std::string::npos)
247 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
248 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
249 SuffixEnd - LastComponent - 1);
251 // Infer target from the prefix.
252 StringRef Prefix(ProgName);
253 Prefix = Prefix.slice(0, LastComponent);
254 std::string IgnoredError;
255 bool IsRegistered =
256 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
257 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
258 IsRegistered};
261 StringRef ToolChain::getDefaultUniversalArchName() const {
262 // In universal driver terms, the arch name accepted by -arch isn't exactly
263 // the same as the ones that appear in the triple. Roughly speaking, this is
264 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
265 switch (Triple.getArch()) {
266 case llvm::Triple::aarch64: {
267 if (getTriple().isArm64e())
268 return "arm64e";
269 return "arm64";
271 case llvm::Triple::aarch64_32:
272 return "arm64_32";
273 case llvm::Triple::ppc:
274 return "ppc";
275 case llvm::Triple::ppcle:
276 return "ppcle";
277 case llvm::Triple::ppc64:
278 return "ppc64";
279 case llvm::Triple::ppc64le:
280 return "ppc64le";
281 default:
282 return Triple.getArchName();
286 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
287 return Input.getFilename();
290 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
291 return false;
294 Tool *ToolChain::getClang() const {
295 if (!Clang)
296 Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
297 return Clang.get();
300 Tool *ToolChain::getFlang() const {
301 if (!Flang)
302 Flang.reset(new tools::Flang(*this));
303 return Flang.get();
306 Tool *ToolChain::buildAssembler() const {
307 return new tools::ClangAs(*this);
310 Tool *ToolChain::buildLinker() const {
311 llvm_unreachable("Linking is not supported by this toolchain");
314 Tool *ToolChain::buildStaticLibTool() const {
315 llvm_unreachable("Creating static lib is not supported by this toolchain");
318 Tool *ToolChain::getAssemble() const {
319 if (!Assemble)
320 Assemble.reset(buildAssembler());
321 return Assemble.get();
324 Tool *ToolChain::getClangAs() const {
325 if (!Assemble)
326 Assemble.reset(new tools::ClangAs(*this));
327 return Assemble.get();
330 Tool *ToolChain::getLink() const {
331 if (!Link)
332 Link.reset(buildLinker());
333 return Link.get();
336 Tool *ToolChain::getStaticLibTool() const {
337 if (!StaticLibTool)
338 StaticLibTool.reset(buildStaticLibTool());
339 return StaticLibTool.get();
342 Tool *ToolChain::getIfsMerge() const {
343 if (!IfsMerge)
344 IfsMerge.reset(new tools::ifstool::Merger(*this));
345 return IfsMerge.get();
348 Tool *ToolChain::getOffloadBundler() const {
349 if (!OffloadBundler)
350 OffloadBundler.reset(new tools::OffloadBundler(*this));
351 return OffloadBundler.get();
354 Tool *ToolChain::getOffloadWrapper() const {
355 if (!OffloadWrapper)
356 OffloadWrapper.reset(new tools::OffloadWrapper(*this));
357 return OffloadWrapper.get();
360 Tool *ToolChain::getOffloadPackager() const {
361 if (!OffloadPackager)
362 OffloadPackager.reset(new tools::OffloadPackager(*this));
363 return OffloadPackager.get();
366 Tool *ToolChain::getLinkerWrapper() const {
367 if (!LinkerWrapper)
368 LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
369 return LinkerWrapper.get();
372 Tool *ToolChain::getTool(Action::ActionClass AC) const {
373 switch (AC) {
374 case Action::AssembleJobClass:
375 return getAssemble();
377 case Action::IfsMergeJobClass:
378 return getIfsMerge();
380 case Action::LinkJobClass:
381 return getLink();
383 case Action::StaticLibJobClass:
384 return getStaticLibTool();
386 case Action::InputClass:
387 case Action::BindArchClass:
388 case Action::OffloadClass:
389 case Action::LipoJobClass:
390 case Action::DsymutilJobClass:
391 case Action::VerifyDebugInfoJobClass:
392 llvm_unreachable("Invalid tool kind.");
394 case Action::CompileJobClass:
395 case Action::PrecompileJobClass:
396 case Action::HeaderModulePrecompileJobClass:
397 case Action::PreprocessJobClass:
398 case Action::ExtractAPIJobClass:
399 case Action::AnalyzeJobClass:
400 case Action::MigrateJobClass:
401 case Action::VerifyPCHJobClass:
402 case Action::BackendJobClass:
403 return getClang();
405 case Action::OffloadBundlingJobClass:
406 case Action::OffloadUnbundlingJobClass:
407 return getOffloadBundler();
409 case Action::OffloadWrapperJobClass:
410 return getOffloadWrapper();
411 case Action::OffloadPackagerJobClass:
412 return getOffloadPackager();
413 case Action::LinkerWrapperJobClass:
414 return getLinkerWrapper();
417 llvm_unreachable("Invalid tool kind.");
420 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
421 const ArgList &Args) {
422 const llvm::Triple &Triple = TC.getTriple();
423 bool IsWindows = Triple.isOSWindows();
425 if (TC.isBareMetal())
426 return Triple.getArchName();
428 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
429 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
430 ? "armhf"
431 : "arm";
433 // For historic reasons, Android library is using i686 instead of i386.
434 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
435 return "i686";
437 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
438 return "x32";
440 return llvm::Triple::getArchTypeName(TC.getArch());
443 StringRef ToolChain::getOSLibName() const {
444 if (Triple.isOSDarwin())
445 return "darwin";
447 switch (Triple.getOS()) {
448 case llvm::Triple::FreeBSD:
449 return "freebsd";
450 case llvm::Triple::NetBSD:
451 return "netbsd";
452 case llvm::Triple::OpenBSD:
453 return "openbsd";
454 case llvm::Triple::Solaris:
455 return "sunos";
456 case llvm::Triple::AIX:
457 return "aix";
458 default:
459 return getOS();
463 std::string ToolChain::getCompilerRTPath() const {
464 SmallString<128> Path(getDriver().ResourceDir);
465 if (isBareMetal()) {
466 llvm::sys::path::append(Path, "lib", getOSLibName());
467 Path += SelectedMultilib.gccSuffix();
468 } else if (Triple.isOSUnknown()) {
469 llvm::sys::path::append(Path, "lib");
470 } else {
471 llvm::sys::path::append(Path, "lib", getOSLibName());
473 return std::string(Path.str());
476 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
477 StringRef Component,
478 FileType Type) const {
479 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
480 return llvm::sys::path::filename(CRTAbsolutePath).str();
483 std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
484 StringRef Component,
485 FileType Type,
486 bool AddArch) const {
487 const llvm::Triple &TT = getTriple();
488 bool IsITANMSVCWindows =
489 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
491 const char *Prefix =
492 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
493 const char *Suffix;
494 switch (Type) {
495 case ToolChain::FT_Object:
496 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
497 break;
498 case ToolChain::FT_Static:
499 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
500 break;
501 case ToolChain::FT_Shared:
502 Suffix = TT.isOSWindows()
503 ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
504 : ".so";
505 break;
508 std::string ArchAndEnv;
509 if (AddArch) {
510 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
511 const char *Env = TT.isAndroid() ? "-android" : "";
512 ArchAndEnv = ("-" + Arch + Env).str();
514 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
517 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
518 FileType Type) const {
519 // Check for runtime files in the new layout without the architecture first.
520 std::string CRTBasename =
521 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
522 for (const auto &LibPath : getLibraryPaths()) {
523 SmallString<128> P(LibPath);
524 llvm::sys::path::append(P, CRTBasename);
525 if (getVFS().exists(P))
526 return std::string(P.str());
529 // Fall back to the old expected compiler-rt name if the new one does not
530 // exist.
531 CRTBasename =
532 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
533 SmallString<128> Path(getCompilerRTPath());
534 llvm::sys::path::append(Path, CRTBasename);
535 return std::string(Path.str());
538 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
539 StringRef Component,
540 FileType Type) const {
541 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
544 ToolChain::path_list ToolChain::getRuntimePaths() const {
545 path_list Paths;
546 auto addPathForTriple = [this, &Paths](const llvm::Triple &Triple) {
547 SmallString<128> P(D.ResourceDir);
548 llvm::sys::path::append(P, "lib", Triple.str());
549 Paths.push_back(std::string(P.str()));
552 addPathForTriple(getTriple());
554 // Android targets may include an API level at the end. We still want to fall
555 // back on a path without the API level.
556 if (getTriple().isAndroid() &&
557 getTriple().getEnvironmentName() != "android") {
558 llvm::Triple TripleWithoutLevel = getTriple();
559 TripleWithoutLevel.setEnvironmentName("android");
560 addPathForTriple(TripleWithoutLevel);
563 return Paths;
566 ToolChain::path_list ToolChain::getStdlibPaths() const {
567 path_list Paths;
568 SmallString<128> P(D.Dir);
569 llvm::sys::path::append(P, "..", "lib", getTripleString());
570 Paths.push_back(std::string(P.str()));
572 return Paths;
575 std::string ToolChain::getArchSpecificLibPath() const {
576 SmallString<128> Path(getDriver().ResourceDir);
577 llvm::sys::path::append(Path, "lib", getOSLibName(),
578 llvm::Triple::getArchTypeName(getArch()));
579 return std::string(Path.str());
582 bool ToolChain::needsProfileRT(const ArgList &Args) {
583 if (Args.hasArg(options::OPT_noprofilelib))
584 return false;
586 return Args.hasArg(options::OPT_fprofile_generate) ||
587 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
588 Args.hasArg(options::OPT_fcs_profile_generate) ||
589 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
590 Args.hasArg(options::OPT_fprofile_instr_generate) ||
591 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
592 Args.hasArg(options::OPT_fcreate_profile) ||
593 Args.hasArg(options::OPT_forder_file_instrumentation);
596 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
597 return Args.hasArg(options::OPT_coverage) ||
598 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
599 false);
602 Tool *ToolChain::SelectTool(const JobAction &JA) const {
603 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
604 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
605 Action::ActionClass AC = JA.getKind();
606 if (AC == Action::AssembleJobClass && useIntegratedAs())
607 return getClangAs();
608 return getTool(AC);
611 std::string ToolChain::GetFilePath(const char *Name) const {
612 return D.GetFilePath(Name, *this);
615 std::string ToolChain::GetProgramPath(const char *Name) const {
616 return D.GetProgramPath(Name, *this);
619 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
620 if (LinkerIsLLD)
621 *LinkerIsLLD = false;
623 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
624 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
625 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
626 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
628 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
629 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
630 // contain a path component separator.
631 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
632 std::string Path(A->getValue());
633 if (!Path.empty()) {
634 if (llvm::sys::path::parent_path(Path).empty())
635 Path = GetProgramPath(A->getValue());
636 if (llvm::sys::fs::can_execute(Path))
637 return std::string(Path);
639 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
640 return GetProgramPath(getDefaultLinker());
642 // If we're passed -fuse-ld= with no argument, or with the argument ld,
643 // then use whatever the default system linker is.
644 if (UseLinker.empty() || UseLinker == "ld") {
645 const char *DefaultLinker = getDefaultLinker();
646 if (llvm::sys::path::is_absolute(DefaultLinker))
647 return std::string(DefaultLinker);
648 else
649 return GetProgramPath(DefaultLinker);
652 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
653 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
654 // to a relative path is surprising. This is more complex due to priorities
655 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
656 if (UseLinker.contains('/'))
657 getDriver().Diag(diag::warn_drv_fuse_ld_path);
659 if (llvm::sys::path::is_absolute(UseLinker)) {
660 // If we're passed what looks like an absolute path, don't attempt to
661 // second-guess that.
662 if (llvm::sys::fs::can_execute(UseLinker))
663 return std::string(UseLinker);
664 } else {
665 llvm::SmallString<8> LinkerName;
666 if (Triple.isOSDarwin())
667 LinkerName.append("ld64.");
668 else
669 LinkerName.append("ld.");
670 LinkerName.append(UseLinker);
672 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
673 if (llvm::sys::fs::can_execute(LinkerPath)) {
674 if (LinkerIsLLD)
675 *LinkerIsLLD = UseLinker == "lld";
676 return LinkerPath;
680 if (A)
681 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
683 return GetProgramPath(getDefaultLinker());
686 std::string ToolChain::GetStaticLibToolPath() const {
687 // TODO: Add support for static lib archiving on Windows
688 if (Triple.isOSDarwin())
689 return GetProgramPath("libtool");
690 return GetProgramPath("llvm-ar");
693 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
694 types::ID id = types::lookupTypeForExtension(Ext);
696 // Flang always runs the preprocessor and has no notion of "preprocessed
697 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
698 // them differently.
699 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
700 id = types::TY_Fortran;
702 return id;
705 bool ToolChain::HasNativeLLVMSupport() const {
706 return false;
709 bool ToolChain::isCrossCompiling() const {
710 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
711 switch (HostTriple.getArch()) {
712 // The A32/T32/T16 instruction sets are not separate architectures in this
713 // context.
714 case llvm::Triple::arm:
715 case llvm::Triple::armeb:
716 case llvm::Triple::thumb:
717 case llvm::Triple::thumbeb:
718 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
719 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
720 default:
721 return HostTriple.getArch() != getArch();
725 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
726 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
727 VersionTuple());
730 llvm::ExceptionHandling
731 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
732 return llvm::ExceptionHandling::None;
735 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
736 if (Model == "single") {
737 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
738 return Triple.getArch() == llvm::Triple::arm ||
739 Triple.getArch() == llvm::Triple::armeb ||
740 Triple.getArch() == llvm::Triple::thumb ||
741 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
742 } else if (Model == "posix")
743 return true;
745 return false;
748 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
749 types::ID InputType) const {
750 switch (getTriple().getArch()) {
751 default:
752 return getTripleString();
754 case llvm::Triple::x86_64: {
755 llvm::Triple Triple = getTriple();
756 if (!Triple.isOSBinFormatMachO())
757 return getTripleString();
759 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
760 // x86_64h goes in the triple. Other -march options just use the
761 // vanilla triple we already have.
762 StringRef MArch = A->getValue();
763 if (MArch == "x86_64h")
764 Triple.setArchName(MArch);
766 return Triple.getTriple();
768 case llvm::Triple::aarch64: {
769 llvm::Triple Triple = getTriple();
770 if (!Triple.isOSBinFormatMachO())
771 return getTripleString();
773 if (Triple.isArm64e())
774 return getTripleString();
776 // FIXME: older versions of ld64 expect the "arm64" component in the actual
777 // triple string and query it to determine whether an LTO file can be
778 // handled. Remove this when we don't care any more.
779 Triple.setArchName("arm64");
780 return Triple.getTriple();
782 case llvm::Triple::aarch64_32:
783 return getTripleString();
784 case llvm::Triple::arm:
785 case llvm::Triple::armeb:
786 case llvm::Triple::thumb:
787 case llvm::Triple::thumbeb: {
788 llvm::Triple Triple = getTriple();
789 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
790 tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
791 return Triple.getTriple();
796 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
797 types::ID InputType) const {
798 return ComputeLLVMTriple(Args, InputType);
801 std::string ToolChain::computeSysRoot() const {
802 return D.SysRoot;
805 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
806 ArgStringList &CC1Args) const {
807 // Each toolchain should provide the appropriate include flags.
810 void ToolChain::addClangTargetOptions(
811 const ArgList &DriverArgs, ArgStringList &CC1Args,
812 Action::OffloadKind DeviceOffloadKind) const {}
814 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
816 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
817 llvm::opt::ArgStringList &CmdArgs) const {
818 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
819 return;
821 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
824 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
825 const ArgList &Args) const {
826 if (runtimeLibType)
827 return *runtimeLibType;
829 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
830 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
832 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
833 if (LibName == "compiler-rt")
834 runtimeLibType = ToolChain::RLT_CompilerRT;
835 else if (LibName == "libgcc")
836 runtimeLibType = ToolChain::RLT_Libgcc;
837 else if (LibName == "platform")
838 runtimeLibType = GetDefaultRuntimeLibType();
839 else {
840 if (A)
841 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
842 << A->getAsString(Args);
844 runtimeLibType = GetDefaultRuntimeLibType();
847 return *runtimeLibType;
850 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
851 const ArgList &Args) const {
852 if (unwindLibType)
853 return *unwindLibType;
855 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
856 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
858 if (LibName == "none")
859 unwindLibType = ToolChain::UNW_None;
860 else if (LibName == "platform" || LibName == "") {
861 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
862 if (RtLibType == ToolChain::RLT_CompilerRT) {
863 if (getTriple().isAndroid() || getTriple().isOSAIX())
864 unwindLibType = ToolChain::UNW_CompilerRT;
865 else
866 unwindLibType = ToolChain::UNW_None;
867 } else if (RtLibType == ToolChain::RLT_Libgcc)
868 unwindLibType = ToolChain::UNW_Libgcc;
869 } else if (LibName == "libunwind") {
870 if (GetRuntimeLibType(Args) == RLT_Libgcc)
871 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
872 unwindLibType = ToolChain::UNW_CompilerRT;
873 } else if (LibName == "libgcc")
874 unwindLibType = ToolChain::UNW_Libgcc;
875 else {
876 if (A)
877 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
878 << A->getAsString(Args);
880 unwindLibType = GetDefaultUnwindLibType();
883 return *unwindLibType;
886 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
887 if (cxxStdlibType)
888 return *cxxStdlibType;
890 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
891 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
893 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
894 if (LibName == "libc++")
895 cxxStdlibType = ToolChain::CST_Libcxx;
896 else if (LibName == "libstdc++")
897 cxxStdlibType = ToolChain::CST_Libstdcxx;
898 else if (LibName == "platform")
899 cxxStdlibType = GetDefaultCXXStdlibType();
900 else {
901 if (A)
902 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
903 << A->getAsString(Args);
905 cxxStdlibType = GetDefaultCXXStdlibType();
908 return *cxxStdlibType;
911 /// Utility function to add a system include directory to CC1 arguments.
912 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
913 ArgStringList &CC1Args,
914 const Twine &Path) {
915 CC1Args.push_back("-internal-isystem");
916 CC1Args.push_back(DriverArgs.MakeArgString(Path));
919 /// Utility function to add a system include directory with extern "C"
920 /// semantics to CC1 arguments.
922 /// Note that this should be used rarely, and only for directories that
923 /// historically and for legacy reasons are treated as having implicit extern
924 /// "C" semantics. These semantics are *ignored* by and large today, but its
925 /// important to preserve the preprocessor changes resulting from the
926 /// classification.
927 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
928 ArgStringList &CC1Args,
929 const Twine &Path) {
930 CC1Args.push_back("-internal-externc-isystem");
931 CC1Args.push_back(DriverArgs.MakeArgString(Path));
934 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
935 ArgStringList &CC1Args,
936 const Twine &Path) {
937 if (llvm::sys::fs::exists(Path))
938 addExternCSystemInclude(DriverArgs, CC1Args, Path);
941 /// Utility function to add a list of system include directories to CC1.
942 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
943 ArgStringList &CC1Args,
944 ArrayRef<StringRef> Paths) {
945 for (const auto &Path : Paths) {
946 CC1Args.push_back("-internal-isystem");
947 CC1Args.push_back(DriverArgs.MakeArgString(Path));
951 /*static*/ std::string ToolChain::concat(StringRef Path, const Twine &A,
952 const Twine &B, const Twine &C,
953 const Twine &D) {
954 SmallString<128> Result(Path);
955 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
956 return std::string(Result);
959 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
960 std::error_code EC;
961 int MaxVersion = 0;
962 std::string MaxVersionString;
963 SmallString<128> Path(IncludePath);
964 llvm::sys::path::append(Path, "c++");
965 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
966 !EC && LI != LE; LI = LI.increment(EC)) {
967 StringRef VersionText = llvm::sys::path::filename(LI->path());
968 int Version;
969 if (VersionText[0] == 'v' &&
970 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
971 if (Version > MaxVersion) {
972 MaxVersion = Version;
973 MaxVersionString = std::string(VersionText);
977 if (!MaxVersion)
978 return "";
979 return MaxVersionString;
982 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
983 ArgStringList &CC1Args) const {
984 // Header search paths should be handled by each of the subclasses.
985 // Historically, they have not been, and instead have been handled inside of
986 // the CC1-layer frontend. As the logic is hoisted out, this generic function
987 // will slowly stop being called.
989 // While it is being called, replicate a bit of a hack to propagate the
990 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
991 // header search paths with it. Once all systems are overriding this
992 // function, the CC1 flag and this line can be removed.
993 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
996 void ToolChain::AddClangCXXStdlibIsystemArgs(
997 const llvm::opt::ArgList &DriverArgs,
998 llvm::opt::ArgStringList &CC1Args) const {
999 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1000 if (!DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
1001 options::OPT_nostdlibinc))
1002 for (const auto &P :
1003 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1004 addSystemInclude(DriverArgs, CC1Args, P);
1007 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1008 return getDriver().CCCIsCXX() &&
1009 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1010 options::OPT_nostdlibxx);
1013 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1014 ArgStringList &CmdArgs) const {
1015 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1016 "should not have called this");
1017 CXXStdlibType Type = GetCXXStdlibType(Args);
1019 switch (Type) {
1020 case ToolChain::CST_Libcxx:
1021 CmdArgs.push_back("-lc++");
1022 if (Args.hasArg(options::OPT_fexperimental_library))
1023 CmdArgs.push_back("-lc++experimental");
1024 break;
1026 case ToolChain::CST_Libstdcxx:
1027 CmdArgs.push_back("-lstdc++");
1028 break;
1032 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1033 ArgStringList &CmdArgs) const {
1034 for (const auto &LibPath : getFilePaths())
1035 if(LibPath.length() > 0)
1036 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1039 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1040 ArgStringList &CmdArgs) const {
1041 CmdArgs.push_back("-lcc_kext");
1044 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
1045 std::string &Path) const {
1046 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1047 // (to keep the linker options consistent with gcc and clang itself).
1048 if (!isOptimizationLevelFast(Args)) {
1049 // Check if -ffast-math or -funsafe-math.
1050 Arg *A =
1051 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
1052 options::OPT_funsafe_math_optimizations,
1053 options::OPT_fno_unsafe_math_optimizations);
1055 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1056 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1057 return false;
1059 // If crtfastmath.o exists add it to the arguments.
1060 Path = GetFilePath("crtfastmath.o");
1061 return (Path != "crtfastmath.o"); // Not found.
1064 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1065 ArgStringList &CmdArgs) const {
1066 std::string Path;
1067 if (isFastMathRuntimeAvailable(Args, Path)) {
1068 CmdArgs.push_back(Args.MakeArgString(Path));
1069 return true;
1072 return false;
1075 SanitizerMask ToolChain::getSupportedSanitizers() const {
1076 // Return sanitizers which don't require runtime support and are not
1077 // platform dependent.
1079 SanitizerMask Res =
1080 (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
1081 ~SanitizerKind::Function) |
1082 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1083 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1084 SanitizerKind::UnsignedIntegerOverflow |
1085 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1086 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1087 if (getTriple().getArch() == llvm::Triple::x86 ||
1088 getTriple().getArch() == llvm::Triple::x86_64 ||
1089 getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
1090 getTriple().isAArch64() || getTriple().isRISCV())
1091 Res |= SanitizerKind::CFIICall;
1092 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1093 getTriple().isAArch64(64) || getTriple().isRISCV())
1094 Res |= SanitizerKind::ShadowCallStack;
1095 if (getTriple().isAArch64(64))
1096 Res |= SanitizerKind::MemTag;
1097 return Res;
1100 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1101 ArgStringList &CC1Args) const {}
1103 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1104 ArgStringList &CC1Args) const {}
1106 llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
1107 ToolChain::getHIPDeviceLibs(const ArgList &DriverArgs) const {
1108 return {};
1111 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1112 ArgStringList &CC1Args) const {}
1114 static VersionTuple separateMSVCFullVersion(unsigned Version) {
1115 if (Version < 100)
1116 return VersionTuple(Version);
1118 if (Version < 10000)
1119 return VersionTuple(Version / 100, Version % 100);
1121 unsigned Build = 0, Factor = 1;
1122 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1123 Build = Build + (Version % 10) * Factor;
1124 return VersionTuple(Version / 100, Version % 100, Build);
1127 VersionTuple
1128 ToolChain::computeMSVCVersion(const Driver *D,
1129 const llvm::opt::ArgList &Args) const {
1130 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1131 const Arg *MSCompatibilityVersion =
1132 Args.getLastArg(options::OPT_fms_compatibility_version);
1134 if (MSCVersion && MSCompatibilityVersion) {
1135 if (D)
1136 D->Diag(diag::err_drv_argument_not_allowed_with)
1137 << MSCVersion->getAsString(Args)
1138 << MSCompatibilityVersion->getAsString(Args);
1139 return VersionTuple();
1142 if (MSCompatibilityVersion) {
1143 VersionTuple MSVT;
1144 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1145 if (D)
1146 D->Diag(diag::err_drv_invalid_value)
1147 << MSCompatibilityVersion->getAsString(Args)
1148 << MSCompatibilityVersion->getValue();
1149 } else {
1150 return MSVT;
1154 if (MSCVersion) {
1155 unsigned Version = 0;
1156 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1157 if (D)
1158 D->Diag(diag::err_drv_invalid_value)
1159 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1160 } else {
1161 return separateMSVCFullVersion(Version);
1165 return VersionTuple();
1168 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1169 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1170 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1171 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1172 const OptTable &Opts = getDriver().getOpts();
1173 bool Modified = false;
1175 // Handle -Xopenmp-target flags
1176 for (auto *A : Args) {
1177 // Exclude flags which may only apply to the host toolchain.
1178 // Do not exclude flags when the host triple (AuxTriple)
1179 // matches the current toolchain triple. If it is not present
1180 // at all, target and host share a toolchain.
1181 if (A->getOption().matches(options::OPT_m_Group)) {
1182 if (SameTripleAsHost)
1183 DAL->append(A);
1184 else
1185 Modified = true;
1186 continue;
1189 unsigned Index;
1190 unsigned Prev;
1191 bool XOpenMPTargetNoTriple =
1192 A->getOption().matches(options::OPT_Xopenmp_target);
1194 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1195 llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1197 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1198 if (TT.getTriple() == getTripleString())
1199 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1200 else
1201 continue;
1202 } else if (XOpenMPTargetNoTriple) {
1203 // Passing device args: -Xopenmp-target -opt=val.
1204 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1205 } else {
1206 DAL->append(A);
1207 continue;
1210 // Parse the argument to -Xopenmp-target.
1211 Prev = Index;
1212 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1213 if (!XOpenMPTargetArg || Index > Prev + 1) {
1214 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1215 << A->getAsString(Args);
1216 continue;
1218 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1219 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1220 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1221 continue;
1223 XOpenMPTargetArg->setBaseArg(A);
1224 A = XOpenMPTargetArg.release();
1225 AllocatedArgs.push_back(A);
1226 DAL->append(A);
1227 Modified = true;
1230 if (Modified)
1231 return DAL;
1233 delete DAL;
1234 return nullptr;
1237 // TODO: Currently argument values separated by space e.g.
1238 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1239 // fixed.
1240 void ToolChain::TranslateXarchArgs(
1241 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1242 llvm::opt::DerivedArgList *DAL,
1243 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1244 const OptTable &Opts = getDriver().getOpts();
1245 unsigned ValuePos = 1;
1246 if (A->getOption().matches(options::OPT_Xarch_device) ||
1247 A->getOption().matches(options::OPT_Xarch_host))
1248 ValuePos = 0;
1250 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1251 unsigned Prev = Index;
1252 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1254 // If the argument parsing failed or more than one argument was
1255 // consumed, the -Xarch_ argument's parameter tried to consume
1256 // extra arguments. Emit an error and ignore.
1258 // We also want to disallow any options which would alter the
1259 // driver behavior; that isn't going to work in our model. We
1260 // use options::NoXarchOption to control this.
1261 if (!XarchArg || Index > Prev + 1) {
1262 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1263 << A->getAsString(Args);
1264 return;
1265 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1266 auto &Diags = getDriver().getDiags();
1267 unsigned DiagID =
1268 Diags.getCustomDiagID(DiagnosticsEngine::Error,
1269 "invalid Xarch argument: '%0', not all driver "
1270 "options can be forwared via Xarch argument");
1271 Diags.Report(DiagID) << A->getAsString(Args);
1272 return;
1274 XarchArg->setBaseArg(A);
1275 A = XarchArg.release();
1276 if (!AllocatedArgs)
1277 DAL->AddSynthesizedArg(A);
1278 else
1279 AllocatedArgs->push_back(A);
1282 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1283 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1284 Action::OffloadKind OFK,
1285 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1286 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1287 bool Modified = false;
1289 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
1290 for (Arg *A : Args) {
1291 bool NeedTrans = false;
1292 bool Skip = false;
1293 if (A->getOption().matches(options::OPT_Xarch_device)) {
1294 NeedTrans = IsGPU;
1295 Skip = !IsGPU;
1296 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1297 NeedTrans = !IsGPU;
1298 Skip = IsGPU;
1299 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
1300 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1301 // they may need special translation.
1302 // Skip this argument unless the architecture matches BoundArch
1303 if (BoundArch.empty() || A->getValue(0) != BoundArch)
1304 Skip = true;
1305 else
1306 NeedTrans = true;
1308 if (NeedTrans || Skip)
1309 Modified = true;
1310 if (NeedTrans)
1311 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1312 if (!Skip)
1313 DAL->append(A);
1316 if (Modified)
1317 return DAL;
1319 delete DAL;
1320 return nullptr;