xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Linux.cpp (revision aa1a8ff2d6dbc51ef058f46f3db5a8bb77967145)
1 //===--- Linux.h - Linux ToolChain Implementations --------------*- C++ -*-===//
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 "Linux.h"
10 #include "Arch/ARM.h"
11 #include "Arch/LoongArch.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "CommonArgs.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Distro.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/ProfileData/InstrProf.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <system_error>
27 
28 using namespace clang::driver;
29 using namespace clang::driver::toolchains;
30 using namespace clang;
31 using namespace llvm::opt;
32 
33 using tools::addPathIfExists;
34 
35 /// Get our best guess at the multiarch triple for a target.
36 ///
37 /// Debian-based systems are starting to use a multiarch setup where they use
38 /// a target-triple directory in the library and header search paths.
39 /// Unfortunately, this triple does not align with the vanilla target triple,
40 /// so we provide a rough mapping here.
41 std::string Linux::getMultiarchTriple(const Driver &D,
42                                       const llvm::Triple &TargetTriple,
43                                       StringRef SysRoot) const {
44   llvm::Triple::EnvironmentType TargetEnvironment =
45       TargetTriple.getEnvironment();
46   bool IsAndroid = TargetTriple.isAndroid();
47   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
48   bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
49 
50   // For most architectures, just use whatever we have rather than trying to be
51   // clever.
52   switch (TargetTriple.getArch()) {
53   default:
54     break;
55 
56   // We use the existence of '/lib/<triple>' as a directory to detect some
57   // common linux triples that don't quite match the Clang triple for both
58   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
59   // regardless of what the actual target triple is.
60   case llvm::Triple::arm:
61   case llvm::Triple::thumb:
62     if (IsAndroid)
63       return "arm-linux-androideabi";
64     if (TargetEnvironment == llvm::Triple::GNUEABIHF ||
65         TargetEnvironment == llvm::Triple::MuslEABIHF ||
66         TargetEnvironment == llvm::Triple::EABIHF)
67       return "arm-linux-gnueabihf";
68     return "arm-linux-gnueabi";
69   case llvm::Triple::armeb:
70   case llvm::Triple::thumbeb:
71     if (TargetEnvironment == llvm::Triple::GNUEABIHF ||
72         TargetEnvironment == llvm::Triple::MuslEABIHF ||
73         TargetEnvironment == llvm::Triple::EABIHF)
74       return "armeb-linux-gnueabihf";
75     return "armeb-linux-gnueabi";
76   case llvm::Triple::x86:
77     if (IsAndroid)
78       return "i686-linux-android";
79     return "i386-linux-gnu";
80   case llvm::Triple::x86_64:
81     if (IsAndroid)
82       return "x86_64-linux-android";
83     if (TargetEnvironment == llvm::Triple::GNUX32)
84       return "x86_64-linux-gnux32";
85     return "x86_64-linux-gnu";
86   case llvm::Triple::aarch64:
87     if (IsAndroid)
88       return "aarch64-linux-android";
89     return "aarch64-linux-gnu";
90   case llvm::Triple::aarch64_be:
91     return "aarch64_be-linux-gnu";
92 
93   case llvm::Triple::loongarch64: {
94     const char *Libc;
95     const char *FPFlavor;
96 
97     if (TargetTriple.isGNUEnvironment()) {
98       Libc = "gnu";
99     } else if (TargetTriple.isMusl()) {
100       Libc = "musl";
101     } else {
102       return TargetTriple.str();
103     }
104 
105     switch (TargetEnvironment) {
106     default:
107       return TargetTriple.str();
108     case llvm::Triple::GNUSF:
109       FPFlavor = "sf";
110       break;
111     case llvm::Triple::GNUF32:
112       FPFlavor = "f32";
113       break;
114     case llvm::Triple::GNU:
115     case llvm::Triple::GNUF64:
116       // This was going to be "f64" in an earlier Toolchain Conventions
117       // revision, but starting from Feb 2023 the F64 ABI variants are
118       // unmarked in their canonical forms.
119       FPFlavor = "";
120       break;
121     }
122 
123     return (Twine("loongarch64-linux-") + Libc + FPFlavor).str();
124   }
125 
126   case llvm::Triple::m68k:
127     return "m68k-linux-gnu";
128 
129   case llvm::Triple::mips:
130     return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
131   case llvm::Triple::mipsel:
132     return IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
133   case llvm::Triple::mips64: {
134     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
135                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
136     if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
137       return MT;
138     if (D.getVFS().exists(concat(SysRoot, "/lib/mips64-linux-gnu")))
139       return "mips64-linux-gnu";
140     break;
141   }
142   case llvm::Triple::mips64el: {
143     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
144                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
145     if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
146       return MT;
147     if (D.getVFS().exists(concat(SysRoot, "/lib/mips64el-linux-gnu")))
148       return "mips64el-linux-gnu";
149     break;
150   }
151   case llvm::Triple::ppc:
152     if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
153       return "powerpc-linux-gnuspe";
154     return "powerpc-linux-gnu";
155   case llvm::Triple::ppcle:
156     return "powerpcle-linux-gnu";
157   case llvm::Triple::ppc64:
158     return "powerpc64-linux-gnu";
159   case llvm::Triple::ppc64le:
160     return "powerpc64le-linux-gnu";
161   case llvm::Triple::riscv64:
162     if (IsAndroid)
163       return "riscv64-linux-android";
164     return "riscv64-linux-gnu";
165   case llvm::Triple::sparc:
166     return "sparc-linux-gnu";
167   case llvm::Triple::sparcv9:
168     return "sparc64-linux-gnu";
169   case llvm::Triple::systemz:
170     return "s390x-linux-gnu";
171   }
172   return TargetTriple.str();
173 }
174 
175 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
176   if (Triple.isMIPS()) {
177     if (Triple.isAndroid()) {
178       StringRef CPUName;
179       StringRef ABIName;
180       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
181       if (CPUName == "mips32r6")
182         return "libr6";
183       if (CPUName == "mips32r2")
184         return "libr2";
185     }
186     // lib32 directory has a special meaning on MIPS targets.
187     // It contains N32 ABI binaries. Use this folder if produce
188     // code for N32 ABI only.
189     if (tools::mips::hasMipsAbiArg(Args, "n32"))
190       return "lib32";
191     return Triple.isArch32Bit() ? "lib" : "lib64";
192   }
193 
194   // It happens that only x86, PPC and SPARC use the 'lib32' variant of
195   // oslibdir, and using that variant while targeting other architectures causes
196   // problems because the libraries are laid out in shared system roots that
197   // can't cope with a 'lib32' library search path being considered. So we only
198   // enable them when we know we may need it.
199   //
200   // FIXME: This is a bit of a hack. We should really unify this code for
201   // reasoning about oslibdir spellings with the lib dir spellings in the
202   // GCCInstallationDetector, but that is a more significant refactoring.
203   if (Triple.getArch() == llvm::Triple::x86 || Triple.isPPC32() ||
204       Triple.getArch() == llvm::Triple::sparc)
205     return "lib32";
206 
207   if (Triple.getArch() == llvm::Triple::x86_64 && Triple.isX32())
208     return "libx32";
209 
210   if (Triple.getArch() == llvm::Triple::riscv32)
211     return "lib32";
212 
213   return Triple.isArch32Bit() ? "lib" : "lib64";
214 }
215 
216 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
217     : Generic_ELF(D, Triple, Args) {
218   GCCInstallation.init(Triple, Args);
219   Multilibs = GCCInstallation.getMultilibs();
220   SelectedMultilibs.assign({GCCInstallation.getMultilib()});
221   llvm::Triple::ArchType Arch = Triple.getArch();
222   std::string SysRoot = computeSysRoot();
223   ToolChain::path_list &PPaths = getProgramPaths();
224 
225   Generic_GCC::PushPPaths(PPaths);
226 
227   Distro Distro(D.getVFS(), Triple);
228 
229   if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
230     ExtraOpts.push_back("-z");
231     ExtraOpts.push_back("now");
232   }
233 
234   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
235       Triple.isAndroid()) {
236     ExtraOpts.push_back("-z");
237     ExtraOpts.push_back("relro");
238   }
239 
240   // Android ARM/AArch64 use max-page-size=4096 to reduce VMA usage. Note, lld
241   // from 11 onwards default max-page-size to 65536 for both ARM and AArch64.
242   if ((Triple.isARM() || Triple.isAArch64()) && Triple.isAndroid()) {
243     ExtraOpts.push_back("-z");
244     ExtraOpts.push_back("max-page-size=4096");
245   }
246 
247   if (GCCInstallation.getParentLibPath().contains("opt/rh/"))
248     // With devtoolset on RHEL, we want to add a bin directory that is relative
249     // to the detected gcc install, because if we are using devtoolset gcc then
250     // we want to use other tools from devtoolset (e.g. ld) instead of the
251     // standard system tools.
252     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
253                      "/../bin").str());
254 
255   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
256     ExtraOpts.push_back("-X");
257 
258   const bool IsAndroid = Triple.isAndroid();
259   const bool IsMips = Triple.isMIPS();
260   const bool IsHexagon = Arch == llvm::Triple::hexagon;
261   const bool IsRISCV = Triple.isRISCV();
262   const bool IsCSKY = Triple.isCSKY();
263 
264   if (IsCSKY && !SelectedMultilibs.empty())
265     SysRoot = SysRoot + SelectedMultilibs.back().osSuffix();
266 
267   if ((IsMips || IsCSKY) && !SysRoot.empty())
268     ExtraOpts.push_back("--sysroot=" + SysRoot);
269 
270   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
271   // and the MIPS ABI require .dynsym to be sorted in different ways.
272   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
273   // ABI requires a mapping between the GOT and the symbol table.
274   // Android loader does not support .gnu.hash until API 23.
275   // Hexagon linker/loader does not support .gnu.hash
276   if (!IsMips && !IsHexagon) {
277     if (Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
278         Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic ||
279         (IsAndroid && Triple.isAndroidVersionLT(23)))
280       ExtraOpts.push_back("--hash-style=both");
281     else
282       ExtraOpts.push_back("--hash-style=gnu");
283   }
284 
285 #ifdef ENABLE_LINKER_BUILD_ID
286   ExtraOpts.push_back("--build-id");
287 #endif
288 
289   // The selection of paths to try here is designed to match the patterns which
290   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
291   // This was determined by running GCC in a fake filesystem, creating all
292   // possible permutations of these directories, and seeing which ones it added
293   // to the link paths.
294   path_list &Paths = getFilePaths();
295 
296   const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
297   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
298 
299   // mips32: Debian multilib, we use /libo32, while in other case, /lib is
300   // used. We need add both libo32 and /lib.
301   if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel) {
302     Generic_GCC::AddMultilibPaths(D, SysRoot, "libo32", MultiarchTriple, Paths);
303     addPathIfExists(D, concat(SysRoot, "/libo32"), Paths);
304     addPathIfExists(D, concat(SysRoot, "/usr/libo32"), Paths);
305   }
306   Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
307 
308   addPathIfExists(D, concat(SysRoot, "/lib", MultiarchTriple), Paths);
309   addPathIfExists(D, concat(SysRoot, "/lib/..", OSLibDir), Paths);
310 
311   if (IsAndroid) {
312     // Android sysroots contain a library directory for each supported OS
313     // version as well as some unversioned libraries in the usual multiarch
314     // directory.
315     addPathIfExists(
316         D,
317         concat(SysRoot, "/usr/lib", MultiarchTriple,
318                llvm::to_string(Triple.getEnvironmentVersion().getMajor())),
319         Paths);
320   }
321 
322   addPathIfExists(D, concat(SysRoot, "/usr/lib", MultiarchTriple), Paths);
323   // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
324   // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
325   // this here.
326   if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
327       Triple.isArch64Bit())
328     addPathIfExists(D, concat(SysRoot, "/usr", OSLibDir), Paths);
329   else
330     addPathIfExists(D, concat(SysRoot, "/usr/lib/..", OSLibDir), Paths);
331   if (IsRISCV) {
332     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
333     addPathIfExists(D, concat(SysRoot, "/", OSLibDir, ABIName), Paths);
334     addPathIfExists(D, concat(SysRoot, "/usr", OSLibDir, ABIName), Paths);
335   }
336 
337   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
338 
339   addPathIfExists(D, concat(SysRoot, "/lib"), Paths);
340   addPathIfExists(D, concat(SysRoot, "/usr/lib"), Paths);
341 }
342 
343 ToolChain::RuntimeLibType Linux::GetDefaultRuntimeLibType() const {
344   if (getTriple().isAndroid())
345     return ToolChain::RLT_CompilerRT;
346   return Generic_ELF::GetDefaultRuntimeLibType();
347 }
348 
349 unsigned Linux::GetDefaultDwarfVersion() const {
350   if (getTriple().isAndroid())
351     return 4;
352   return ToolChain::GetDefaultDwarfVersion();
353 }
354 
355 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
356   if (getTriple().isAndroid())
357     return ToolChain::CST_Libcxx;
358   return ToolChain::CST_Libstdcxx;
359 }
360 
361 bool Linux::HasNativeLLVMSupport() const { return true; }
362 
363 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
364 
365 Tool *Linux::buildStaticLibTool() const {
366   return new tools::gnutools::StaticLibTool(*this);
367 }
368 
369 Tool *Linux::buildAssembler() const {
370   return new tools::gnutools::Assembler(*this);
371 }
372 
373 std::string Linux::computeSysRoot() const {
374   if (!getDriver().SysRoot.empty())
375     return getDriver().SysRoot;
376 
377   if (getTriple().isAndroid()) {
378     // Android toolchains typically include a sysroot at ../sysroot relative to
379     // the clang binary.
380     const StringRef ClangDir = getDriver().getInstalledDir();
381     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
382     if (getVFS().exists(AndroidSysRootPath))
383       return AndroidSysRootPath;
384   }
385 
386   if (getTriple().isCSKY()) {
387     // CSKY toolchains use different names for sysroot folder.
388     if (!GCCInstallation.isValid())
389       return std::string();
390     // GCCInstallation.getInstallPath() =
391     //   $GCCToolchainPath/lib/gcc/csky-linux-gnuabiv2/6.3.0
392     // Path = $GCCToolchainPath/csky-linux-gnuabiv2/libc
393     std::string Path = (GCCInstallation.getInstallPath() + "/../../../../" +
394                         GCCInstallation.getTriple().str() + "/libc")
395                            .str();
396     if (getVFS().exists(Path))
397       return Path;
398     return std::string();
399   }
400 
401   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
402     return std::string();
403 
404   // Standalone MIPS toolchains use different names for sysroot folder
405   // and put it into different places. Here we try to check some known
406   // variants.
407 
408   const StringRef InstallDir = GCCInstallation.getInstallPath();
409   const StringRef TripleStr = GCCInstallation.getTriple().str();
410   const Multilib &Multilib = GCCInstallation.getMultilib();
411 
412   std::string Path =
413       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
414           .str();
415 
416   if (getVFS().exists(Path))
417     return Path;
418 
419   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
420 
421   if (getVFS().exists(Path))
422     return Path;
423 
424   return std::string();
425 }
426 
427 std::string Linux::getDynamicLinker(const ArgList &Args) const {
428   const llvm::Triple::ArchType Arch = getArch();
429   const llvm::Triple &Triple = getTriple();
430 
431   const Distro Distro(getDriver().getVFS(), Triple);
432 
433   if (Triple.isAndroid()) {
434     if (getSanitizerArgs(Args).needsHwasanRt() &&
435         !Triple.isAndroidVersionLT(34) && Triple.isArch64Bit()) {
436       // On Android 14 and newer, there is a special linker_hwasan64 that
437       // allows to run HWASan binaries on non-HWASan system images. This
438       // is also available on HWASan system images, so we can just always
439       // use that instead.
440       return "/system/bin/linker_hwasan64";
441     }
442     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
443   }
444   if (Triple.isMusl()) {
445     std::string ArchName;
446     bool IsArm = false;
447 
448     switch (Arch) {
449     case llvm::Triple::arm:
450     case llvm::Triple::thumb:
451       ArchName = "arm";
452       IsArm = true;
453       break;
454     case llvm::Triple::armeb:
455     case llvm::Triple::thumbeb:
456       ArchName = "armeb";
457       IsArm = true;
458       break;
459     case llvm::Triple::x86:
460       ArchName = "i386";
461       break;
462     case llvm::Triple::x86_64:
463       ArchName = Triple.isX32() ? "x32" : Triple.getArchName().str();
464       break;
465     default:
466       ArchName = Triple.getArchName().str();
467     }
468     if (IsArm &&
469         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
470          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
471       ArchName += "hf";
472     if (Arch == llvm::Triple::ppc &&
473         Triple.getSubArch() == llvm::Triple::PPCSubArch_spe)
474       ArchName = "powerpc-sf";
475 
476     return "/lib/ld-musl-" + ArchName + ".so.1";
477   }
478 
479   std::string LibDir;
480   std::string Loader;
481 
482   switch (Arch) {
483   default:
484     llvm_unreachable("unsupported architecture");
485 
486   case llvm::Triple::aarch64:
487     LibDir = "lib";
488     Loader = "ld-linux-aarch64.so.1";
489     break;
490   case llvm::Triple::aarch64_be:
491     LibDir = "lib";
492     Loader = "ld-linux-aarch64_be.so.1";
493     break;
494   case llvm::Triple::arm:
495   case llvm::Triple::thumb:
496   case llvm::Triple::armeb:
497   case llvm::Triple::thumbeb: {
498     const bool HF =
499         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
500         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
501 
502     LibDir = "lib";
503     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
504     break;
505   }
506   case llvm::Triple::loongarch32: {
507     LibDir = "lib32";
508     Loader =
509         ("ld-linux-loongarch-" +
510          tools::loongarch::getLoongArchABI(getDriver(), Args, Triple) + ".so.1")
511             .str();
512     break;
513   }
514   case llvm::Triple::loongarch64: {
515     LibDir = "lib64";
516     Loader =
517         ("ld-linux-loongarch-" +
518          tools::loongarch::getLoongArchABI(getDriver(), Args, Triple) + ".so.1")
519             .str();
520     break;
521   }
522   case llvm::Triple::m68k:
523     LibDir = "lib";
524     Loader = "ld.so.1";
525     break;
526   case llvm::Triple::mips:
527   case llvm::Triple::mipsel:
528   case llvm::Triple::mips64:
529   case llvm::Triple::mips64el: {
530     bool IsNaN2008 = tools::mips::isNaN2008(getDriver(), Args, Triple);
531 
532     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
533 
534     if (tools::mips::isUCLibc(Args))
535       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
536     else if (!Triple.hasEnvironment() &&
537              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
538       Loader =
539           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
540     else
541       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
542 
543     break;
544   }
545   case llvm::Triple::ppc:
546     LibDir = "lib";
547     Loader = "ld.so.1";
548     break;
549   case llvm::Triple::ppcle:
550     LibDir = "lib";
551     Loader = "ld.so.1";
552     break;
553   case llvm::Triple::ppc64:
554     LibDir = "lib64";
555     Loader =
556         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
557     break;
558   case llvm::Triple::ppc64le:
559     LibDir = "lib64";
560     Loader =
561         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
562     break;
563   case llvm::Triple::riscv32: {
564     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
565     LibDir = "lib";
566     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
567     break;
568   }
569   case llvm::Triple::riscv64: {
570     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
571     LibDir = "lib";
572     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
573     break;
574   }
575   case llvm::Triple::sparc:
576   case llvm::Triple::sparcel:
577     LibDir = "lib";
578     Loader = "ld-linux.so.2";
579     break;
580   case llvm::Triple::sparcv9:
581     LibDir = "lib64";
582     Loader = "ld-linux.so.2";
583     break;
584   case llvm::Triple::systemz:
585     LibDir = "lib";
586     Loader = "ld64.so.1";
587     break;
588   case llvm::Triple::x86:
589     LibDir = "lib";
590     Loader = "ld-linux.so.2";
591     break;
592   case llvm::Triple::x86_64: {
593     bool X32 = Triple.isX32();
594 
595     LibDir = X32 ? "libx32" : "lib64";
596     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
597     break;
598   }
599   case llvm::Triple::ve:
600     return "/opt/nec/ve/lib/ld-linux-ve.so.1";
601   case llvm::Triple::csky: {
602     LibDir = "lib";
603     Loader = "ld.so.1";
604     break;
605   }
606   }
607 
608   if (Distro == Distro::Exherbo &&
609       (Triple.getVendor() == llvm::Triple::UnknownVendor ||
610        Triple.getVendor() == llvm::Triple::PC))
611     return "/usr/" + Triple.str() + "/lib/" + Loader;
612   return "/" + LibDir + "/" + Loader;
613 }
614 
615 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
616                                       ArgStringList &CC1Args) const {
617   const Driver &D = getDriver();
618   std::string SysRoot = computeSysRoot();
619 
620   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
621     return;
622 
623   // Add 'include' in the resource directory, which is similar to
624   // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
625   // contains some files conflicting with system /usr/include. musl systems
626   // prefer the /usr/include copies which are more relevant.
627   SmallString<128> ResourceDirInclude(D.ResourceDir);
628   llvm::sys::path::append(ResourceDirInclude, "include");
629   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) &&
630       (!getTriple().isMusl() || DriverArgs.hasArg(options::OPT_nostdlibinc)))
631     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
632 
633   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
634     return;
635 
636   // LOCAL_INCLUDE_DIR
637   addSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/usr/local/include"));
638   // TOOL_INCLUDE_DIR
639   AddMultilibIncludeArgs(DriverArgs, CC1Args);
640 
641   // Check for configure-time C include directories.
642   StringRef CIncludeDirs(C_INCLUDE_DIRS);
643   if (CIncludeDirs != "") {
644     SmallVector<StringRef, 5> dirs;
645     CIncludeDirs.split(dirs, ":");
646     for (StringRef dir : dirs) {
647       StringRef Prefix =
648           llvm::sys::path::is_absolute(dir) ? "" : StringRef(SysRoot);
649       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
650     }
651     return;
652   }
653 
654   // On systems using multiarch and Android, add /usr/include/$triple before
655   // /usr/include.
656   std::string MultiarchIncludeDir = getMultiarchTriple(D, getTriple(), SysRoot);
657   if (!MultiarchIncludeDir.empty() &&
658       D.getVFS().exists(concat(SysRoot, "/usr/include", MultiarchIncludeDir)))
659     addExternCSystemInclude(
660         DriverArgs, CC1Args,
661         concat(SysRoot, "/usr/include", MultiarchIncludeDir));
662 
663   if (getTriple().getOS() == llvm::Triple::RTEMS)
664     return;
665 
666   // Add an include of '/include' directly. This isn't provided by default by
667   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
668   // add even when Clang is acting as-if it were a system compiler.
669   addExternCSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/include"));
670 
671   addExternCSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/usr/include"));
672 
673   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
674     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
675 }
676 
677 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
678                                      llvm::opt::ArgStringList &CC1Args) const {
679   // We need a detected GCC installation on Linux to provide libstdc++'s
680   // headers in odd Linuxish places.
681   if (!GCCInstallation.isValid())
682     return;
683 
684   // Detect Debian g++-multiarch-incdir.diff.
685   StringRef TripleStr = GCCInstallation.getTriple().str();
686   StringRef DebianMultiarch =
687       GCCInstallation.getTriple().getArch() == llvm::Triple::x86
688           ? "i386-linux-gnu"
689           : TripleStr;
690 
691   // Try generic GCC detection first.
692   if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
693                                                DebianMultiarch))
694     return;
695 
696   StringRef LibDir = GCCInstallation.getParentLibPath();
697   const Multilib &Multilib = GCCInstallation.getMultilib();
698   const GCCVersion &Version = GCCInstallation.getVersion();
699 
700   const std::string LibStdCXXIncludePathCandidates[] = {
701       // Android standalone toolchain has C++ headers in yet another place.
702       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
703       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
704       // without a subdirectory corresponding to the gcc version.
705       LibDir.str() + "/../include/c++",
706       // Cray's gcc installation puts headers under "g++" without a
707       // version suffix.
708       LibDir.str() + "/../include/g++",
709   };
710 
711   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
712     if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
713                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
714       break;
715   }
716 }
717 
718 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
719                                ArgStringList &CC1Args) const {
720   CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
721 }
722 
723 void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
724                               ArgStringList &CC1Args) const {
725   RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
726 }
727 
728 void Linux::AddHIPRuntimeLibArgs(const ArgList &Args,
729                                  ArgStringList &CmdArgs) const {
730   CmdArgs.push_back(
731       Args.MakeArgString(StringRef("-L") + RocmInstallation->getLibPath()));
732 
733   if (Args.hasFlag(options::OPT_frtlib_add_rpath,
734                    options::OPT_fno_rtlib_add_rpath, false))
735     CmdArgs.append(
736         {"-rpath", Args.MakeArgString(RocmInstallation->getLibPath())});
737 
738   CmdArgs.push_back("-lamdhip64");
739 }
740 
741 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
742                                 ArgStringList &CC1Args) const {
743   if (GCCInstallation.isValid()) {
744     CC1Args.push_back("-isystem");
745     CC1Args.push_back(DriverArgs.MakeArgString(
746         GCCInstallation.getParentLibPath() + "/../" +
747         GCCInstallation.getTriple().str() + "/include"));
748   }
749 }
750 
751 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
752   return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
753          getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
754 }
755 
756 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
757   // Outline atomics for AArch64 are supported by compiler-rt
758   // and libgcc since 9.3.1
759   assert(getTriple().isAArch64() && "expected AArch64 target!");
760   ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
761   if (RtLib == ToolChain::RLT_CompilerRT)
762     return true;
763   assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
764   if (GCCInstallation.getVersion().isOlderThan(9, 3, 1))
765     return false;
766   return true;
767 }
768 
769 bool Linux::IsMathErrnoDefault() const {
770   if (getTriple().isAndroid() || getTriple().isMusl())
771     return false;
772   return Generic_ELF::IsMathErrnoDefault();
773 }
774 
775 SanitizerMask Linux::getSupportedSanitizers() const {
776   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
777   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
778   const bool IsMIPS = getTriple().isMIPS32();
779   const bool IsMIPS64 = getTriple().isMIPS64();
780   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
781                            getTriple().getArch() == llvm::Triple::ppc64le;
782   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
783                          getTriple().getArch() == llvm::Triple::aarch64_be;
784   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
785                          getTriple().getArch() == llvm::Triple::thumb ||
786                          getTriple().getArch() == llvm::Triple::armeb ||
787                          getTriple().getArch() == llvm::Triple::thumbeb;
788   const bool IsLoongArch64 = getTriple().getArch() == llvm::Triple::loongarch64;
789   const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
790   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
791   const bool IsHexagon = getTriple().getArch() == llvm::Triple::hexagon;
792   SanitizerMask Res = ToolChain::getSupportedSanitizers();
793   Res |= SanitizerKind::Address;
794   Res |= SanitizerKind::PointerCompare;
795   Res |= SanitizerKind::PointerSubtract;
796   Res |= SanitizerKind::Fuzzer;
797   Res |= SanitizerKind::FuzzerNoLink;
798   Res |= SanitizerKind::KernelAddress;
799   Res |= SanitizerKind::Memory;
800   Res |= SanitizerKind::Vptr;
801   Res |= SanitizerKind::SafeStack;
802   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsLoongArch64)
803     Res |= SanitizerKind::DataFlow;
804   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
805       IsRISCV64 || IsSystemZ || IsHexagon || IsLoongArch64)
806     Res |= SanitizerKind::Leak;
807   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ ||
808       IsLoongArch64 || IsRISCV64)
809     Res |= SanitizerKind::Thread;
810   if (IsX86_64 || IsSystemZ)
811     Res |= SanitizerKind::KernelMemory;
812   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
813       IsPowerPC64 || IsHexagon || IsLoongArch64 || IsRISCV64)
814     Res |= SanitizerKind::Scudo;
815   if (IsX86_64 || IsAArch64 || IsRISCV64) {
816     Res |= SanitizerKind::HWAddress;
817   }
818   if (IsX86_64 || IsAArch64) {
819     Res |= SanitizerKind::KernelHWAddress;
820   }
821   // Work around "Cannot represent a difference across sections".
822   if (getTriple().getArch() == llvm::Triple::ppc64)
823     Res &= ~SanitizerKind::Function;
824   return Res;
825 }
826 
827 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
828                              llvm::opt::ArgStringList &CmdArgs) const {
829   // Add linker option -u__llvm_profile_runtime to cause runtime
830   // initialization module to be linked in.
831   if (needsProfileRT(Args))
832     CmdArgs.push_back(Args.MakeArgString(
833         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
834   ToolChain::addProfileRTLibs(Args, CmdArgs);
835 }
836 
837 llvm::DenormalMode
838 Linux::getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs,
839                                      const JobAction &JA,
840                                      const llvm::fltSemantics *FPType) const {
841   switch (getTriple().getArch()) {
842   case llvm::Triple::x86:
843   case llvm::Triple::x86_64: {
844     std::string Unused;
845     // DAZ and FTZ are turned on in crtfastmath.o
846     if (!DriverArgs.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
847         isFastMathRuntimeAvailable(DriverArgs, Unused))
848       return llvm::DenormalMode::getPreserveSign();
849     return llvm::DenormalMode::getIEEE();
850   }
851   default:
852     return llvm::DenormalMode::getIEEE();
853   }
854 }
855 
856 void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
857   for (const auto &Opt : ExtraOpts)
858     CmdArgs.push_back(Opt.c_str());
859 }
860 
861 const char *Linux::getDefaultLinker() const {
862   if (getTriple().isAndroid())
863     return "ld.lld";
864   return Generic_ELF::getDefaultLinker();
865 }
866