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