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