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