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