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