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