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