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