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