]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains/Linux.cpp
Merge clang trunk r351319, resolve conflicts, and update FREEBSD-Xlist.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Driver / ToolChains / Linux.cpp
1 //===--- Linux.h - Linux ToolChain Implementations --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Linux.h"
11 #include "Arch/ARM.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "CommonArgs.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Distro.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/ProfileData/InstrProf.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <system_error>
27
28 using namespace clang::driver;
29 using namespace clang::driver::toolchains;
30 using namespace clang;
31 using namespace llvm::opt;
32
33 using tools::addPathIfExists;
34
35 /// Get our best guess at the multiarch triple for a target.
36 ///
37 /// Debian-based systems are starting to use a multiarch setup where they use
38 /// a target-triple directory in the library and header search paths.
39 /// Unfortunately, this triple does not align with the vanilla target triple,
40 /// so we provide a rough mapping here.
41 static std::string getMultiarchTriple(const Driver &D,
42                                       const llvm::Triple &TargetTriple,
43                                       StringRef SysRoot) {
44   llvm::Triple::EnvironmentType TargetEnvironment =
45       TargetTriple.getEnvironment();
46   bool IsAndroid = TargetTriple.isAndroid();
47   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
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 Arch = IsMipsR6 ? "mipsisa32r6" : "mips";
107     if (D.getVFS().exists(SysRoot + "/lib/" + Arch + "-linux-gnu"))
108       return Arch + "-linux-gnu";
109     break;
110   }
111   case llvm::Triple::mipsel: {
112     if (IsAndroid)
113       return "mipsel-linux-android";
114     std::string Arch = IsMipsR6 ? "mipsisa32r6el" : "mipsel";
115     if (D.getVFS().exists(SysRoot + "/lib/" + Arch + "-linux-gnu"))
116       return Arch + "-linux-gnu";
117     break;
118   }
119   case llvm::Triple::mips64: {
120     std::string Arch = IsMipsR6 ? "mipsisa64r6" : "mips64";
121     std::string ABI = llvm::Triple::getEnvironmentTypeName(TargetEnvironment);
122     if (D.getVFS().exists(SysRoot + "/lib/" + Arch + "-linux-" + ABI))
123       return Arch + "-linux-" + ABI;
124     break;
125   }
126   case llvm::Triple::mips64el: {
127     if (IsAndroid)
128       return "mips64el-linux-android";
129     std::string Arch = IsMipsR6 ? "mipsisa64r6el" : "mips64el";
130     std::string ABI = llvm::Triple::getEnvironmentTypeName(TargetEnvironment);
131     if (D.getVFS().exists(SysRoot + "/lib/" + Arch + "-linux-" + ABI))
132       return Arch + "-linux-" + ABI;
133     break;
134   }
135   case llvm::Triple::ppc:
136     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
137       return "powerpc-linux-gnuspe";
138     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
139       return "powerpc-linux-gnu";
140     break;
141   case llvm::Triple::ppc64:
142     if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
143       return "powerpc64-linux-gnu";
144     break;
145   case llvm::Triple::ppc64le:
146     if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
147       return "powerpc64le-linux-gnu";
148     break;
149   case llvm::Triple::sparc:
150     if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
151       return "sparc-linux-gnu";
152     break;
153   case llvm::Triple::sparcv9:
154     if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
155       return "sparc64-linux-gnu";
156     break;
157   case llvm::Triple::systemz:
158     if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
159       return "s390x-linux-gnu";
160     break;
161   }
162   return TargetTriple.str();
163 }
164
165 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
166   if (Triple.isMIPS()) {
167     if (Triple.isAndroid()) {
168       StringRef CPUName;
169       StringRef ABIName;
170       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
171       if (CPUName == "mips32r6")
172         return "libr6";
173       if (CPUName == "mips32r2")
174         return "libr2";
175     }
176     // lib32 directory has a special meaning on MIPS targets.
177     // It contains N32 ABI binaries. Use this folder if produce
178     // code for N32 ABI only.
179     if (tools::mips::hasMipsAbiArg(Args, "n32"))
180       return "lib32";
181     return Triple.isArch32Bit() ? "lib" : "lib64";
182   }
183
184   // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
185   // using that variant while targeting other architectures causes problems
186   // because the libraries are laid out in shared system roots that can't cope
187   // with a 'lib32' library search path being considered. So we only enable
188   // them when we know we may need it.
189   //
190   // FIXME: This is a bit of a hack. We should really unify this code for
191   // reasoning about oslibdir spellings with the lib dir spellings in the
192   // GCCInstallationDetector, but that is a more significant refactoring.
193   if (Triple.getArch() == llvm::Triple::x86 ||
194       Triple.getArch() == llvm::Triple::ppc)
195     return "lib32";
196
197   if (Triple.getArch() == llvm::Triple::x86_64 &&
198       Triple.getEnvironment() == llvm::Triple::GNUX32)
199     return "libx32";
200
201   if (Triple.getArch() == llvm::Triple::riscv32)
202     return "lib32";
203
204   return Triple.isArch32Bit() ? "lib" : "lib64";
205 }
206
207 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
208                                   const Multilib &Multilib,
209                                   StringRef InstallPath,
210                                   ToolChain::path_list &Paths) {
211   if (const auto &PathsCallback = Multilibs.filePathsCallback())
212     for (const auto &Path : PathsCallback(Multilib))
213       addPathIfExists(D, InstallPath + Path, Paths);
214 }
215
216 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
217     : Generic_ELF(D, Triple, Args) {
218   GCCInstallation.init(Triple, Args);
219   Multilibs = GCCInstallation.getMultilibs();
220   SelectedMultilib = GCCInstallation.getMultilib();
221   llvm::Triple::ArchType Arch = Triple.getArch();
222   std::string SysRoot = computeSysRoot();
223
224   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
225   // least) put various tools in a triple-prefixed directory off of the parent
226   // of the GCC installation. We use the GCC triple here to ensure that we end
227   // up with tools that support the same amount of cross compiling as the
228   // detected GCC installation. For example, if we find a GCC installation
229   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
230   // used to target i386.
231   // FIXME: This seems unlikely to be Linux-specific.
232   ToolChain::path_list &PPaths = getProgramPaths();
233   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
234                          GCCInstallation.getTriple().str() + "/bin")
235                        .str());
236
237   Distro Distro(D.getVFS());
238
239   if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
240     ExtraOpts.push_back("-z");
241     ExtraOpts.push_back("now");
242   }
243
244   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
245       Triple.isAndroid()) {
246     ExtraOpts.push_back("-z");
247     ExtraOpts.push_back("relro");
248   }
249
250   // The lld default page size is too large for Aarch64, which produces much
251   // larger .so files and images for arm64 device targets. Use 4KB page size
252   // for Android arm64 targets instead.
253   if (Triple.isAArch64() && Triple.isAndroid()) {
254     ExtraOpts.push_back("-z");
255     ExtraOpts.push_back("max-page-size=4096");
256   }
257
258   if (GCCInstallation.getParentLibPath().find("opt/rh/devtoolset") !=
259       StringRef::npos)
260     // With devtoolset on RHEL, we want to add a bin directory that is relative
261     // to the detected gcc install, because if we are using devtoolset gcc then
262     // we want to use other tools from devtoolset (e.g. ld) instead of the
263     // standard system tools.
264     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
265                      "/../bin").str());
266
267   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
268     ExtraOpts.push_back("-X");
269
270   const bool IsAndroid = Triple.isAndroid();
271   const bool IsMips = Triple.isMIPS();
272   const bool IsHexagon = Arch == llvm::Triple::hexagon;
273   const bool IsRISCV =
274       Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64;
275
276   if (IsMips && !SysRoot.empty())
277     ExtraOpts.push_back("--sysroot=" + SysRoot);
278
279   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
280   // and the MIPS ABI require .dynsym to be sorted in different ways.
281   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
282   // ABI requires a mapping between the GOT and the symbol table.
283   // Android loader does not support .gnu.hash until API 23.
284   // Hexagon linker/loader does not support .gnu.hash
285   if (!IsMips && !IsHexagon) {
286     if (Distro.IsRedhat() || Distro.IsOpenSUSE() || Distro.IsAlpineLinux() ||
287         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick) ||
288         (IsAndroid && !Triple.isAndroidVersionLT(23)))
289       ExtraOpts.push_back("--hash-style=gnu");
290
291     if (Distro.IsDebian() || Distro.IsOpenSUSE() ||
292         Distro == Distro::UbuntuLucid || Distro == Distro::UbuntuJaunty ||
293         Distro == Distro::UbuntuKarmic ||
294         (IsAndroid && Triple.isAndroidVersionLT(23)))
295       ExtraOpts.push_back("--hash-style=both");
296   }
297
298   if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6)
299     ExtraOpts.push_back("--no-add-needed");
300
301 #ifdef ENABLE_LINKER_BUILD_ID
302   ExtraOpts.push_back("--build-id");
303 #endif
304
305   if (IsAndroid || Distro.IsOpenSUSE())
306     ExtraOpts.push_back("--enable-new-dtags");
307
308   // The selection of paths to try here is designed to match the patterns which
309   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
310   // This was determined by running GCC in a fake filesystem, creating all
311   // possible permutations of these directories, and seeing which ones it added
312   // to the link paths.
313   path_list &Paths = getFilePaths();
314
315   const std::string OSLibDir = getOSLibDir(Triple, Args);
316   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
317
318   // Add the multilib suffixed paths where they are available.
319   if (GCCInstallation.isValid()) {
320     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
321     const std::string &LibPath = GCCInstallation.getParentLibPath();
322
323     // Add toolchain / multilib specific file paths.
324     addMultilibsFilePaths(D, Multilibs, SelectedMultilib,
325                           GCCInstallation.getInstallPath(), Paths);
326
327     // Sourcery CodeBench MIPS toolchain holds some libraries under
328     // a biarch-like suffix of the GCC installation.
329     addPathIfExists(D, GCCInstallation.getInstallPath() + SelectedMultilib.gccSuffix(),
330                     Paths);
331
332     // GCC cross compiling toolchains will install target libraries which ship
333     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
334     // any part of the GCC installation in
335     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
336     // debatable, but is the reality today. We need to search this tree even
337     // when we have a sysroot somewhere else. It is the responsibility of
338     // whomever is doing the cross build targeting a sysroot using a GCC
339     // installation that is *not* within the system root to ensure two things:
340     //
341     //  1) Any DSOs that are linked in from this tree or from the install path
342     //     above must be present on the system root and found via an
343     //     appropriate rpath.
344     //  2) There must not be libraries installed into
345     //     <prefix>/<triple>/<libdir> unless they should be preferred over
346     //     those within the system root.
347     //
348     // Note that this matches the GCC behavior. See the below comment for where
349     // Clang diverges from GCC's behavior.
350     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
351                            OSLibDir + SelectedMultilib.osSuffix(),
352                     Paths);
353
354     // If the GCC installation we found is inside of the sysroot, we want to
355     // prefer libraries installed in the parent prefix of the GCC installation.
356     // It is important to *not* use these paths when the GCC installation is
357     // outside of the system root as that can pick up unintended libraries.
358     // This usually happens when there is an external cross compiler on the
359     // host system, and a more minimal sysroot available that is the target of
360     // the cross. Note that GCC does include some of these directories in some
361     // configurations but this seems somewhere between questionable and simply
362     // a bug.
363     if (StringRef(LibPath).startswith(SysRoot)) {
364       addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
365       addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
366     }
367   }
368
369   // Similar to the logic for GCC above, if we currently running Clang inside
370   // of the requested system root, add its parent library paths to
371   // those searched.
372   // FIXME: It's not clear whether we should use the driver's installed
373   // directory ('Dir' below) or the ResourceDir.
374   if (StringRef(D.Dir).startswith(SysRoot)) {
375     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
376     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
377   }
378
379   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
380   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
381
382   if (IsAndroid) {
383     // Android sysroots contain a library directory for each supported OS
384     // version as well as some unversioned libraries in the usual multiarch
385     // directory.
386     unsigned Major;
387     unsigned Minor;
388     unsigned Micro;
389     Triple.getEnvironmentVersion(Major, Minor, Micro);
390     addPathIfExists(D,
391                     SysRoot + "/usr/lib/" + MultiarchTriple + "/" +
392                         llvm::to_string(Major),
393                     Paths);
394   }
395
396   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
397   // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
398   // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
399   // this here.
400   if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
401       Triple.isArch64Bit())
402     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir, Paths);
403   else
404     addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
405   if (IsRISCV) {
406     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
407     addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths);
408     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir + "/" + ABIName, Paths);
409   }
410
411   // Try walking via the GCC triple path in case of biarch or multiarch GCC
412   // installations with strange symlinks.
413   if (GCCInstallation.isValid()) {
414     addPathIfExists(D,
415                     SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
416                         "/../../" + OSLibDir,
417                     Paths);
418
419     // Add the 'other' biarch variant path
420     Multilib BiarchSibling;
421     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
422       addPathIfExists(D, GCCInstallation.getInstallPath() +
423                              BiarchSibling.gccSuffix(),
424                       Paths);
425     }
426
427     // See comments above on the multilib variant for details of why this is
428     // included even from outside the sysroot.
429     const std::string &LibPath = GCCInstallation.getParentLibPath();
430     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
431     const Multilib &Multilib = GCCInstallation.getMultilib();
432     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
433                            Multilib.osSuffix(),
434                     Paths);
435
436     // See comments above on the multilib variant for details of why this is
437     // only included from within the sysroot.
438     if (StringRef(LibPath).startswith(SysRoot))
439       addPathIfExists(D, LibPath, Paths);
440   }
441
442   // Similar to the logic for GCC above, if we are currently running Clang
443   // inside of the requested system root, add its parent library path to those
444   // searched.
445   // FIXME: It's not clear whether we should use the driver's installed
446   // directory ('Dir' below) or the ResourceDir.
447   if (StringRef(D.Dir).startswith(SysRoot))
448     addPathIfExists(D, D.Dir + "/../lib", Paths);
449
450   addPathIfExists(D, SysRoot + "/lib", Paths);
451   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
452 }
453
454 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
455   if (getTriple().isAndroid())
456     return ToolChain::CST_Libcxx;
457   return ToolChain::CST_Libstdcxx;
458 }
459
460 bool Linux::HasNativeLLVMSupport() const { return true; }
461
462 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
463
464 Tool *Linux::buildAssembler() const {
465   return new tools::gnutools::Assembler(*this);
466 }
467
468 std::string Linux::computeSysRoot() const {
469   if (!getDriver().SysRoot.empty())
470     return getDriver().SysRoot;
471
472   if (getTriple().isAndroid()) {
473     // Android toolchains typically include a sysroot at ../sysroot relative to
474     // the clang binary.
475     const StringRef ClangDir = getDriver().getInstalledDir();
476     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
477     if (getVFS().exists(AndroidSysRootPath))
478       return AndroidSysRootPath;
479   }
480
481   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
482     return std::string();
483
484   // Standalone MIPS toolchains use different names for sysroot folder
485   // and put it into different places. Here we try to check some known
486   // variants.
487
488   const StringRef InstallDir = GCCInstallation.getInstallPath();
489   const StringRef TripleStr = GCCInstallation.getTriple().str();
490   const Multilib &Multilib = GCCInstallation.getMultilib();
491
492   std::string Path =
493       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
494           .str();
495
496   if (getVFS().exists(Path))
497     return Path;
498
499   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
500
501   if (getVFS().exists(Path))
502     return Path;
503
504   return std::string();
505 }
506
507 std::string Linux::getDynamicLinker(const ArgList &Args) const {
508   const llvm::Triple::ArchType Arch = getArch();
509   const llvm::Triple &Triple = getTriple();
510
511   const Distro Distro(getDriver().getVFS());
512
513   if (Triple.isAndroid())
514     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
515
516   if (Triple.isMusl()) {
517     std::string ArchName;
518     bool IsArm = false;
519
520     switch (Arch) {
521     case llvm::Triple::arm:
522     case llvm::Triple::thumb:
523       ArchName = "arm";
524       IsArm = true;
525       break;
526     case llvm::Triple::armeb:
527     case llvm::Triple::thumbeb:
528       ArchName = "armeb";
529       IsArm = true;
530       break;
531     default:
532       ArchName = Triple.getArchName().str();
533     }
534     if (IsArm &&
535         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
536          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
537       ArchName += "hf";
538
539     return "/lib/ld-musl-" + ArchName + ".so.1";
540   }
541
542   std::string LibDir;
543   std::string Loader;
544
545   switch (Arch) {
546   default:
547     llvm_unreachable("unsupported architecture");
548
549   case llvm::Triple::aarch64:
550     LibDir = "lib";
551     Loader = "ld-linux-aarch64.so.1";
552     break;
553   case llvm::Triple::aarch64_be:
554     LibDir = "lib";
555     Loader = "ld-linux-aarch64_be.so.1";
556     break;
557   case llvm::Triple::arm:
558   case llvm::Triple::thumb:
559   case llvm::Triple::armeb:
560   case llvm::Triple::thumbeb: {
561     const bool HF =
562         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
563         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
564
565     LibDir = "lib";
566     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
567     break;
568   }
569   case llvm::Triple::mips:
570   case llvm::Triple::mipsel:
571   case llvm::Triple::mips64:
572   case llvm::Triple::mips64el: {
573     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
574
575     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
576
577     if (tools::mips::isUCLibc(Args))
578       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
579     else if (!Triple.hasEnvironment() &&
580              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
581       Loader =
582           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
583     else
584       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
585
586     break;
587   }
588   case llvm::Triple::ppc:
589     LibDir = "lib";
590     Loader = "ld.so.1";
591     break;
592   case llvm::Triple::ppc64:
593     LibDir = "lib64";
594     Loader =
595         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
596     break;
597   case llvm::Triple::ppc64le:
598     LibDir = "lib64";
599     Loader =
600         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
601     break;
602   case llvm::Triple::riscv32: {
603     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
604     LibDir = "lib";
605     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
606     break;
607   }
608   case llvm::Triple::riscv64: {
609     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
610     LibDir = "lib";
611     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
612     break;
613   }
614   case llvm::Triple::sparc:
615   case llvm::Triple::sparcel:
616     LibDir = "lib";
617     Loader = "ld-linux.so.2";
618     break;
619   case llvm::Triple::sparcv9:
620     LibDir = "lib64";
621     Loader = "ld-linux.so.2";
622     break;
623   case llvm::Triple::systemz:
624     LibDir = "lib";
625     Loader = "ld64.so.1";
626     break;
627   case llvm::Triple::x86:
628     LibDir = "lib";
629     Loader = "ld-linux.so.2";
630     break;
631   case llvm::Triple::x86_64: {
632     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
633
634     LibDir = X32 ? "libx32" : "lib64";
635     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
636     break;
637   }
638   }
639
640   if (Distro == Distro::Exherbo && (Triple.getVendor() == llvm::Triple::UnknownVendor ||
641                                     Triple.getVendor() == llvm::Triple::PC))
642     return "/usr/" + Triple.str() + "/lib/" + Loader;
643   return "/" + LibDir + "/" + Loader;
644 }
645
646 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
647                                       ArgStringList &CC1Args) const {
648   const Driver &D = getDriver();
649   std::string SysRoot = computeSysRoot();
650
651   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
652     return;
653
654   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
655     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
656
657   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
658     SmallString<128> P(D.ResourceDir);
659     llvm::sys::path::append(P, "include");
660     addSystemInclude(DriverArgs, CC1Args, P);
661   }
662
663   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
664     return;
665
666   // Check for configure-time C include directories.
667   StringRef CIncludeDirs(C_INCLUDE_DIRS);
668   if (CIncludeDirs != "") {
669     SmallVector<StringRef, 5> dirs;
670     CIncludeDirs.split(dirs, ":");
671     for (StringRef dir : dirs) {
672       StringRef Prefix =
673           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
674       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
675     }
676     return;
677   }
678
679   // Lacking those, try to detect the correct set of system includes for the
680   // target triple.
681
682   // Add include directories specific to the selected multilib set and multilib.
683   if (GCCInstallation.isValid()) {
684     const auto &Callback = Multilibs.includeDirsCallback();
685     if (Callback) {
686       for (const auto &Path : Callback(GCCInstallation.getMultilib()))
687         addExternCSystemIncludeIfExists(
688             DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
689     }
690   }
691
692   // Implement generic Debian multiarch support.
693   const StringRef X86_64MultiarchIncludeDirs[] = {
694       "/usr/include/x86_64-linux-gnu",
695
696       // FIXME: These are older forms of multiarch. It's not clear that they're
697       // in use in any released version of Debian, so we should consider
698       // removing them.
699       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
700   const StringRef X86MultiarchIncludeDirs[] = {
701       "/usr/include/i386-linux-gnu",
702
703       // FIXME: These are older forms of multiarch. It's not clear that they're
704       // in use in any released version of Debian, so we should consider
705       // removing them.
706       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
707       "/usr/include/i486-linux-gnu"};
708   const StringRef AArch64MultiarchIncludeDirs[] = {
709       "/usr/include/aarch64-linux-gnu"};
710   const StringRef ARMMultiarchIncludeDirs[] = {
711       "/usr/include/arm-linux-gnueabi"};
712   const StringRef ARMHFMultiarchIncludeDirs[] = {
713       "/usr/include/arm-linux-gnueabihf"};
714   const StringRef ARMEBMultiarchIncludeDirs[] = {
715       "/usr/include/armeb-linux-gnueabi"};
716   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
717       "/usr/include/armeb-linux-gnueabihf"};
718   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
719   const StringRef MIPSELMultiarchIncludeDirs[] = {
720       "/usr/include/mipsel-linux-gnu"};
721   const StringRef MIPS64MultiarchIncludeDirs[] = {
722       "/usr/include/mips64-linux-gnuabi64"};
723   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
724       "/usr/include/mips64el-linux-gnuabi64"};
725   const StringRef MIPSN32MultiarchIncludeDirs[] = {
726       "/usr/include/mips64-linux-gnuabin32"};
727   const StringRef MIPSN32ELMultiarchIncludeDirs[] = {
728       "/usr/include/mips64el-linux-gnuabin32"};
729   const StringRef MIPSR6MultiarchIncludeDirs[] = {
730       "/usr/include/mipsisa32-linux-gnu"};
731   const StringRef MIPSR6ELMultiarchIncludeDirs[] = {
732       "/usr/include/mipsisa32r6el-linux-gnu"};
733   const StringRef MIPS64R6MultiarchIncludeDirs[] = {
734       "/usr/include/mipsisa64r6-linux-gnuabi64"};
735   const StringRef MIPS64R6ELMultiarchIncludeDirs[] = {
736       "/usr/include/mipsisa64r6el-linux-gnuabi64"};
737   const StringRef MIPSN32R6MultiarchIncludeDirs[] = {
738       "/usr/include/mipsisa64r6-linux-gnuabin32"};
739   const StringRef MIPSN32R6ELMultiarchIncludeDirs[] = {
740       "/usr/include/mipsisa64r6el-linux-gnuabin32"};
741   const StringRef PPCMultiarchIncludeDirs[] = {
742       "/usr/include/powerpc-linux-gnu",
743       "/usr/include/powerpc-linux-gnuspe"};
744   const StringRef PPC64MultiarchIncludeDirs[] = {
745       "/usr/include/powerpc64-linux-gnu"};
746   const StringRef PPC64LEMultiarchIncludeDirs[] = {
747       "/usr/include/powerpc64le-linux-gnu"};
748   const StringRef SparcMultiarchIncludeDirs[] = {
749       "/usr/include/sparc-linux-gnu"};
750   const StringRef Sparc64MultiarchIncludeDirs[] = {
751       "/usr/include/sparc64-linux-gnu"};
752   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
753       "/usr/include/s390x-linux-gnu"};
754   ArrayRef<StringRef> MultiarchIncludeDirs;
755   switch (getTriple().getArch()) {
756   case llvm::Triple::x86_64:
757     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
758     break;
759   case llvm::Triple::x86:
760     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
761     break;
762   case llvm::Triple::aarch64:
763   case llvm::Triple::aarch64_be:
764     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
765     break;
766   case llvm::Triple::arm:
767   case llvm::Triple::thumb:
768     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
769       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
770     else
771       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
772     break;
773   case llvm::Triple::armeb:
774   case llvm::Triple::thumbeb:
775     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
776       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
777     else
778       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
779     break;
780   case llvm::Triple::mips:
781     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
782       MultiarchIncludeDirs = MIPSR6MultiarchIncludeDirs;
783     else
784       MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
785     break;
786   case llvm::Triple::mipsel:
787     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
788       MultiarchIncludeDirs = MIPSR6ELMultiarchIncludeDirs;
789     else
790       MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
791     break;
792   case llvm::Triple::mips64:
793     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
794       if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
795         MultiarchIncludeDirs = MIPSN32R6MultiarchIncludeDirs;
796       else
797         MultiarchIncludeDirs = MIPS64R6MultiarchIncludeDirs;
798     else if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
799       MultiarchIncludeDirs = MIPSN32MultiarchIncludeDirs;
800     else
801       MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
802     break;
803   case llvm::Triple::mips64el:
804     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
805       if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
806         MultiarchIncludeDirs = MIPSN32R6ELMultiarchIncludeDirs;
807       else
808         MultiarchIncludeDirs = MIPS64R6ELMultiarchIncludeDirs;
809     else if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
810       MultiarchIncludeDirs = MIPSN32ELMultiarchIncludeDirs;
811     else
812       MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
813     break;
814   case llvm::Triple::ppc:
815     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
816     break;
817   case llvm::Triple::ppc64:
818     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
819     break;
820   case llvm::Triple::ppc64le:
821     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
822     break;
823   case llvm::Triple::sparc:
824     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
825     break;
826   case llvm::Triple::sparcv9:
827     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
828     break;
829   case llvm::Triple::systemz:
830     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
831     break;
832   default:
833     break;
834   }
835
836   const std::string AndroidMultiarchIncludeDir =
837       std::string("/usr/include/") +
838       getMultiarchTriple(D, getTriple(), SysRoot);
839   const StringRef AndroidMultiarchIncludeDirs[] = {AndroidMultiarchIncludeDir};
840   if (getTriple().isAndroid())
841     MultiarchIncludeDirs = AndroidMultiarchIncludeDirs;
842
843   for (StringRef Dir : MultiarchIncludeDirs) {
844     if (D.getVFS().exists(SysRoot + Dir)) {
845       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
846       break;
847     }
848   }
849
850   if (getTriple().getOS() == llvm::Triple::RTEMS)
851     return;
852
853   // Add an include of '/include' directly. This isn't provided by default by
854   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
855   // add even when Clang is acting as-if it were a system compiler.
856   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
857
858   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
859 }
860
861 static std::string DetectLibcxxIncludePath(StringRef base) {
862   std::error_code EC;
863   int MaxVersion = 0;
864   std::string MaxVersionString = "";
865   for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
866        LI = LI.increment(EC)) {
867     StringRef VersionText = llvm::sys::path::filename(LI->path());
868     int Version;
869     if (VersionText[0] == 'v' &&
870         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
871       if (Version > MaxVersion) {
872         MaxVersion = Version;
873         MaxVersionString = VersionText;
874       }
875     }
876   }
877   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
878 }
879
880 void Linux::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
881                                   llvm::opt::ArgStringList &CC1Args) const {
882   const std::string& SysRoot = computeSysRoot();
883   const std::string LibCXXIncludePathCandidates[] = {
884       DetectLibcxxIncludePath(getDriver().ResourceDir + "/include/c++"),
885       DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
886       // If this is a development, non-installed, clang, libcxx will
887       // not be found at ../include/c++ but it likely to be found at
888       // one of the following two locations:
889       DetectLibcxxIncludePath(SysRoot + "/usr/local/include/c++"),
890       DetectLibcxxIncludePath(SysRoot + "/usr/include/c++") };
891   for (const auto &IncludePath : LibCXXIncludePathCandidates) {
892     if (IncludePath.empty() || !getVFS().exists(IncludePath))
893       continue;
894     // Use the first candidate that exists.
895     addSystemInclude(DriverArgs, CC1Args, IncludePath);
896     return;
897   }
898 }
899
900 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
901                                      llvm::opt::ArgStringList &CC1Args) const {
902   // We need a detected GCC installation on Linux to provide libstdc++'s
903   // headers.
904   if (!GCCInstallation.isValid())
905     return;
906
907   // By default, look for the C++ headers in an include directory adjacent to
908   // the lib directory of the GCC installation. Note that this is expect to be
909   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
910   StringRef LibDir = GCCInstallation.getParentLibPath();
911   StringRef InstallDir = GCCInstallation.getInstallPath();
912   StringRef TripleStr = GCCInstallation.getTriple().str();
913   const Multilib &Multilib = GCCInstallation.getMultilib();
914   const std::string GCCMultiarchTriple = getMultiarchTriple(
915       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
916   const std::string TargetMultiarchTriple =
917       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
918   const GCCVersion &Version = GCCInstallation.getVersion();
919
920   // The primary search for libstdc++ supports multiarch variants.
921   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
922                                "/c++/" + Version.Text, TripleStr,
923                                GCCMultiarchTriple, TargetMultiarchTriple,
924                                Multilib.includeSuffix(), DriverArgs, CC1Args))
925     return;
926
927   // Otherwise, fall back on a bunch of options which don't use multiarch
928   // layouts for simplicity.
929   const std::string LibStdCXXIncludePathCandidates[] = {
930       // Gentoo is weird and places its headers inside the GCC install,
931       // so if the first attempt to find the headers fails, try these patterns.
932       InstallDir.str() + "/include/g++-v" + Version.Text,
933       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
934           Version.MinorStr,
935       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
936       // Android standalone toolchain has C++ headers in yet another place.
937       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
938       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
939       // without a subdirectory corresponding to the gcc version.
940       LibDir.str() + "/../include/c++",
941       // Cray's gcc installation puts headers under "g++" without a
942       // version suffix.
943       LibDir.str() + "/../include/g++",
944   };
945
946   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
947     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
948                                  /*GCCMultiarchTriple*/ "",
949                                  /*TargetMultiarchTriple*/ "",
950                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
951       break;
952   }
953 }
954
955 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
956                                ArgStringList &CC1Args) const {
957   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
958 }
959
960 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
961                                 ArgStringList &CC1Args) const {
962   if (GCCInstallation.isValid()) {
963     CC1Args.push_back("-isystem");
964     CC1Args.push_back(DriverArgs.MakeArgString(
965         GCCInstallation.getParentLibPath() + "/../" +
966         GCCInstallation.getTriple().str() + "/include"));
967   }
968 }
969
970 bool Linux::isPIEDefault() const {
971   return (getTriple().isAndroid() && !getTriple().isAndroidVersionLT(16)) ||
972           getTriple().isMusl() || getSanitizerArgs().requiresPIE();
973 }
974
975 bool Linux::IsMathErrnoDefault() const {
976   if (getTriple().isAndroid())
977     return false;
978   return Generic_ELF::IsMathErrnoDefault();
979 }
980
981 SanitizerMask Linux::getSupportedSanitizers() const {
982   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
983   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
984   const bool IsMIPS = getTriple().isMIPS32();
985   const bool IsMIPS64 = getTriple().isMIPS64();
986   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
987                            getTriple().getArch() == llvm::Triple::ppc64le;
988   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
989                          getTriple().getArch() == llvm::Triple::aarch64_be;
990   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
991                          getTriple().getArch() == llvm::Triple::thumb ||
992                          getTriple().getArch() == llvm::Triple::armeb ||
993                          getTriple().getArch() == llvm::Triple::thumbeb;
994   SanitizerMask Res = ToolChain::getSupportedSanitizers();
995   Res |= SanitizerKind::Address;
996   Res |= SanitizerKind::Fuzzer;
997   Res |= SanitizerKind::FuzzerNoLink;
998   Res |= SanitizerKind::KernelAddress;
999   Res |= SanitizerKind::Memory;
1000   Res |= SanitizerKind::Vptr;
1001   Res |= SanitizerKind::SafeStack;
1002   if (IsX86_64 || IsMIPS64 || IsAArch64)
1003     Res |= SanitizerKind::DataFlow;
1004   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64)
1005     Res |= SanitizerKind::Leak;
1006   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
1007     Res |= SanitizerKind::Thread;
1008   if (IsX86_64)
1009     Res |= SanitizerKind::KernelMemory;
1010   if (IsX86_64 || IsMIPS64)
1011     Res |= SanitizerKind::Efficiency;
1012   if (IsX86 || IsX86_64)
1013     Res |= SanitizerKind::Function;
1014   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
1015       IsPowerPC64)
1016     Res |= SanitizerKind::Scudo;
1017   if (IsX86_64 || IsAArch64) {
1018     Res |= SanitizerKind::HWAddress;
1019     Res |= SanitizerKind::KernelHWAddress;
1020   }
1021   return Res;
1022 }
1023
1024 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
1025                              llvm::opt::ArgStringList &CmdArgs) const {
1026   if (!needsProfileRT(Args)) return;
1027
1028   // Add linker option -u__llvm_runtime_variable to cause runtime
1029   // initialization module to be linked in.
1030   if ((!Args.hasArg(options::OPT_coverage)) && (!Args.hasArg(options::OPT_ftest_coverage)))
1031     CmdArgs.push_back(Args.MakeArgString(
1032         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
1033   ToolChain::addProfileRTLibs(Args, CmdArgs);
1034 }