xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Linux.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 
425     return "/lib/ld-musl-" + ArchName + ".so.1";
426   }
427 
428   std::string LibDir;
429   std::string Loader;
430 
431   switch (Arch) {
432   default:
433     llvm_unreachable("unsupported architecture");
434 
435   case llvm::Triple::aarch64:
436     LibDir = "lib";
437     Loader = "ld-linux-aarch64.so.1";
438     break;
439   case llvm::Triple::aarch64_be:
440     LibDir = "lib";
441     Loader = "ld-linux-aarch64_be.so.1";
442     break;
443   case llvm::Triple::arm:
444   case llvm::Triple::thumb:
445   case llvm::Triple::armeb:
446   case llvm::Triple::thumbeb: {
447     const bool HF =
448         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
449         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
450 
451     LibDir = "lib";
452     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
453     break;
454   }
455   case llvm::Triple::m68k:
456     LibDir = "lib";
457     Loader = "ld.so.1";
458     break;
459   case llvm::Triple::mips:
460   case llvm::Triple::mipsel:
461   case llvm::Triple::mips64:
462   case llvm::Triple::mips64el: {
463     bool IsNaN2008 = tools::mips::isNaN2008(getDriver(), Args, Triple);
464 
465     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
466 
467     if (tools::mips::isUCLibc(Args))
468       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
469     else if (!Triple.hasEnvironment() &&
470              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
471       Loader =
472           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
473     else
474       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
475 
476     break;
477   }
478   case llvm::Triple::ppc:
479     LibDir = "lib";
480     Loader = "ld.so.1";
481     break;
482   case llvm::Triple::ppcle:
483     LibDir = "lib";
484     Loader = "ld.so.1";
485     break;
486   case llvm::Triple::ppc64:
487     LibDir = "lib64";
488     Loader =
489         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
490     break;
491   case llvm::Triple::ppc64le:
492     LibDir = "lib64";
493     Loader =
494         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
495     break;
496   case llvm::Triple::riscv32: {
497     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
498     LibDir = "lib";
499     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
500     break;
501   }
502   case llvm::Triple::riscv64: {
503     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
504     LibDir = "lib";
505     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
506     break;
507   }
508   case llvm::Triple::sparc:
509   case llvm::Triple::sparcel:
510     LibDir = "lib";
511     Loader = "ld-linux.so.2";
512     break;
513   case llvm::Triple::sparcv9:
514     LibDir = "lib64";
515     Loader = "ld-linux.so.2";
516     break;
517   case llvm::Triple::systemz:
518     LibDir = "lib";
519     Loader = "ld64.so.1";
520     break;
521   case llvm::Triple::x86:
522     LibDir = "lib";
523     Loader = "ld-linux.so.2";
524     break;
525   case llvm::Triple::x86_64: {
526     bool X32 = Triple.isX32();
527 
528     LibDir = X32 ? "libx32" : "lib64";
529     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
530     break;
531   }
532   case llvm::Triple::ve:
533     return "/opt/nec/ve/lib/ld-linux-ve.so.1";
534   }
535 
536   if (Distro == Distro::Exherbo &&
537       (Triple.getVendor() == llvm::Triple::UnknownVendor ||
538        Triple.getVendor() == llvm::Triple::PC))
539     return "/usr/" + Triple.str() + "/lib/" + Loader;
540   return "/" + LibDir + "/" + Loader;
541 }
542 
543 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
544                                       ArgStringList &CC1Args) const {
545   const Driver &D = getDriver();
546   std::string SysRoot = computeSysRoot();
547 
548   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
549     return;
550 
551   // Add 'include' in the resource directory, which is similar to
552   // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
553   // contains some files conflicting with system /usr/include. musl systems
554   // prefer the /usr/include copies which are more relevant.
555   SmallString<128> ResourceDirInclude(D.ResourceDir);
556   llvm::sys::path::append(ResourceDirInclude, "include");
557   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) &&
558       (!getTriple().isMusl() || DriverArgs.hasArg(options::OPT_nostdlibinc)))
559     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
560 
561   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
562     return;
563 
564   // LOCAL_INCLUDE_DIR
565   addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
566   // TOOL_INCLUDE_DIR
567   AddMultilibIncludeArgs(DriverArgs, CC1Args);
568 
569   // Check for configure-time C include directories.
570   StringRef CIncludeDirs(C_INCLUDE_DIRS);
571   if (CIncludeDirs != "") {
572     SmallVector<StringRef, 5> dirs;
573     CIncludeDirs.split(dirs, ":");
574     for (StringRef dir : dirs) {
575       StringRef Prefix =
576           llvm::sys::path::is_absolute(dir) ? "" : StringRef(SysRoot);
577       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
578     }
579     return;
580   }
581 
582   // On systems using multiarch and Android, add /usr/include/$triple before
583   // /usr/include.
584   std::string MultiarchIncludeDir = getMultiarchTriple(D, getTriple(), SysRoot);
585   if (!MultiarchIncludeDir.empty() &&
586       D.getVFS().exists(SysRoot + "/usr/include/" + MultiarchIncludeDir))
587     addExternCSystemInclude(DriverArgs, CC1Args,
588                             SysRoot + "/usr/include/" + MultiarchIncludeDir);
589 
590   if (getTriple().getOS() == llvm::Triple::RTEMS)
591     return;
592 
593   // Add an include of '/include' directly. This isn't provided by default by
594   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
595   // add even when Clang is acting as-if it were a system compiler.
596   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
597 
598   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
599 
600   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
601     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
602 }
603 
604 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
605                                      llvm::opt::ArgStringList &CC1Args) const {
606   // We need a detected GCC installation on Linux to provide libstdc++'s
607   // headers in odd Linuxish places.
608   if (!GCCInstallation.isValid())
609     return;
610 
611   // Detect Debian g++-multiarch-incdir.diff.
612   StringRef TripleStr = GCCInstallation.getTriple().str();
613   StringRef DebianMultiarch =
614       GCCInstallation.getTriple().getArch() == llvm::Triple::x86
615           ? "i386-linux-gnu"
616           : TripleStr;
617 
618   // Try generic GCC detection first.
619   if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
620                                                DebianMultiarch))
621     return;
622 
623   StringRef LibDir = GCCInstallation.getParentLibPath();
624   const Multilib &Multilib = GCCInstallation.getMultilib();
625   const GCCVersion &Version = GCCInstallation.getVersion();
626 
627   const std::string LibStdCXXIncludePathCandidates[] = {
628       // Android standalone toolchain has C++ headers in yet another place.
629       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
630       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
631       // without a subdirectory corresponding to the gcc version.
632       LibDir.str() + "/../include/c++",
633       // Cray's gcc installation puts headers under "g++" without a
634       // version suffix.
635       LibDir.str() + "/../include/g++",
636   };
637 
638   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
639     if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
640                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
641       break;
642   }
643 }
644 
645 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
646                                ArgStringList &CC1Args) const {
647   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
648 }
649 
650 void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
651                               ArgStringList &CC1Args) const {
652   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
653 }
654 
655 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
656                                 ArgStringList &CC1Args) const {
657   if (GCCInstallation.isValid()) {
658     CC1Args.push_back("-isystem");
659     CC1Args.push_back(DriverArgs.MakeArgString(
660         GCCInstallation.getParentLibPath() + "/../" +
661         GCCInstallation.getTriple().str() + "/include"));
662   }
663 }
664 
665 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
666   return getTriple().isAndroid() || getTriple().isMusl() ||
667          getSanitizerArgs(Args).requiresPIE();
668 }
669 
670 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
671   // Outline atomics for AArch64 are supported by compiler-rt
672   // and libgcc since 9.3.1
673   assert(getTriple().isAArch64() && "expected AArch64 target!");
674   ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
675   if (RtLib == ToolChain::RLT_CompilerRT)
676     return true;
677   assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
678   if (GCCInstallation.getVersion().isOlderThan(9, 3, 1))
679     return false;
680   return true;
681 }
682 
683 bool Linux::IsMathErrnoDefault() const {
684   if (getTriple().isAndroid())
685     return false;
686   return Generic_ELF::IsMathErrnoDefault();
687 }
688 
689 SanitizerMask Linux::getSupportedSanitizers() const {
690   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
691   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
692   const bool IsMIPS = getTriple().isMIPS32();
693   const bool IsMIPS64 = getTriple().isMIPS64();
694   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
695                            getTriple().getArch() == llvm::Triple::ppc64le;
696   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
697                          getTriple().getArch() == llvm::Triple::aarch64_be;
698   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
699                          getTriple().getArch() == llvm::Triple::thumb ||
700                          getTriple().getArch() == llvm::Triple::armeb ||
701                          getTriple().getArch() == llvm::Triple::thumbeb;
702   const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
703   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
704   const bool IsHexagon = getTriple().getArch() == llvm::Triple::hexagon;
705   SanitizerMask Res = ToolChain::getSupportedSanitizers();
706   Res |= SanitizerKind::Address;
707   Res |= SanitizerKind::PointerCompare;
708   Res |= SanitizerKind::PointerSubtract;
709   Res |= SanitizerKind::Fuzzer;
710   Res |= SanitizerKind::FuzzerNoLink;
711   Res |= SanitizerKind::KernelAddress;
712   Res |= SanitizerKind::Memory;
713   Res |= SanitizerKind::Vptr;
714   Res |= SanitizerKind::SafeStack;
715   if (IsX86_64 || IsMIPS64 || IsAArch64)
716     Res |= SanitizerKind::DataFlow;
717   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
718       IsRISCV64 || IsSystemZ || IsHexagon)
719     Res |= SanitizerKind::Leak;
720   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ)
721     Res |= SanitizerKind::Thread;
722   if (IsX86_64)
723     Res |= SanitizerKind::KernelMemory;
724   if (IsX86 || IsX86_64)
725     Res |= SanitizerKind::Function;
726   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
727       IsPowerPC64 || IsHexagon)
728     Res |= SanitizerKind::Scudo;
729   if (IsX86_64 || IsAArch64) {
730     Res |= SanitizerKind::HWAddress;
731     Res |= SanitizerKind::KernelHWAddress;
732   }
733   return Res;
734 }
735 
736 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
737                              llvm::opt::ArgStringList &CmdArgs) const {
738   // Add linker option -u__llvm_profile_runtime to cause runtime
739   // initialization module to be linked in.
740   if (needsProfileRT(Args))
741     CmdArgs.push_back(Args.MakeArgString(
742         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
743   ToolChain::addProfileRTLibs(Args, CmdArgs);
744 }
745 
746 llvm::DenormalMode
747 Linux::getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs,
748                                      const JobAction &JA,
749                                      const llvm::fltSemantics *FPType) const {
750   switch (getTriple().getArch()) {
751   case llvm::Triple::x86:
752   case llvm::Triple::x86_64: {
753     std::string Unused;
754     // DAZ and FTZ are turned on in crtfastmath.o
755     if (!DriverArgs.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
756         isFastMathRuntimeAvailable(DriverArgs, Unused))
757       return llvm::DenormalMode::getPreserveSign();
758     return llvm::DenormalMode::getIEEE();
759   }
760   default:
761     return llvm::DenormalMode::getIEEE();
762   }
763 }
764 
765 void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
766   for (const auto &Opt : ExtraOpts)
767     CmdArgs.push_back(Opt.c_str());
768 }
769