xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Gnu.cpp (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
1 //===--- Gnu.cpp - Gnu Tool and 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 "Gnu.h"
10 #include "Arch/ARM.h"
11 #include "Arch/Mips.h"
12 #include "Arch/PPC.h"
13 #include "Arch/RISCV.h"
14 #include "Arch/Sparc.h"
15 #include "Arch/SystemZ.h"
16 #include "CommonArgs.h"
17 #include "Linux.h"
18 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Driver/Tool.h"
24 #include "clang/Driver/ToolChain.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Support/CodeGen.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/TargetParser.h"
29 #include "llvm/Support/VirtualFileSystem.h"
30 #include <system_error>
31 
32 using namespace clang::driver;
33 using namespace clang::driver::toolchains;
34 using namespace clang;
35 using namespace llvm::opt;
36 
37 using tools::addMultilibFlag;
38 
39 void tools::GnuTool::anchor() {}
40 
41 static bool forwardToGCC(const Option &O) {
42   // Don't forward inputs from the original command line.  They are added from
43   // InputInfoList.
44   return O.getKind() != Option::InputClass &&
45          !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
46 }
47 
48 // Switch CPU names not recognized by GNU assembler to a close CPU that it does
49 // recognize, instead of a lower march from being picked in the absence of a cpu
50 // flag.
51 static void normalizeCPUNamesForAssembler(const ArgList &Args,
52                                           ArgStringList &CmdArgs) {
53   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
54     StringRef CPUArg(A->getValue());
55     if (CPUArg.equals_lower("krait"))
56       CmdArgs.push_back("-mcpu=cortex-a15");
57     else if(CPUArg.equals_lower("kryo"))
58       CmdArgs.push_back("-mcpu=cortex-a57");
59     else
60       Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
61   }
62 }
63 
64 void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
65                                       const InputInfo &Output,
66                                       const InputInfoList &Inputs,
67                                       const ArgList &Args,
68                                       const char *LinkingOutput) const {
69   const Driver &D = getToolChain().getDriver();
70   ArgStringList CmdArgs;
71 
72   for (const auto &A : Args) {
73     if (forwardToGCC(A->getOption())) {
74       // It is unfortunate that we have to claim here, as this means
75       // we will basically never report anything interesting for
76       // platforms using a generic gcc, even if we are just using gcc
77       // to get to the assembler.
78       A->claim();
79 
80       // Don't forward any -g arguments to assembly steps.
81       if (isa<AssembleJobAction>(JA) &&
82           A->getOption().matches(options::OPT_g_Group))
83         continue;
84 
85       // Don't forward any -W arguments to assembly and link steps.
86       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
87           A->getOption().matches(options::OPT_W_Group))
88         continue;
89 
90       // Don't forward -mno-unaligned-access since GCC doesn't understand
91       // it and because it doesn't affect the assembly or link steps.
92       if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
93           (A->getOption().matches(options::OPT_munaligned_access) ||
94            A->getOption().matches(options::OPT_mno_unaligned_access)))
95         continue;
96 
97       A->render(Args, CmdArgs);
98     }
99   }
100 
101   RenderExtraToolArgs(JA, CmdArgs);
102 
103   // If using a driver driver, force the arch.
104   if (getToolChain().getTriple().isOSDarwin()) {
105     CmdArgs.push_back("-arch");
106     CmdArgs.push_back(
107         Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
108   }
109 
110   // Try to force gcc to match the tool chain we want, if we recognize
111   // the arch.
112   //
113   // FIXME: The triple class should directly provide the information we want
114   // here.
115   switch (getToolChain().getArch()) {
116   default:
117     break;
118   case llvm::Triple::x86:
119   case llvm::Triple::ppc:
120     CmdArgs.push_back("-m32");
121     break;
122   case llvm::Triple::x86_64:
123   case llvm::Triple::ppc64:
124   case llvm::Triple::ppc64le:
125     CmdArgs.push_back("-m64");
126     break;
127   case llvm::Triple::sparcel:
128     CmdArgs.push_back("-EL");
129     break;
130   }
131 
132   if (Output.isFilename()) {
133     CmdArgs.push_back("-o");
134     CmdArgs.push_back(Output.getFilename());
135   } else {
136     assert(Output.isNothing() && "Unexpected output");
137     CmdArgs.push_back("-fsyntax-only");
138   }
139 
140   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
141 
142   // Only pass -x if gcc will understand it; otherwise hope gcc
143   // understands the suffix correctly. The main use case this would go
144   // wrong in is for linker inputs if they happened to have an odd
145   // suffix; really the only way to get this to happen is a command
146   // like '-x foobar a.c' which will treat a.c like a linker input.
147   //
148   // FIXME: For the linker case specifically, can we safely convert
149   // inputs into '-Wl,' options?
150   for (const auto &II : Inputs) {
151     // Don't try to pass LLVM or AST inputs to a generic gcc.
152     if (types::isLLVMIR(II.getType()))
153       D.Diag(clang::diag::err_drv_no_linker_llvm_support)
154           << getToolChain().getTripleString();
155     else if (II.getType() == types::TY_AST)
156       D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
157     else if (II.getType() == types::TY_ModuleFile)
158       D.Diag(diag::err_drv_no_module_support)
159           << getToolChain().getTripleString();
160 
161     if (types::canTypeBeUserSpecified(II.getType())) {
162       CmdArgs.push_back("-x");
163       CmdArgs.push_back(types::getTypeName(II.getType()));
164     }
165 
166     if (II.isFilename())
167       CmdArgs.push_back(II.getFilename());
168     else {
169       const Arg &A = II.getInputArg();
170 
171       // Reverse translate some rewritten options.
172       if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
173         CmdArgs.push_back("-lstdc++");
174         continue;
175       }
176 
177       // Don't render as input, we need gcc to do the translations.
178       A.render(Args, CmdArgs);
179     }
180   }
181 
182   const std::string &customGCCName = D.getCCCGenericGCCName();
183   const char *GCCName;
184   if (!customGCCName.empty())
185     GCCName = customGCCName.c_str();
186   else if (D.CCCIsCXX()) {
187     GCCName = "g++";
188   } else
189     GCCName = "gcc";
190 
191   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
192   C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
193 }
194 
195 void tools::gcc::Preprocessor::RenderExtraToolArgs(
196     const JobAction &JA, ArgStringList &CmdArgs) const {
197   CmdArgs.push_back("-E");
198 }
199 
200 void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
201                                                ArgStringList &CmdArgs) const {
202   const Driver &D = getToolChain().getDriver();
203 
204   switch (JA.getType()) {
205   // If -flto, etc. are present then make sure not to force assembly output.
206   case types::TY_LLVM_IR:
207   case types::TY_LTO_IR:
208   case types::TY_LLVM_BC:
209   case types::TY_LTO_BC:
210     CmdArgs.push_back("-c");
211     break;
212   // We assume we've got an "integrated" assembler in that gcc will produce an
213   // object file itself.
214   case types::TY_Object:
215     CmdArgs.push_back("-c");
216     break;
217   case types::TY_PP_Asm:
218     CmdArgs.push_back("-S");
219     break;
220   case types::TY_Nothing:
221     CmdArgs.push_back("-fsyntax-only");
222     break;
223   default:
224     D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
225   }
226 }
227 
228 void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
229                                              ArgStringList &CmdArgs) const {
230   // The types are (hopefully) good enough.
231 }
232 
233 // On Arm the endianness of the output file is determined by the target and
234 // can be overridden by the pseudo-target flags '-mlittle-endian'/'-EL' and
235 // '-mbig-endian'/'-EB'. Unlike other targets the flag does not result in a
236 // normalized triple so we must handle the flag here.
237 static bool isArmBigEndian(const llvm::Triple &Triple,
238                            const ArgList &Args) {
239   bool IsBigEndian = false;
240   switch (Triple.getArch()) {
241   case llvm::Triple::armeb:
242   case llvm::Triple::thumbeb:
243     IsBigEndian = true;
244     LLVM_FALLTHROUGH;
245   case llvm::Triple::arm:
246   case llvm::Triple::thumb:
247     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
248                                options::OPT_mbig_endian))
249       IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
250     break;
251   default:
252     break;
253   }
254   return IsBigEndian;
255 }
256 
257 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
258   switch (T.getArch()) {
259   case llvm::Triple::x86:
260     if (T.isOSIAMCU())
261       return "elf_iamcu";
262     return "elf_i386";
263   case llvm::Triple::aarch64:
264     return "aarch64linux";
265   case llvm::Triple::aarch64_be:
266     return "aarch64linuxb";
267   case llvm::Triple::arm:
268   case llvm::Triple::thumb:
269   case llvm::Triple::armeb:
270   case llvm::Triple::thumbeb:
271     return isArmBigEndian(T, Args) ? "armelfb_linux_eabi" : "armelf_linux_eabi";
272   case llvm::Triple::ppc:
273     return "elf32ppclinux";
274   case llvm::Triple::ppc64:
275     return "elf64ppc";
276   case llvm::Triple::ppc64le:
277     return "elf64lppc";
278   case llvm::Triple::riscv32:
279     return "elf32lriscv";
280   case llvm::Triple::riscv64:
281     return "elf64lriscv";
282   case llvm::Triple::sparc:
283   case llvm::Triple::sparcel:
284     return "elf32_sparc";
285   case llvm::Triple::sparcv9:
286     return "elf64_sparc";
287   case llvm::Triple::mips:
288     return "elf32btsmip";
289   case llvm::Triple::mipsel:
290     return "elf32ltsmip";
291   case llvm::Triple::mips64:
292     if (tools::mips::hasMipsAbiArg(Args, "n32") ||
293         T.getEnvironment() == llvm::Triple::GNUABIN32)
294       return "elf32btsmipn32";
295     return "elf64btsmip";
296   case llvm::Triple::mips64el:
297     if (tools::mips::hasMipsAbiArg(Args, "n32") ||
298         T.getEnvironment() == llvm::Triple::GNUABIN32)
299       return "elf32ltsmipn32";
300     return "elf64ltsmip";
301   case llvm::Triple::systemz:
302     return "elf64_s390";
303   case llvm::Triple::x86_64:
304     if (T.getEnvironment() == llvm::Triple::GNUX32)
305       return "elf32_x86_64";
306     return "elf_x86_64";
307   default:
308     return nullptr;
309   }
310 }
311 
312 static bool getPIE(const ArgList &Args, const ToolChain &TC) {
313   if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
314       Args.hasArg(options::OPT_r) || Args.hasArg(options::OPT_static_pie))
315     return false;
316 
317   Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
318                            options::OPT_nopie);
319   if (!A)
320     return TC.isPIEDefault();
321   return A->getOption().matches(options::OPT_pie);
322 }
323 
324 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
325   bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
326   // -no-pie is an alias for -nopie. So, handling -nopie takes care of
327   // -no-pie as well.
328   if (HasStaticPIE && Args.hasArg(options::OPT_nopie)) {
329     const Driver &D = TC.getDriver();
330     const llvm::opt::OptTable &Opts = D.getOpts();
331     const char *StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
332     const char *NoPIEName = Opts.getOptionName(options::OPT_nopie);
333     D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
334   }
335   return HasStaticPIE;
336 }
337 
338 static bool getStatic(const ArgList &Args) {
339   return Args.hasArg(options::OPT_static) &&
340       !Args.hasArg(options::OPT_static_pie);
341 }
342 
343 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
344                                            const InputInfo &Output,
345                                            const InputInfoList &Inputs,
346                                            const ArgList &Args,
347                                            const char *LinkingOutput) const {
348   // FIXME: The Linker class constructor takes a ToolChain and not a
349   // Generic_ELF, so the static_cast might return a reference to a invalid
350   // instance (see PR45061). Ideally, the Linker constructor needs to take a
351   // Generic_ELF instead.
352   const toolchains::Generic_ELF &ToolChain =
353       static_cast<const toolchains::Generic_ELF &>(getToolChain());
354   const Driver &D = ToolChain.getDriver();
355 
356   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
357 
358   const llvm::Triple::ArchType Arch = ToolChain.getArch();
359   const bool isAndroid = ToolChain.getTriple().isAndroid();
360   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
361   const bool IsPIE = getPIE(Args, ToolChain);
362   const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
363   const bool IsStatic = getStatic(Args);
364   const bool HasCRTBeginEndFiles =
365       ToolChain.getTriple().hasEnvironment() ||
366       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
367 
368   ArgStringList CmdArgs;
369 
370   // Silence warning for "clang -g foo.o -o foo"
371   Args.ClaimAllArgs(options::OPT_g_Group);
372   // and "clang -emit-llvm foo.o -o foo"
373   Args.ClaimAllArgs(options::OPT_emit_llvm);
374   // and for "clang -w foo.o -o foo". Other warning options are already
375   // handled somewhere else.
376   Args.ClaimAllArgs(options::OPT_w);
377 
378   if (!D.SysRoot.empty())
379     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
380 
381   if (IsPIE)
382     CmdArgs.push_back("-pie");
383 
384   if (IsStaticPIE) {
385     CmdArgs.push_back("-static");
386     CmdArgs.push_back("-pie");
387     CmdArgs.push_back("--no-dynamic-linker");
388     CmdArgs.push_back("-z");
389     CmdArgs.push_back("text");
390   }
391 
392   if (ToolChain.isNoExecStackDefault()) {
393     CmdArgs.push_back("-z");
394     CmdArgs.push_back("noexecstack");
395   }
396 
397   if (Args.hasArg(options::OPT_rdynamic))
398     CmdArgs.push_back("-export-dynamic");
399 
400   if (Args.hasArg(options::OPT_s))
401     CmdArgs.push_back("-s");
402 
403   if (Triple.isARM() || Triple.isThumb() || Triple.isAArch64()) {
404     bool IsBigEndian = isArmBigEndian(Triple, Args);
405     if (IsBigEndian)
406       arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
407     IsBigEndian = IsBigEndian || Arch == llvm::Triple::aarch64_be;
408     CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL");
409   }
410 
411   // Most Android ARM64 targets should enable the linker fix for erratum
412   // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
413   if (Arch == llvm::Triple::aarch64 && isAndroid) {
414     std::string CPU = getCPUName(Args, Triple);
415     if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
416       CmdArgs.push_back("--fix-cortex-a53-843419");
417   }
418 
419   // Android does not allow shared text relocations. Emit a warning if the
420   // user's code contains any.
421   if (isAndroid)
422       CmdArgs.push_back("--warn-shared-textrel");
423 
424   ToolChain.addExtraOpts(CmdArgs);
425 
426   CmdArgs.push_back("--eh-frame-hdr");
427 
428   if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
429     CmdArgs.push_back("-m");
430     CmdArgs.push_back(LDMOption);
431   } else {
432     D.Diag(diag::err_target_unknown_triple) << Triple.str();
433     return;
434   }
435 
436   if (IsStatic) {
437     if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
438         Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
439       CmdArgs.push_back("-Bstatic");
440     else
441       CmdArgs.push_back("-static");
442   } else if (Args.hasArg(options::OPT_shared)) {
443     CmdArgs.push_back("-shared");
444   }
445 
446   if (!IsStatic) {
447     if (Args.hasArg(options::OPT_rdynamic))
448       CmdArgs.push_back("-export-dynamic");
449 
450     if (!Args.hasArg(options::OPT_shared) && !IsStaticPIE) {
451       const std::string Loader =
452           D.DyldPrefix + ToolChain.getDynamicLinker(Args);
453       CmdArgs.push_back("-dynamic-linker");
454       CmdArgs.push_back(Args.MakeArgString(Loader));
455     }
456   }
457 
458   CmdArgs.push_back("-o");
459   CmdArgs.push_back(Output.getFilename());
460 
461   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
462     if (!isAndroid && !IsIAMCU) {
463       const char *crt1 = nullptr;
464       if (!Args.hasArg(options::OPT_shared)) {
465         if (Args.hasArg(options::OPT_pg))
466           crt1 = "gcrt1.o";
467         else if (IsPIE)
468           crt1 = "Scrt1.o";
469         else if (IsStaticPIE)
470           crt1 = "rcrt1.o";
471         else
472           crt1 = "crt1.o";
473       }
474       if (crt1)
475         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
476 
477       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
478     }
479 
480     if (IsIAMCU)
481       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
482     else if (HasCRTBeginEndFiles) {
483       std::string P;
484       if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
485           !isAndroid) {
486         std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
487                                                        ToolChain::FT_Object);
488         if (ToolChain.getVFS().exists(crtbegin))
489           P = crtbegin;
490       }
491       if (P.empty()) {
492         const char *crtbegin;
493         if (IsStatic)
494           crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
495         else if (Args.hasArg(options::OPT_shared))
496           crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
497         else if (IsPIE || IsStaticPIE)
498           crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
499         else
500           crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
501         P = ToolChain.GetFilePath(crtbegin);
502       }
503       CmdArgs.push_back(Args.MakeArgString(P));
504     }
505 
506     // Add crtfastmath.o if available and fast math is enabled.
507     ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
508   }
509 
510   Args.AddAllArgs(CmdArgs, options::OPT_L);
511   Args.AddAllArgs(CmdArgs, options::OPT_u);
512 
513   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
514 
515   if (D.isUsingLTO()) {
516     assert(!Inputs.empty() && "Must have at least one input.");
517     AddGoldPlugin(ToolChain, Args, CmdArgs, Output, Inputs[0],
518                   D.getLTOMode() == LTOK_Thin);
519   }
520 
521   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
522     CmdArgs.push_back("--no-demangle");
523 
524   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
525   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
526   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
527   // The profile runtime also needs access to system libraries.
528   getToolChain().addProfileRTLibs(Args, CmdArgs);
529 
530   if (D.CCCIsCXX() &&
531       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
532     if (ToolChain.ShouldLinkCXXStdlib(Args)) {
533       bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
534                                  !Args.hasArg(options::OPT_static);
535       if (OnlyLibstdcxxStatic)
536         CmdArgs.push_back("-Bstatic");
537       ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
538       if (OnlyLibstdcxxStatic)
539         CmdArgs.push_back("-Bdynamic");
540     }
541     CmdArgs.push_back("-lm");
542   }
543   // Silence warnings when linking C code with a C++ '-stdlib' argument.
544   Args.ClaimAllArgs(options::OPT_stdlib_EQ);
545 
546   if (!Args.hasArg(options::OPT_nostdlib)) {
547     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
548       if (IsStatic || IsStaticPIE)
549         CmdArgs.push_back("--start-group");
550 
551       if (NeedsSanitizerDeps)
552         linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
553 
554       if (NeedsXRayDeps)
555         linkXRayRuntimeDeps(ToolChain, CmdArgs);
556 
557       bool WantPthread = Args.hasArg(options::OPT_pthread) ||
558                          Args.hasArg(options::OPT_pthreads);
559 
560       // Use the static OpenMP runtime with -static-openmp
561       bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
562                           !Args.hasArg(options::OPT_static);
563 
564       // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
565       // require librt. Most modern Linux platforms do, but some may not.
566       if (addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP,
567                            JA.isHostOffloading(Action::OFK_OpenMP),
568                            /* GompNeedsRT= */ true))
569         // OpenMP runtimes implies pthreads when using the GNU toolchain.
570         // FIXME: Does this really make sense for all GNU toolchains?
571         WantPthread = true;
572 
573       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
574 
575       if (WantPthread && !isAndroid)
576         CmdArgs.push_back("-lpthread");
577 
578       if (Args.hasArg(options::OPT_fsplit_stack))
579         CmdArgs.push_back("--wrap=pthread_create");
580 
581       if (!Args.hasArg(options::OPT_nolibc))
582         CmdArgs.push_back("-lc");
583 
584       // Add IAMCU specific libs, if needed.
585       if (IsIAMCU)
586         CmdArgs.push_back("-lgloss");
587 
588       if (IsStatic || IsStaticPIE)
589         CmdArgs.push_back("--end-group");
590       else
591         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
592 
593       // Add IAMCU specific libs (outside the group), if needed.
594       if (IsIAMCU) {
595         CmdArgs.push_back("--as-needed");
596         CmdArgs.push_back("-lsoftfp");
597         CmdArgs.push_back("--no-as-needed");
598       }
599     }
600 
601     if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
602       if (HasCRTBeginEndFiles) {
603         std::string P;
604         if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
605             !isAndroid) {
606           std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
607                                                        ToolChain::FT_Object);
608           if (ToolChain.getVFS().exists(crtend))
609             P = crtend;
610         }
611         if (P.empty()) {
612           const char *crtend;
613           if (Args.hasArg(options::OPT_shared))
614             crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
615           else if (IsPIE || IsStaticPIE)
616             crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
617           else
618             crtend = isAndroid ? "crtend_android.o" : "crtend.o";
619           P = ToolChain.GetFilePath(crtend);
620         }
621         CmdArgs.push_back(Args.MakeArgString(P));
622       }
623       if (!isAndroid)
624         CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
625     }
626   }
627 
628   // Add HIP offloading linker script args if required.
629   AddHIPLinkerScript(getToolChain(), C, Output, Inputs, Args, CmdArgs, JA,
630                      *this);
631 
632   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
633   C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
634 }
635 
636 void tools::gnutools::Assembler::ConstructJob(Compilation &C,
637                                               const JobAction &JA,
638                                               const InputInfo &Output,
639                                               const InputInfoList &Inputs,
640                                               const ArgList &Args,
641                                               const char *LinkingOutput) const {
642   const auto &D = getToolChain().getDriver();
643 
644   claimNoWarnArgs(Args);
645 
646   ArgStringList CmdArgs;
647 
648   llvm::Reloc::Model RelocationModel;
649   unsigned PICLevel;
650   bool IsPIE;
651   std::tie(RelocationModel, PICLevel, IsPIE) =
652       ParsePICArgs(getToolChain(), Args);
653 
654   if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
655     if (A->getOption().getID() == options::OPT_gz) {
656       CmdArgs.push_back("--compress-debug-sections");
657     } else {
658       StringRef Value = A->getValue();
659       if (Value == "none" || Value == "zlib" || Value == "zlib-gnu") {
660         CmdArgs.push_back(
661             Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
662       } else {
663         D.Diag(diag::err_drv_unsupported_option_argument)
664             << A->getOption().getName() << Value;
665       }
666     }
667   }
668 
669   if (getToolChain().isNoExecStackDefault()) {
670       CmdArgs.push_back("--noexecstack");
671   }
672 
673   switch (getToolChain().getArch()) {
674   default:
675     break;
676   // Add --32/--64 to make sure we get the format we want.
677   // This is incomplete
678   case llvm::Triple::x86:
679     CmdArgs.push_back("--32");
680     break;
681   case llvm::Triple::x86_64:
682     if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
683       CmdArgs.push_back("--x32");
684     else
685       CmdArgs.push_back("--64");
686     break;
687   case llvm::Triple::ppc: {
688     CmdArgs.push_back("-a32");
689     CmdArgs.push_back("-mppc");
690     CmdArgs.push_back(
691       ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
692     break;
693   }
694   case llvm::Triple::ppc64: {
695     CmdArgs.push_back("-a64");
696     CmdArgs.push_back("-mppc64");
697     CmdArgs.push_back(
698       ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
699     break;
700   }
701   case llvm::Triple::ppc64le: {
702     CmdArgs.push_back("-a64");
703     CmdArgs.push_back("-mppc64");
704     CmdArgs.push_back("-mlittle-endian");
705     CmdArgs.push_back(
706       ppc::getPPCAsmModeForCPU(getCPUName(Args, getToolChain().getTriple())));
707     break;
708   }
709   case llvm::Triple::riscv32:
710   case llvm::Triple::riscv64: {
711     StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
712     CmdArgs.push_back("-mabi");
713     CmdArgs.push_back(ABIName.data());
714     StringRef MArchName = riscv::getRISCVArch(Args, getToolChain().getTriple());
715     CmdArgs.push_back("-march");
716     CmdArgs.push_back(MArchName.data());
717     break;
718   }
719   case llvm::Triple::sparc:
720   case llvm::Triple::sparcel: {
721     CmdArgs.push_back("-32");
722     std::string CPU = getCPUName(Args, getToolChain().getTriple());
723     CmdArgs.push_back(
724         sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
725     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
726     break;
727   }
728   case llvm::Triple::sparcv9: {
729     CmdArgs.push_back("-64");
730     std::string CPU = getCPUName(Args, getToolChain().getTriple());
731     CmdArgs.push_back(
732         sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
733     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
734     break;
735   }
736   case llvm::Triple::arm:
737   case llvm::Triple::armeb:
738   case llvm::Triple::thumb:
739   case llvm::Triple::thumbeb: {
740     const llvm::Triple &Triple2 = getToolChain().getTriple();
741     CmdArgs.push_back(isArmBigEndian(Triple2, Args) ? "-EB" : "-EL");
742     switch (Triple2.getSubArch()) {
743     case llvm::Triple::ARMSubArch_v7:
744       CmdArgs.push_back("-mfpu=neon");
745       break;
746     case llvm::Triple::ARMSubArch_v8:
747       CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
748       break;
749     default:
750       break;
751     }
752 
753     switch (arm::getARMFloatABI(getToolChain(), Args)) {
754     case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
755     case arm::FloatABI::Soft:
756       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
757       break;
758     case arm::FloatABI::SoftFP:
759       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
760       break;
761     case arm::FloatABI::Hard:
762       CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
763       break;
764     }
765 
766     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
767     normalizeCPUNamesForAssembler(Args, CmdArgs);
768 
769     Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
770     break;
771   }
772   case llvm::Triple::aarch64:
773   case llvm::Triple::aarch64_be: {
774     CmdArgs.push_back(
775         getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL");
776     Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
777     normalizeCPUNamesForAssembler(Args, CmdArgs);
778 
779     break;
780   }
781   case llvm::Triple::mips:
782   case llvm::Triple::mipsel:
783   case llvm::Triple::mips64:
784   case llvm::Triple::mips64el: {
785     StringRef CPUName;
786     StringRef ABIName;
787     mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
788     ABIName = mips::getGnuCompatibleMipsABIName(ABIName);
789 
790     CmdArgs.push_back("-march");
791     CmdArgs.push_back(CPUName.data());
792 
793     CmdArgs.push_back("-mabi");
794     CmdArgs.push_back(ABIName.data());
795 
796     // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
797     // or -mshared (not implemented) is in effect.
798     if (RelocationModel == llvm::Reloc::Static)
799       CmdArgs.push_back("-mno-shared");
800 
801     // LLVM doesn't support -mplt yet and acts as if it is always given.
802     // However, -mplt has no effect with the N64 ABI.
803     if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls))
804       CmdArgs.push_back("-call_nonpic");
805 
806     if (getToolChain().getTriple().isLittleEndian())
807       CmdArgs.push_back("-EL");
808     else
809       CmdArgs.push_back("-EB");
810 
811     if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
812       if (StringRef(A->getValue()) == "2008")
813         CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
814     }
815 
816     // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
817     if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
818                                  options::OPT_mfp64)) {
819       A->claim();
820       A->render(Args, CmdArgs);
821     } else if (mips::shouldUseFPXX(
822                    Args, getToolChain().getTriple(), CPUName, ABIName,
823                    mips::getMipsFloatABI(getToolChain().getDriver(), Args,
824                                          getToolChain().getTriple())))
825       CmdArgs.push_back("-mfpxx");
826 
827     // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
828     // -mno-mips16 is actually -no-mips16.
829     if (Arg *A =
830             Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
831       if (A->getOption().matches(options::OPT_mips16)) {
832         A->claim();
833         A->render(Args, CmdArgs);
834       } else {
835         A->claim();
836         CmdArgs.push_back("-no-mips16");
837       }
838     }
839 
840     Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
841                     options::OPT_mno_micromips);
842     Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
843     Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
844 
845     if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
846       // Do not use AddLastArg because not all versions of MIPS assembler
847       // support -mmsa / -mno-msa options.
848       if (A->getOption().matches(options::OPT_mmsa))
849         CmdArgs.push_back(Args.MakeArgString("-mmsa"));
850     }
851 
852     Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
853                     options::OPT_msoft_float);
854 
855     Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
856                     options::OPT_msingle_float);
857 
858     Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
859                     options::OPT_mno_odd_spreg);
860 
861     AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
862     break;
863   }
864   case llvm::Triple::systemz: {
865     // Always pass an -march option, since our default of z10 is later
866     // than the GNU assembler's default.
867     std::string CPUName = systemz::getSystemZTargetCPU(Args);
868     CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
869     break;
870   }
871   }
872 
873   for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
874                                     options::OPT_fdebug_prefix_map_EQ)) {
875     StringRef Map = A->getValue();
876     if (Map.find('=') == StringRef::npos)
877       D.Diag(diag::err_drv_invalid_argument_to_option)
878           << Map << A->getOption().getName();
879     else {
880       CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
881       CmdArgs.push_back(Args.MakeArgString(Map));
882     }
883     A->claim();
884   }
885 
886   Args.AddAllArgs(CmdArgs, options::OPT_I);
887   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
888 
889   CmdArgs.push_back("-o");
890   CmdArgs.push_back(Output.getFilename());
891 
892   for (const auto &II : Inputs)
893     CmdArgs.push_back(II.getFilename());
894 
895   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
896   C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
897 
898   // Handle the debug info splitting at object creation time if we're
899   // creating an object.
900   // TODO: Currently only works on linux with newer objcopy.
901   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
902       getToolChain().getTriple().isOSLinux())
903     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
904                    SplitDebugName(Args, Inputs[0], Output));
905 }
906 
907 namespace {
908 // Filter to remove Multilibs that don't exist as a suffix to Path
909 class FilterNonExistent {
910   StringRef Base, File;
911   llvm::vfs::FileSystem &VFS;
912 
913 public:
914   FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
915       : Base(Base), File(File), VFS(VFS) {}
916   bool operator()(const Multilib &M) {
917     return !VFS.exists(Base + M.gccSuffix() + File);
918   }
919 };
920 } // end anonymous namespace
921 
922 static bool isSoftFloatABI(const ArgList &Args) {
923   Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
924                            options::OPT_mfloat_abi_EQ);
925   if (!A)
926     return false;
927 
928   return A->getOption().matches(options::OPT_msoft_float) ||
929          (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
930           A->getValue() == StringRef("soft"));
931 }
932 
933 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
934   return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
935 }
936 
937 static bool isMipsEL(llvm::Triple::ArchType Arch) {
938   return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
939 }
940 
941 static bool isMips16(const ArgList &Args) {
942   Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
943   return A && A->getOption().matches(options::OPT_mips16);
944 }
945 
946 static bool isMicroMips(const ArgList &Args) {
947   Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
948   return A && A->getOption().matches(options::OPT_mmicromips);
949 }
950 
951 static bool isMSP430(llvm::Triple::ArchType Arch) {
952   return Arch == llvm::Triple::msp430;
953 }
954 
955 static Multilib makeMultilib(StringRef commonSuffix) {
956   return Multilib(commonSuffix, commonSuffix, commonSuffix);
957 }
958 
959 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
960                                 FilterNonExistent &NonExistent,
961                                 DetectedMultilibs &Result) {
962   // Check for Code Sourcery toolchain multilibs
963   MultilibSet CSMipsMultilibs;
964   {
965     auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
966 
967     auto MArchMicroMips =
968         makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
969 
970     auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
971 
972     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
973 
974     auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
975 
976     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
977 
978     auto DefaultFloat =
979         makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
980 
981     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
982 
983     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
984 
985     // Note that this one's osSuffix is ""
986     auto MAbi64 = makeMultilib("")
987                       .gccSuffix("/64")
988                       .includeSuffix("/64")
989                       .flag("+mabi=n64")
990                       .flag("-mabi=n32")
991                       .flag("-m32");
992 
993     CSMipsMultilibs =
994         MultilibSet()
995             .Either(MArchMips16, MArchMicroMips, MArchDefault)
996             .Maybe(UCLibc)
997             .Either(SoftFloat, Nan2008, DefaultFloat)
998             .FilterOut("/micromips/nan2008")
999             .FilterOut("/mips16/nan2008")
1000             .Either(BigEndian, LittleEndian)
1001             .Maybe(MAbi64)
1002             .FilterOut("/mips16.*/64")
1003             .FilterOut("/micromips.*/64")
1004             .FilterOut(NonExistent)
1005             .setIncludeDirsCallback([](const Multilib &M) {
1006               std::vector<std::string> Dirs({"/include"});
1007               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1008                 Dirs.push_back(
1009                     "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1010               else
1011                 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1012               return Dirs;
1013             });
1014   }
1015 
1016   MultilibSet DebianMipsMultilibs;
1017   {
1018     Multilib MAbiN32 =
1019         Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1020 
1021     Multilib M64 = Multilib()
1022                        .gccSuffix("/64")
1023                        .includeSuffix("/64")
1024                        .flag("+m64")
1025                        .flag("-m32")
1026                        .flag("-mabi=n32");
1027 
1028     Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1029 
1030     DebianMipsMultilibs =
1031         MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1032   }
1033 
1034   // Sort candidates. Toolchain that best meets the directories tree goes first.
1035   // Then select the first toolchains matches command line flags.
1036   MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1037   if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1038     std::iter_swap(Candidates, Candidates + 1);
1039   for (const MultilibSet *Candidate : Candidates) {
1040     if (Candidate->select(Flags, Result.SelectedMultilib)) {
1041       if (Candidate == &DebianMipsMultilibs)
1042         Result.BiarchSibling = Multilib();
1043       Result.Multilibs = *Candidate;
1044       return true;
1045     }
1046   }
1047   return false;
1048 }
1049 
1050 static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
1051                                      const Multilib::flags_list &Flags,
1052                                      FilterNonExistent &NonExistent,
1053                                      DetectedMultilibs &Result) {
1054 
1055   MultilibSet AndroidMipsMultilibs =
1056       MultilibSet()
1057           .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1058           .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1059           .FilterOut(NonExistent);
1060 
1061   MultilibSet AndroidMipselMultilibs =
1062       MultilibSet()
1063           .Either(Multilib().flag("+march=mips32"),
1064                   Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1065                   Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1066           .FilterOut(NonExistent);
1067 
1068   MultilibSet AndroidMips64elMultilibs =
1069       MultilibSet()
1070           .Either(
1071               Multilib().flag("+march=mips64r6"),
1072               Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
1073               Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1074               Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1075           .FilterOut(NonExistent);
1076 
1077   MultilibSet *MS = &AndroidMipsMultilibs;
1078   if (VFS.exists(Path + "/mips-r6"))
1079     MS = &AndroidMipselMultilibs;
1080   else if (VFS.exists(Path + "/32"))
1081     MS = &AndroidMips64elMultilibs;
1082   if (MS->select(Flags, Result.SelectedMultilib)) {
1083     Result.Multilibs = *MS;
1084     return true;
1085   }
1086   return false;
1087 }
1088 
1089 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags,
1090                                   FilterNonExistent &NonExistent,
1091                                   DetectedMultilibs &Result) {
1092   // Musl toolchain multilibs
1093   MultilibSet MuslMipsMultilibs;
1094   {
1095     auto MArchMipsR2 = makeMultilib("")
1096                            .osSuffix("/mips-r2-hard-musl")
1097                            .flag("+EB")
1098                            .flag("-EL")
1099                            .flag("+march=mips32r2");
1100 
1101     auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1102                              .flag("-EB")
1103                              .flag("+EL")
1104                              .flag("+march=mips32r2");
1105 
1106     MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1107 
1108     // Specify the callback that computes the include directories.
1109     MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1110       return std::vector<std::string>(
1111           {"/../sysroot" + M.osSuffix() + "/usr/include"});
1112     });
1113   }
1114   if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1115     Result.Multilibs = MuslMipsMultilibs;
1116     return true;
1117   }
1118   return false;
1119 }
1120 
1121 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags,
1122                                  FilterNonExistent &NonExistent,
1123                                  DetectedMultilibs &Result) {
1124   // CodeScape MTI toolchain v1.2 and early.
1125   MultilibSet MtiMipsMultilibsV1;
1126   {
1127     auto MArchMips32 = makeMultilib("/mips32")
1128                            .flag("+m32")
1129                            .flag("-m64")
1130                            .flag("-mmicromips")
1131                            .flag("+march=mips32");
1132 
1133     auto MArchMicroMips = makeMultilib("/micromips")
1134                               .flag("+m32")
1135                               .flag("-m64")
1136                               .flag("+mmicromips");
1137 
1138     auto MArchMips64r2 = makeMultilib("/mips64r2")
1139                              .flag("-m32")
1140                              .flag("+m64")
1141                              .flag("+march=mips64r2");
1142 
1143     auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1144         "-march=mips64r2");
1145 
1146     auto MArchDefault = makeMultilib("")
1147                             .flag("+m32")
1148                             .flag("-m64")
1149                             .flag("-mmicromips")
1150                             .flag("+march=mips32r2");
1151 
1152     auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1153 
1154     auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1155 
1156     auto MAbi64 =
1157         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1158 
1159     auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1160 
1161     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1162 
1163     auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1164 
1165     auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1166 
1167     MtiMipsMultilibsV1 =
1168         MultilibSet()
1169             .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1170                     MArchDefault)
1171             .Maybe(UCLibc)
1172             .Maybe(Mips16)
1173             .FilterOut("/mips64/mips16")
1174             .FilterOut("/mips64r2/mips16")
1175             .FilterOut("/micromips/mips16")
1176             .Maybe(MAbi64)
1177             .FilterOut("/micromips/64")
1178             .FilterOut("/mips32/64")
1179             .FilterOut("^/64")
1180             .FilterOut("/mips16/64")
1181             .Either(BigEndian, LittleEndian)
1182             .Maybe(SoftFloat)
1183             .Maybe(Nan2008)
1184             .FilterOut(".*sof/nan2008")
1185             .FilterOut(NonExistent)
1186             .setIncludeDirsCallback([](const Multilib &M) {
1187               std::vector<std::string> Dirs({"/include"});
1188               if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1189                 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1190               else
1191                 Dirs.push_back("/../../../../sysroot/usr/include");
1192               return Dirs;
1193             });
1194   }
1195 
1196   // CodeScape IMG toolchain starting from v1.3.
1197   MultilibSet MtiMipsMultilibsV2;
1198   {
1199     auto BeHard = makeMultilib("/mips-r2-hard")
1200                       .flag("+EB")
1201                       .flag("-msoft-float")
1202                       .flag("-mnan=2008")
1203                       .flag("-muclibc");
1204     auto BeSoft = makeMultilib("/mips-r2-soft")
1205                       .flag("+EB")
1206                       .flag("+msoft-float")
1207                       .flag("-mnan=2008");
1208     auto ElHard = makeMultilib("/mipsel-r2-hard")
1209                       .flag("+EL")
1210                       .flag("-msoft-float")
1211                       .flag("-mnan=2008")
1212                       .flag("-muclibc");
1213     auto ElSoft = makeMultilib("/mipsel-r2-soft")
1214                       .flag("+EL")
1215                       .flag("+msoft-float")
1216                       .flag("-mnan=2008")
1217                       .flag("-mmicromips");
1218     auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
1219                          .flag("+EB")
1220                          .flag("-msoft-float")
1221                          .flag("+mnan=2008")
1222                          .flag("-muclibc");
1223     auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
1224                          .flag("+EL")
1225                          .flag("-msoft-float")
1226                          .flag("+mnan=2008")
1227                          .flag("-muclibc")
1228                          .flag("-mmicromips");
1229     auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
1230                                .flag("+EB")
1231                                .flag("-msoft-float")
1232                                .flag("+mnan=2008")
1233                                .flag("+muclibc");
1234     auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
1235                                .flag("+EL")
1236                                .flag("-msoft-float")
1237                                .flag("+mnan=2008")
1238                                .flag("+muclibc");
1239     auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
1240                             .flag("+EB")
1241                             .flag("-msoft-float")
1242                             .flag("-mnan=2008")
1243                             .flag("+muclibc");
1244     auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
1245                             .flag("+EL")
1246                             .flag("-msoft-float")
1247                             .flag("-mnan=2008")
1248                             .flag("+muclibc");
1249     auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
1250                               .flag("+EL")
1251                               .flag("-msoft-float")
1252                               .flag("+mnan=2008")
1253                               .flag("+mmicromips");
1254     auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
1255                            .flag("+EL")
1256                            .flag("+msoft-float")
1257                            .flag("-mnan=2008")
1258                            .flag("+mmicromips");
1259 
1260     auto O32 =
1261         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1262     auto N32 =
1263         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1264     auto N64 =
1265         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1266 
1267     MtiMipsMultilibsV2 =
1268         MultilibSet()
1269             .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1270                      BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1271                      ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1272             .Either(O32, N32, N64)
1273             .FilterOut(NonExistent)
1274             .setIncludeDirsCallback([](const Multilib &M) {
1275               return std::vector<std::string>({"/../../../../sysroot" +
1276                                                M.includeSuffix() +
1277                                                "/../usr/include"});
1278             })
1279             .setFilePathsCallback([](const Multilib &M) {
1280               return std::vector<std::string>(
1281                   {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1282             });
1283   }
1284   for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1285     if (Candidate->select(Flags, Result.SelectedMultilib)) {
1286       Result.Multilibs = *Candidate;
1287       return true;
1288     }
1289   }
1290   return false;
1291 }
1292 
1293 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags,
1294                                  FilterNonExistent &NonExistent,
1295                                  DetectedMultilibs &Result) {
1296   // CodeScape IMG toolchain v1.2 and early.
1297   MultilibSet ImgMultilibsV1;
1298   {
1299     auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1300 
1301     auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1302 
1303     auto MAbi64 =
1304         makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1305 
1306     ImgMultilibsV1 =
1307         MultilibSet()
1308             .Maybe(Mips64r6)
1309             .Maybe(MAbi64)
1310             .Maybe(LittleEndian)
1311             .FilterOut(NonExistent)
1312             .setIncludeDirsCallback([](const Multilib &M) {
1313               return std::vector<std::string>(
1314                   {"/include", "/../../../../sysroot/usr/include"});
1315             });
1316   }
1317 
1318   // CodeScape IMG toolchain starting from v1.3.
1319   MultilibSet ImgMultilibsV2;
1320   {
1321     auto BeHard = makeMultilib("/mips-r6-hard")
1322                       .flag("+EB")
1323                       .flag("-msoft-float")
1324                       .flag("-mmicromips");
1325     auto BeSoft = makeMultilib("/mips-r6-soft")
1326                       .flag("+EB")
1327                       .flag("+msoft-float")
1328                       .flag("-mmicromips");
1329     auto ElHard = makeMultilib("/mipsel-r6-hard")
1330                       .flag("+EL")
1331                       .flag("-msoft-float")
1332                       .flag("-mmicromips");
1333     auto ElSoft = makeMultilib("/mipsel-r6-soft")
1334                       .flag("+EL")
1335                       .flag("+msoft-float")
1336                       .flag("-mmicromips");
1337     auto BeMicroHard = makeMultilib("/micromips-r6-hard")
1338                            .flag("+EB")
1339                            .flag("-msoft-float")
1340                            .flag("+mmicromips");
1341     auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
1342                            .flag("+EB")
1343                            .flag("+msoft-float")
1344                            .flag("+mmicromips");
1345     auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
1346                            .flag("+EL")
1347                            .flag("-msoft-float")
1348                            .flag("+mmicromips");
1349     auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
1350                            .flag("+EL")
1351                            .flag("+msoft-float")
1352                            .flag("+mmicromips");
1353 
1354     auto O32 =
1355         makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1356     auto N32 =
1357         makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1358     auto N64 =
1359         makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1360 
1361     ImgMultilibsV2 =
1362         MultilibSet()
1363             .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1364                      ElMicroHard, ElMicroSoft})
1365             .Either(O32, N32, N64)
1366             .FilterOut(NonExistent)
1367             .setIncludeDirsCallback([](const Multilib &M) {
1368               return std::vector<std::string>({"/../../../../sysroot" +
1369                                                M.includeSuffix() +
1370                                                "/../usr/include"});
1371             })
1372             .setFilePathsCallback([](const Multilib &M) {
1373               return std::vector<std::string>(
1374                   {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1375             });
1376   }
1377   for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1378     if (Candidate->select(Flags, Result.SelectedMultilib)) {
1379       Result.Multilibs = *Candidate;
1380       return true;
1381     }
1382   }
1383   return false;
1384 }
1385 
1386 bool clang::driver::findMIPSMultilibs(const Driver &D,
1387                                       const llvm::Triple &TargetTriple,
1388                                       StringRef Path, const ArgList &Args,
1389                                       DetectedMultilibs &Result) {
1390   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1391 
1392   StringRef CPUName;
1393   StringRef ABIName;
1394   tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1395 
1396   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1397 
1398   Multilib::flags_list Flags;
1399   addMultilibFlag(TargetTriple.isMIPS32(), "m32", Flags);
1400   addMultilibFlag(TargetTriple.isMIPS64(), "m64", Flags);
1401   addMultilibFlag(isMips16(Args), "mips16", Flags);
1402   addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1403   addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1404                       CPUName == "mips32r5" || CPUName == "p5600",
1405                   "march=mips32r2", Flags);
1406   addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1407   addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1408   addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1409                       CPUName == "mips64r5" || CPUName == "octeon" ||
1410                       CPUName == "octeon+",
1411                   "march=mips64r2", Flags);
1412   addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
1413   addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1414   addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1415   addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1416                   Flags);
1417   addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1418   addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1419   addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1420   addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1421   addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1422   addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1423 
1424   if (TargetTriple.isAndroid())
1425     return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1426                                     Result);
1427 
1428   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1429       TargetTriple.getOS() == llvm::Triple::Linux &&
1430       TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1431     return findMipsMuslMultilibs(Flags, NonExistent, Result);
1432 
1433   if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1434       TargetTriple.getOS() == llvm::Triple::Linux &&
1435       TargetTriple.isGNUEnvironment())
1436     return findMipsMtiMultilibs(Flags, NonExistent, Result);
1437 
1438   if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1439       TargetTriple.getOS() == llvm::Triple::Linux &&
1440       TargetTriple.isGNUEnvironment())
1441     return findMipsImgMultilibs(Flags, NonExistent, Result);
1442 
1443   if (findMipsCsMultilibs(Flags, NonExistent, Result))
1444     return true;
1445 
1446   // Fallback to the regular toolchain-tree structure.
1447   Multilib Default;
1448   Result.Multilibs.push_back(Default);
1449   Result.Multilibs.FilterOut(NonExistent);
1450 
1451   if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1452     Result.BiarchSibling = Multilib();
1453     return true;
1454   }
1455 
1456   return false;
1457 }
1458 
1459 static void findAndroidArmMultilibs(const Driver &D,
1460                                     const llvm::Triple &TargetTriple,
1461                                     StringRef Path, const ArgList &Args,
1462                                     DetectedMultilibs &Result) {
1463   // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1464   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1465   Multilib ArmV7Multilib = makeMultilib("/armv7-a")
1466                                .flag("+march=armv7-a")
1467                                .flag("-mthumb");
1468   Multilib ThumbMultilib = makeMultilib("/thumb")
1469                                .flag("-march=armv7-a")
1470                                .flag("+mthumb");
1471   Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
1472                                .flag("+march=armv7-a")
1473                                .flag("+mthumb");
1474   Multilib DefaultMultilib = makeMultilib("")
1475                                .flag("-march=armv7-a")
1476                                .flag("-mthumb");
1477   MultilibSet AndroidArmMultilibs =
1478       MultilibSet()
1479           .Either(ThumbMultilib, ArmV7Multilib,
1480                   ArmV7ThumbMultilib, DefaultMultilib)
1481           .FilterOut(NonExistent);
1482 
1483   Multilib::flags_list Flags;
1484   llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1485   bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1486   bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1487   bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1488   bool IsThumbMode = IsThumbArch ||
1489       Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1490       (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1491   bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1492       (llvm::ARM::parseArchVersion(Arch) == 7 ||
1493        (IsArmArch && Arch == "" && IsV7SubArch));
1494   addMultilibFlag(IsArmV7Mode, "march=armv7-a", Flags);
1495   addMultilibFlag(IsThumbMode, "mthumb", Flags);
1496 
1497   if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
1498     Result.Multilibs = AndroidArmMultilibs;
1499 }
1500 
1501 static bool findMSP430Multilibs(const Driver &D,
1502                                 const llvm::Triple &TargetTriple,
1503                                 StringRef Path, const ArgList &Args,
1504                                 DetectedMultilibs &Result) {
1505   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1506   Multilib MSP430Multilib = makeMultilib("/430");
1507   // FIXME: when clang starts to support msp430x ISA additional logic
1508   // to select between multilib must be implemented
1509   // Multilib MSP430xMultilib = makeMultilib("/large");
1510 
1511   Result.Multilibs.push_back(MSP430Multilib);
1512   Result.Multilibs.FilterOut(NonExistent);
1513 
1514   Multilib::flags_list Flags;
1515   if (Result.Multilibs.select(Flags, Result.SelectedMultilib))
1516     return true;
1517 
1518   return false;
1519 }
1520 
1521 static void findRISCVBareMetalMultilibs(const Driver &D,
1522                                         const llvm::Triple &TargetTriple,
1523                                         StringRef Path, const ArgList &Args,
1524                                         DetectedMultilibs &Result) {
1525   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1526   struct RiscvMultilib {
1527     StringRef march;
1528     StringRef mabi;
1529   };
1530   // currently only support the set of multilibs like riscv-gnu-toolchain does.
1531   // TODO: support MULTILIB_REUSE
1532   SmallVector<RiscvMultilib, 8> RISCVMultilibSet = {
1533       {"rv32i", "ilp32"},     {"rv32im", "ilp32"},     {"rv32iac", "ilp32"},
1534       {"rv32imac", "ilp32"},  {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1535       {"rv64imafdc", "lp64d"}};
1536 
1537   std::vector<Multilib> Ms;
1538   for (auto Element : RISCVMultilibSet) {
1539     // multilib path rule is ${march}/${mabi}
1540     Ms.emplace_back(
1541         makeMultilib((Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1542             .flag(Twine("+march=", Element.march).str())
1543             .flag(Twine("+mabi=", Element.mabi).str()));
1544   }
1545   MultilibSet RISCVMultilibs =
1546       MultilibSet()
1547           .Either(ArrayRef<Multilib>(Ms))
1548           .FilterOut(NonExistent)
1549           .setFilePathsCallback([](const Multilib &M) {
1550             return std::vector<std::string>(
1551                 {M.gccSuffix(),
1552                  "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1553                  "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1554           });
1555 
1556 
1557   Multilib::flags_list Flags;
1558   llvm::StringSet<> Added_ABIs;
1559   StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1560   StringRef MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1561   for (auto Element : RISCVMultilibSet) {
1562     addMultilibFlag(MArch == Element.march,
1563                     Twine("march=", Element.march).str().c_str(), Flags);
1564     if (!Added_ABIs.count(Element.mabi)) {
1565       Added_ABIs.insert(Element.mabi);
1566       addMultilibFlag(ABIName == Element.mabi,
1567                       Twine("mabi=", Element.mabi).str().c_str(), Flags);
1568     }
1569   }
1570 
1571   if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1572     Result.Multilibs = RISCVMultilibs;
1573 }
1574 
1575 static void findRISCVMultilibs(const Driver &D,
1576                                const llvm::Triple &TargetTriple, StringRef Path,
1577                                const ArgList &Args, DetectedMultilibs &Result) {
1578   if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1579     return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1580 
1581   FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1582   Multilib Ilp32 = makeMultilib("lib32/ilp32").flag("+m32").flag("+mabi=ilp32");
1583   Multilib Ilp32f =
1584       makeMultilib("lib32/ilp32f").flag("+m32").flag("+mabi=ilp32f");
1585   Multilib Ilp32d =
1586       makeMultilib("lib32/ilp32d").flag("+m32").flag("+mabi=ilp32d");
1587   Multilib Lp64 = makeMultilib("lib64/lp64").flag("+m64").flag("+mabi=lp64");
1588   Multilib Lp64f = makeMultilib("lib64/lp64f").flag("+m64").flag("+mabi=lp64f");
1589   Multilib Lp64d = makeMultilib("lib64/lp64d").flag("+m64").flag("+mabi=lp64d");
1590   MultilibSet RISCVMultilibs =
1591       MultilibSet()
1592           .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1593           .FilterOut(NonExistent);
1594 
1595   Multilib::flags_list Flags;
1596   bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1597   StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1598 
1599   addMultilibFlag(!IsRV64, "m32", Flags);
1600   addMultilibFlag(IsRV64, "m64", Flags);
1601   addMultilibFlag(ABIName == "ilp32", "mabi=ilp32", Flags);
1602   addMultilibFlag(ABIName == "ilp32f", "mabi=ilp32f", Flags);
1603   addMultilibFlag(ABIName == "ilp32d", "mabi=ilp32d", Flags);
1604   addMultilibFlag(ABIName == "lp64", "mabi=lp64", Flags);
1605   addMultilibFlag(ABIName == "lp64f", "mabi=lp64f", Flags);
1606   addMultilibFlag(ABIName == "lp64d", "mabi=lp64d", Flags);
1607 
1608   if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1609     Result.Multilibs = RISCVMultilibs;
1610 }
1611 
1612 static bool findBiarchMultilibs(const Driver &D,
1613                                 const llvm::Triple &TargetTriple,
1614                                 StringRef Path, const ArgList &Args,
1615                                 bool NeedsBiarchSuffix,
1616                                 DetectedMultilibs &Result) {
1617   Multilib Default;
1618 
1619   // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1620   // in what would normally be GCCInstallPath and put the 64-bit
1621   // libs in a subdirectory named 64. The simple logic we follow is that
1622   // *if* there is a subdirectory of the right name with crtbegin.o in it,
1623   // we use that. If not, and if not a biarch triple alias, we look for
1624   // crtbegin.o without the subdirectory.
1625 
1626   StringRef Suff64 = "/64";
1627   // Solaris uses platform-specific suffixes instead of /64.
1628   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1629     switch (TargetTriple.getArch()) {
1630     case llvm::Triple::x86:
1631     case llvm::Triple::x86_64:
1632       Suff64 = "/amd64";
1633       break;
1634     case llvm::Triple::sparc:
1635     case llvm::Triple::sparcv9:
1636       Suff64 = "/sparcv9";
1637       break;
1638     default:
1639       break;
1640     }
1641   }
1642 
1643   Multilib Alt64 = Multilib()
1644                        .gccSuffix(Suff64)
1645                        .includeSuffix(Suff64)
1646                        .flag("-m32")
1647                        .flag("+m64")
1648                        .flag("-mx32");
1649   Multilib Alt32 = Multilib()
1650                        .gccSuffix("/32")
1651                        .includeSuffix("/32")
1652                        .flag("+m32")
1653                        .flag("-m64")
1654                        .flag("-mx32");
1655   Multilib Altx32 = Multilib()
1656                         .gccSuffix("/x32")
1657                         .includeSuffix("/x32")
1658                         .flag("-m32")
1659                         .flag("-m64")
1660                         .flag("+mx32");
1661 
1662   // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
1663   FilterNonExistent NonExistent(
1664       Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
1665 
1666   // Determine default multilib from: 32, 64, x32
1667   // Also handle cases such as 64 on 32, 32 on 64, etc.
1668   enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1669   const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1670   if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1671     Want = WANT64;
1672   else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1673     Want = WANT64;
1674   else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1675     Want = WANT32;
1676   else {
1677     if (TargetTriple.isArch32Bit())
1678       Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1679     else if (IsX32)
1680       Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1681     else
1682       Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1683   }
1684 
1685   if (Want == WANT32)
1686     Default.flag("+m32").flag("-m64").flag("-mx32");
1687   else if (Want == WANT64)
1688     Default.flag("-m32").flag("+m64").flag("-mx32");
1689   else if (Want == WANTX32)
1690     Default.flag("-m32").flag("-m64").flag("+mx32");
1691   else
1692     return false;
1693 
1694   Result.Multilibs.push_back(Default);
1695   Result.Multilibs.push_back(Alt64);
1696   Result.Multilibs.push_back(Alt32);
1697   Result.Multilibs.push_back(Altx32);
1698 
1699   Result.Multilibs.FilterOut(NonExistent);
1700 
1701   Multilib::flags_list Flags;
1702   addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1703   addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1704   addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1705 
1706   if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1707     return false;
1708 
1709   if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
1710       Result.SelectedMultilib == Altx32)
1711     Result.BiarchSibling = Default;
1712 
1713   return true;
1714 }
1715 
1716 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1717 /// all subcommands; this relies on gcc translating the majority of
1718 /// command line options.
1719 
1720 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
1721 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1722                                           int RHSPatch,
1723                                           StringRef RHSPatchSuffix) const {
1724   if (Major != RHSMajor)
1725     return Major < RHSMajor;
1726   if (Minor != RHSMinor)
1727     return Minor < RHSMinor;
1728   if (Patch != RHSPatch) {
1729     // Note that versions without a specified patch sort higher than those with
1730     // a patch.
1731     if (RHSPatch == -1)
1732       return true;
1733     if (Patch == -1)
1734       return false;
1735 
1736     // Otherwise just sort on the patch itself.
1737     return Patch < RHSPatch;
1738   }
1739   if (PatchSuffix != RHSPatchSuffix) {
1740     // Sort empty suffixes higher.
1741     if (RHSPatchSuffix.empty())
1742       return true;
1743     if (PatchSuffix.empty())
1744       return false;
1745 
1746     // Provide a lexicographic sort to make this a total ordering.
1747     return PatchSuffix < RHSPatchSuffix;
1748   }
1749 
1750   // The versions are equal.
1751   return false;
1752 }
1753 
1754 /// Parse a GCCVersion object out of a string of text.
1755 ///
1756 /// This is the primary means of forming GCCVersion objects.
1757 /*static*/
1758 Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
1759   const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1760   std::pair<StringRef, StringRef> First = VersionText.split('.');
1761   std::pair<StringRef, StringRef> Second = First.second.split('.');
1762 
1763   GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1764   if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1765     return BadVersion;
1766   GoodVersion.MajorStr = First.first.str();
1767   if (First.second.empty())
1768     return GoodVersion;
1769   StringRef MinorStr = Second.first;
1770   if (Second.second.empty()) {
1771     if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
1772       GoodVersion.PatchSuffix = MinorStr.substr(EndNumber);
1773       MinorStr = MinorStr.slice(0, EndNumber);
1774     }
1775   }
1776   if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1777     return BadVersion;
1778   GoodVersion.MinorStr = MinorStr.str();
1779 
1780   // First look for a number prefix and parse that if present. Otherwise just
1781   // stash the entire patch string in the suffix, and leave the number
1782   // unspecified. This covers versions strings such as:
1783   //   5        (handled above)
1784   //   4.4
1785   //   4.4-patched
1786   //   4.4.0
1787   //   4.4.x
1788   //   4.4.2-rc4
1789   //   4.4.x-patched
1790   // And retains any patch number it finds.
1791   StringRef PatchText = Second.second;
1792   if (!PatchText.empty()) {
1793     if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1794       // Try to parse the number and any suffix.
1795       if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1796           GoodVersion.Patch < 0)
1797         return BadVersion;
1798       GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1799     }
1800   }
1801 
1802   return GoodVersion;
1803 }
1804 
1805 static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
1806                                           llvm::StringRef SysRoot) {
1807   const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
1808   if (A)
1809     return A->getValue();
1810 
1811   // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
1812   // GCC_INSTALL_PREFIX specifies the gcc installation for the default
1813   // sysroot and is likely not valid with a different sysroot.
1814   if (!SysRoot.empty())
1815     return "";
1816 
1817   return GCC_INSTALL_PREFIX;
1818 }
1819 
1820 /// Initialize a GCCInstallationDetector from the driver.
1821 ///
1822 /// This performs all of the autodetection and sets up the various paths.
1823 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1824 ///
1825 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1826 /// should instead pull the target out of the driver. This is currently
1827 /// necessary because the driver doesn't store the final version of the target
1828 /// triple.
1829 void Generic_GCC::GCCInstallationDetector::init(
1830     const llvm::Triple &TargetTriple, const ArgList &Args,
1831     ArrayRef<std::string> ExtraTripleAliases) {
1832   llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1833                                          ? TargetTriple.get64BitArchVariant()
1834                                          : TargetTriple.get32BitArchVariant();
1835   // The library directories which may contain GCC installations.
1836   SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1837   // The compatible GCC triples for this particular architecture.
1838   SmallVector<StringRef, 16> CandidateTripleAliases;
1839   SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1840   CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1841                            CandidateTripleAliases, CandidateBiarchLibDirs,
1842                            CandidateBiarchTripleAliases);
1843 
1844   // Compute the set of prefixes for our search.
1845   SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1846                                        D.PrefixDirs.end());
1847 
1848   StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
1849   if (GCCToolchainDir != "") {
1850     if (GCCToolchainDir.back() == '/')
1851       GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1852 
1853     Prefixes.push_back(GCCToolchainDir);
1854   } else {
1855     // If we have a SysRoot, try that first.
1856     if (!D.SysRoot.empty()) {
1857       Prefixes.push_back(D.SysRoot);
1858       AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1859     }
1860 
1861     // Then look for gcc installed alongside clang.
1862     Prefixes.push_back(D.InstalledDir + "/..");
1863 
1864     // Next, look for prefix(es) that correspond to distribution-supplied gcc
1865     // installations.
1866     if (D.SysRoot.empty()) {
1867       // Typically /usr.
1868       AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1869     }
1870   }
1871 
1872   // Try to respect gcc-config on Gentoo. However, do that only
1873   // if --gcc-toolchain is not provided or equal to the Gentoo install
1874   // in /usr. This avoids accidentally enforcing the system GCC version
1875   // when using a custom toolchain.
1876   if (GCCToolchainDir == "" || GCCToolchainDir == D.SysRoot + "/usr") {
1877     SmallVector<StringRef, 16> GentooTestTriples;
1878     // Try to match an exact triple as target triple first.
1879     // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
1880     // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
1881     // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
1882     // triple x86_64-gentoo-linux-gnu is present.
1883     GentooTestTriples.push_back(TargetTriple.str());
1884     // Check rest of triples.
1885     GentooTestTriples.append(ExtraTripleAliases.begin(),
1886                              ExtraTripleAliases.end());
1887     GentooTestTriples.append(CandidateTripleAliases.begin(),
1888                              CandidateTripleAliases.end());
1889     if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
1890                           CandidateBiarchTripleAliases))
1891       return;
1892   }
1893 
1894   // Loop over the various components which exist and select the best GCC
1895   // installation available. GCC installs are ranked by version number.
1896   Version = GCCVersion::Parse("0.0.0");
1897   for (const std::string &Prefix : Prefixes) {
1898     if (!D.getVFS().exists(Prefix))
1899       continue;
1900     for (StringRef Suffix : CandidateLibDirs) {
1901       const std::string LibDir = Prefix + Suffix.str();
1902       if (!D.getVFS().exists(LibDir))
1903         continue;
1904       // Try to match the exact target triple first.
1905       ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str());
1906       // Try rest of possible triples.
1907       for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1908         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1909       for (StringRef Candidate : CandidateTripleAliases)
1910         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1911     }
1912     for (StringRef Suffix : CandidateBiarchLibDirs) {
1913       const std::string LibDir = Prefix + Suffix.str();
1914       if (!D.getVFS().exists(LibDir))
1915         continue;
1916       for (StringRef Candidate : CandidateBiarchTripleAliases)
1917         ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1918                                /*NeedsBiarchSuffix=*/ true);
1919     }
1920   }
1921 }
1922 
1923 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1924   for (const auto &InstallPath : CandidateGCCInstallPaths)
1925     OS << "Found candidate GCC installation: " << InstallPath << "\n";
1926 
1927   if (!GCCInstallPath.empty())
1928     OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1929 
1930   for (const auto &Multilib : Multilibs)
1931     OS << "Candidate multilib: " << Multilib << "\n";
1932 
1933   if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1934     OS << "Selected multilib: " << SelectedMultilib << "\n";
1935 }
1936 
1937 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1938   if (BiarchSibling.hasValue()) {
1939     M = BiarchSibling.getValue();
1940     return true;
1941   }
1942   return false;
1943 }
1944 
1945 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
1946     const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
1947     StringRef SysRoot) {
1948   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1949     // Solaris is a special case.
1950     // The GCC installation is under
1951     //   /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
1952     // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
1953     // /usr/gcc/<version> as a prefix.
1954 
1955     std::string PrefixDir = SysRoot.str() + "/usr/gcc";
1956     std::error_code EC;
1957     for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
1958                                        LE;
1959          !EC && LI != LE; LI = LI.increment(EC)) {
1960       StringRef VersionText = llvm::sys::path::filename(LI->path());
1961       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1962 
1963       // Filter out obviously bad entries.
1964       if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
1965         continue;
1966 
1967       std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
1968       std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
1969       if (!D.getVFS().exists(CandidateLibPath))
1970         continue;
1971 
1972       Prefixes.push_back(CandidatePrefix);
1973     }
1974     return;
1975   }
1976 
1977   // Non-Solaris is much simpler - most systems just go with "/usr".
1978   if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
1979     // Yet, still look for RHEL devtoolsets.
1980     Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
1981     Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
1982     Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
1983     Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
1984     Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
1985     Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
1986   }
1987   Prefixes.push_back(SysRoot.str() + "/usr");
1988 }
1989 
1990 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1991     const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1992     SmallVectorImpl<StringRef> &LibDirs,
1993     SmallVectorImpl<StringRef> &TripleAliases,
1994     SmallVectorImpl<StringRef> &BiarchLibDirs,
1995     SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1996   // Declare a bunch of static data sets that we'll select between below. These
1997   // are specifically designed to always refer to string literals to avoid any
1998   // lifetime or initialization issues.
1999   static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2000   static const char *const AArch64Triples[] = {
2001       "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
2002       "aarch64-suse-linux", "aarch64-linux-android"};
2003   static const char *const AArch64beLibDirs[] = {"/lib"};
2004   static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
2005                                                  "aarch64_be-linux-gnu"};
2006 
2007   static const char *const ARMLibDirs[] = {"/lib"};
2008   static const char *const ARMTriples[] = {"arm-linux-gnueabi",
2009                                            "arm-linux-androideabi"};
2010   static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2011                                              "armv7hl-redhat-linux-gnueabi",
2012                                              "armv6hl-suse-linux-gnueabi",
2013                                              "armv7hl-suse-linux-gnueabi"};
2014   static const char *const ARMebLibDirs[] = {"/lib"};
2015   static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
2016                                              "armeb-linux-androideabi"};
2017   static const char *const ARMebHFTriples[] = {
2018       "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2019 
2020   static const char *const AVRLibDirs[] = {"/lib"};
2021   static const char *const AVRTriples[] = {"avr"};
2022 
2023   static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2024   static const char *const X86_64Triples[] = {
2025       "x86_64-linux-gnu",       "x86_64-unknown-linux-gnu",
2026       "x86_64-pc-linux-gnu",    "x86_64-redhat-linux6E",
2027       "x86_64-redhat-linux",    "x86_64-suse-linux",
2028       "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
2029       "x86_64-slackware-linux", "x86_64-unknown-linux",
2030       "x86_64-amazon-linux",    "x86_64-linux-android"};
2031   static const char *const X32LibDirs[] = {"/libx32"};
2032   static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2033   static const char *const X86Triples[] = {
2034       "i686-linux-gnu",       "i686-pc-linux-gnu",     "i486-linux-gnu",
2035       "i386-linux-gnu",       "i386-redhat-linux6E",   "i686-redhat-linux",
2036       "i586-redhat-linux",    "i386-redhat-linux",     "i586-suse-linux",
2037       "i486-slackware-linux", "i686-montavista-linux", "i586-linux-gnu",
2038       "i686-linux-android",   "i386-gnu",              "i486-gnu",
2039       "i586-gnu",             "i686-gnu"};
2040 
2041   static const char *const MIPSLibDirs[] = {"/lib"};
2042   static const char *const MIPSTriples[] = {
2043       "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2044       "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2045   static const char *const MIPSELLibDirs[] = {"/lib"};
2046   static const char *const MIPSELTriples[] = {
2047       "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu",
2048       "mipsel-linux-android"};
2049 
2050   static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2051   static const char *const MIPS64Triples[] = {
2052       "mips64-linux-gnu",      "mips-mti-linux-gnu",
2053       "mips-img-linux-gnu",    "mips64-linux-gnuabi64",
2054       "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2055   static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2056   static const char *const MIPS64ELTriples[] = {
2057       "mips64el-linux-gnu",      "mips-mti-linux-gnu",
2058       "mips-img-linux-gnu",      "mips64el-linux-gnuabi64",
2059       "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64",
2060       "mips64el-linux-android"};
2061 
2062   static const char *const MIPSN32LibDirs[] = {"/lib32"};
2063   static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2064                                                "mipsisa64r6-linux-gnuabin32"};
2065   static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2066   static const char *const MIPSN32ELTriples[] = {
2067       "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2068 
2069   static const char *const MSP430LibDirs[] = {"/lib"};
2070   static const char *const MSP430Triples[] = {"msp430-elf"};
2071 
2072   static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2073   static const char *const PPCTriples[] = {
2074       "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
2075       // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2076       // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2077       "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2078   static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2079   static const char *const PPC64Triples[] = {
2080       "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
2081       "powerpc64-suse-linux", "ppc64-redhat-linux"};
2082   static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2083   static const char *const PPC64LETriples[] = {
2084       "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
2085       "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
2086 
2087   static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2088   static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2089                                                "riscv32-linux-gnu",
2090                                                "riscv32-unknown-elf"};
2091   static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2092   static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2093                                                "riscv64-linux-gnu",
2094                                                "riscv64-unknown-elf",
2095                                                "riscv64-suse-linux"};
2096 
2097   static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2098   static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2099                                                "sparcv8-linux-gnu"};
2100   static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2101   static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2102                                                "sparcv9-linux-gnu"};
2103 
2104   static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2105   static const char *const SystemZTriples[] = {
2106       "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
2107       "s390x-suse-linux", "s390x-redhat-linux"};
2108 
2109 
2110   using std::begin;
2111   using std::end;
2112 
2113   if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2114     static const char *const SolarisLibDirs[] = {"/lib"};
2115     static const char *const SolarisSparcV8Triples[] = {
2116         "sparc-sun-solaris2.11", "sparc-sun-solaris2.12"};
2117     static const char *const SolarisSparcV9Triples[] = {
2118         "sparcv9-sun-solaris2.11", "sparcv9-sun-solaris2.12"};
2119     static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11",
2120                                                     "i386-pc-solaris2.12"};
2121     static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11",
2122                                                        "x86_64-pc-solaris2.12"};
2123     LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2124     BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2125     switch (TargetTriple.getArch()) {
2126     case llvm::Triple::x86:
2127       TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2128       BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2129                                  end(SolarisX86_64Triples));
2130       break;
2131     case llvm::Triple::x86_64:
2132       TripleAliases.append(begin(SolarisX86_64Triples),
2133                            end(SolarisX86_64Triples));
2134       BiarchTripleAliases.append(begin(SolarisX86Triples),
2135                                  end(SolarisX86Triples));
2136       break;
2137     case llvm::Triple::sparc:
2138       TripleAliases.append(begin(SolarisSparcV8Triples),
2139                            end(SolarisSparcV8Triples));
2140       BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2141                                  end(SolarisSparcV9Triples));
2142       break;
2143     case llvm::Triple::sparcv9:
2144       TripleAliases.append(begin(SolarisSparcV9Triples),
2145                            end(SolarisSparcV9Triples));
2146       BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2147                                  end(SolarisSparcV8Triples));
2148       break;
2149     default:
2150       break;
2151     }
2152     return;
2153   }
2154 
2155   // Android targets should not use GNU/Linux tools or libraries.
2156   if (TargetTriple.isAndroid()) {
2157     static const char *const AArch64AndroidTriples[] = {
2158         "aarch64-linux-android"};
2159     static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2160     static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
2161     static const char *const MIPS64ELAndroidTriples[] = {
2162         "mips64el-linux-android"};
2163     static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2164     static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2165 
2166     switch (TargetTriple.getArch()) {
2167     case llvm::Triple::aarch64:
2168       LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2169       TripleAliases.append(begin(AArch64AndroidTriples),
2170                            end(AArch64AndroidTriples));
2171       break;
2172     case llvm::Triple::arm:
2173     case llvm::Triple::thumb:
2174       LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2175       TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2176       break;
2177     case llvm::Triple::mipsel:
2178       LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2179       TripleAliases.append(begin(MIPSELAndroidTriples),
2180                            end(MIPSELAndroidTriples));
2181       BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2182       BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
2183                                  end(MIPS64ELAndroidTriples));
2184       break;
2185     case llvm::Triple::mips64el:
2186       LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2187       TripleAliases.append(begin(MIPS64ELAndroidTriples),
2188                            end(MIPS64ELAndroidTriples));
2189       BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2190       BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
2191                                  end(MIPSELAndroidTriples));
2192       break;
2193     case llvm::Triple::x86_64:
2194       LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2195       TripleAliases.append(begin(X86_64AndroidTriples),
2196                            end(X86_64AndroidTriples));
2197       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2198       BiarchTripleAliases.append(begin(X86AndroidTriples),
2199                                  end(X86AndroidTriples));
2200       break;
2201     case llvm::Triple::x86:
2202       LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2203       TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2204       BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2205       BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2206                                  end(X86_64AndroidTriples));
2207       break;
2208     default:
2209       break;
2210     }
2211 
2212     return;
2213   }
2214 
2215   switch (TargetTriple.getArch()) {
2216   case llvm::Triple::aarch64:
2217     LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2218     TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2219     BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2220     BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2221     break;
2222   case llvm::Triple::aarch64_be:
2223     LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2224     TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2225     BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2226     BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2227     break;
2228   case llvm::Triple::arm:
2229   case llvm::Triple::thumb:
2230     LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2231     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2232       TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2233     } else {
2234       TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2235     }
2236     break;
2237   case llvm::Triple::armeb:
2238   case llvm::Triple::thumbeb:
2239     LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2240     if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2241       TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2242     } else {
2243       TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2244     }
2245     break;
2246   case llvm::Triple::avr:
2247     LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2248     TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2249     break;
2250   case llvm::Triple::x86_64:
2251     LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2252     TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2253     // x32 is always available when x86_64 is available, so adding it as
2254     // secondary arch with x86_64 triples
2255     if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
2256       BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2257       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2258     } else {
2259       BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2260       BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2261     }
2262     break;
2263   case llvm::Triple::x86:
2264     LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2265     // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2266     // itself, which will be appended below.
2267     if (!TargetTriple.isOSIAMCU()) {
2268       TripleAliases.append(begin(X86Triples), end(X86Triples));
2269       BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2270       BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2271     }
2272     break;
2273   case llvm::Triple::mips:
2274     LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2275     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2276     BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2277     BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2278     BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2279     BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2280     break;
2281   case llvm::Triple::mipsel:
2282     LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2283     TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2284     TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2285     BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2286     BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2287     BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2288     BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2289     break;
2290   case llvm::Triple::mips64:
2291     LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2292     TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2293     BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2294     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2295     BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2296     BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2297     break;
2298   case llvm::Triple::mips64el:
2299     LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2300     TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2301     BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2302     BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2303     BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2304     BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2305     BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2306     break;
2307   case llvm::Triple::msp430:
2308     LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2309     TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2310     break;
2311   case llvm::Triple::ppc:
2312     LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2313     TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2314     BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2315     BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2316     break;
2317   case llvm::Triple::ppc64:
2318     LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2319     TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2320     BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2321     BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2322     break;
2323   case llvm::Triple::ppc64le:
2324     LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2325     TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2326     break;
2327   case llvm::Triple::riscv32:
2328     LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2329     TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2330     BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2331     BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2332     break;
2333   case llvm::Triple::riscv64:
2334     LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2335     TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2336     BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2337     BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2338     break;
2339   case llvm::Triple::sparc:
2340   case llvm::Triple::sparcel:
2341     LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2342     TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2343     BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2344     BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2345     break;
2346   case llvm::Triple::sparcv9:
2347     LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2348     TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2349     BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2350     BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2351     break;
2352   case llvm::Triple::systemz:
2353     LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2354     TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2355     break;
2356   default:
2357     // By default, just rely on the standard lib directories and the original
2358     // triple.
2359     break;
2360   }
2361 
2362   // Always append the drivers target triple to the end, in case it doesn't
2363   // match any of our aliases.
2364   TripleAliases.push_back(TargetTriple.str());
2365 
2366   // Also include the multiarch variant if it's different.
2367   if (TargetTriple.str() != BiarchTriple.str())
2368     BiarchTripleAliases.push_back(BiarchTriple.str());
2369 }
2370 
2371 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2372     const llvm::Triple &TargetTriple, const ArgList &Args,
2373     StringRef Path, bool NeedsBiarchSuffix) {
2374   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2375   DetectedMultilibs Detected;
2376 
2377   // Android standalone toolchain could have multilibs for ARM and Thumb.
2378   // Debian mips multilibs behave more like the rest of the biarch ones,
2379   // so handle them there
2380   if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2381     // It should also work without multilibs in a simplified toolchain.
2382     findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2383   } else if (TargetTriple.isMIPS()) {
2384     if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2385       return false;
2386   } else if (TargetTriple.isRISCV()) {
2387     findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2388   } else if (isMSP430(TargetArch)) {
2389     findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2390   } else if (TargetArch == llvm::Triple::avr) {
2391     // AVR has no multilibs.
2392   } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2393                                   NeedsBiarchSuffix, Detected)) {
2394     return false;
2395   }
2396 
2397   Multilibs = Detected.Multilibs;
2398   SelectedMultilib = Detected.SelectedMultilib;
2399   BiarchSibling = Detected.BiarchSibling;
2400 
2401   return true;
2402 }
2403 
2404 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2405     const llvm::Triple &TargetTriple, const ArgList &Args,
2406     const std::string &LibDir, StringRef CandidateTriple,
2407     bool NeedsBiarchSuffix) {
2408   llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2409   // Locations relative to the system lib directory where GCC's triple-specific
2410   // directories might reside.
2411   struct GCCLibSuffix {
2412     // Path from system lib directory to GCC triple-specific directory.
2413     std::string LibSuffix;
2414     // Path from GCC triple-specific directory back to system lib directory.
2415     // This is one '..' component per component in LibSuffix.
2416     StringRef ReversePath;
2417     // Whether this library suffix is relevant for the triple.
2418     bool Active;
2419   } Suffixes[] = {
2420       // This is the normal place.
2421       {"gcc/" + CandidateTriple.str(), "../..", true},
2422 
2423       // Debian puts cross-compilers in gcc-cross.
2424       {"gcc-cross/" + CandidateTriple.str(), "../..",
2425        TargetTriple.getOS() != llvm::Triple::Solaris},
2426 
2427       // The Freescale PPC SDK has the gcc libraries in
2428       // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2429       // this on Freescale triples, though, since some systems put a *lot* of
2430       // files in that location, not just GCC installation data.
2431       {CandidateTriple.str(), "..",
2432        TargetTriple.getVendor() == llvm::Triple::Freescale ||
2433        TargetTriple.getVendor() == llvm::Triple::OpenEmbedded},
2434 
2435       // Natively multiarch systems sometimes put the GCC triple-specific
2436       // directory within their multiarch lib directory, resulting in the
2437       // triple appearing twice.
2438       {CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), "../../..",
2439        TargetTriple.getOS() != llvm::Triple::Solaris},
2440 
2441       // Deal with cases (on Ubuntu) where the system architecture could be i386
2442       // but the GCC target architecture could be (say) i686.
2443       // FIXME: It may be worthwhile to generalize this and look for a second
2444       // triple.
2445       {"i386-linux-gnu/gcc/" + CandidateTriple.str(), "../../..",
2446        (TargetArch == llvm::Triple::x86 &&
2447         TargetTriple.getOS() != llvm::Triple::Solaris)},
2448       {"i386-gnu/gcc/" + CandidateTriple.str(), "../../..",
2449        (TargetArch == llvm::Triple::x86 &&
2450         TargetTriple.getOS() != llvm::Triple::Solaris)}};
2451 
2452   for (auto &Suffix : Suffixes) {
2453     if (!Suffix.Active)
2454       continue;
2455 
2456     StringRef LibSuffix = Suffix.LibSuffix;
2457     std::error_code EC;
2458     for (llvm::vfs::directory_iterator
2459              LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2460              LE;
2461          !EC && LI != LE; LI = LI.increment(EC)) {
2462       StringRef VersionText = llvm::sys::path::filename(LI->path());
2463       GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2464       if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2465         if (!CandidateGCCInstallPaths.insert(LI->path()).second)
2466           continue; // Saw this path before; no need to look at it again.
2467       if (CandidateVersion.isOlderThan(4, 1, 1))
2468         continue;
2469       if (CandidateVersion <= Version)
2470         continue;
2471 
2472       if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2473                                NeedsBiarchSuffix))
2474         continue;
2475 
2476       Version = CandidateVersion;
2477       GCCTriple.setTriple(CandidateTriple);
2478       // FIXME: We hack together the directory name here instead of
2479       // using LI to ensure stable path separators across Windows and
2480       // Linux.
2481       GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2482       GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2483       IsValid = true;
2484     }
2485   }
2486 }
2487 
2488 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2489     const llvm::Triple &TargetTriple, const ArgList &Args,
2490     const SmallVectorImpl<StringRef> &CandidateTriples,
2491     const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2492   for (StringRef CandidateTriple : CandidateTriples) {
2493     if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2494       return true;
2495   }
2496 
2497   for (StringRef CandidateTriple : CandidateBiarchTriples) {
2498     if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2499       return true;
2500   }
2501   return false;
2502 }
2503 
2504 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2505     const llvm::Triple &TargetTriple, const ArgList &Args,
2506     StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2507   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2508       D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
2509                                   CandidateTriple.str());
2510   if (File) {
2511     SmallVector<StringRef, 2> Lines;
2512     File.get()->getBuffer().split(Lines, "\n");
2513     for (StringRef Line : Lines) {
2514       Line = Line.trim();
2515       // CURRENT=triple-version
2516       if (!Line.consume_front("CURRENT="))
2517         continue;
2518       // Process the config file pointed to by CURRENT.
2519       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2520           D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
2521                                       Line.str());
2522       std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2523       // List of paths to scan for libraries.
2524       SmallVector<StringRef, 4> GentooScanPaths;
2525       // Scan the Config file to find installed GCC libraries path.
2526       // Typical content of the GCC config file:
2527       // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2528       // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2529       // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2530       // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2531       // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2532       // We are looking for the paths listed in LDPATH=... .
2533       if (ConfigFile) {
2534         SmallVector<StringRef, 2> ConfigLines;
2535         ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2536         for (StringRef ConfLine : ConfigLines) {
2537           ConfLine = ConfLine.trim();
2538           if (ConfLine.consume_front("LDPATH=")) {
2539             // Drop '"' from front and back if present.
2540             ConfLine.consume_back("\"");
2541             ConfLine.consume_front("\"");
2542             // Get all paths sperated by ':'
2543             ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2544           }
2545         }
2546       }
2547       // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2548       std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2549           + ActiveVersion.second.str();
2550       GentooScanPaths.push_back(StringRef(basePath));
2551 
2552       // Scan all paths for GCC libraries.
2553       for (const auto &GentooScanPath : GentooScanPaths) {
2554         std::string GentooPath = D.SysRoot + std::string(GentooScanPath);
2555         if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2556           if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2557                                    NeedsBiarchSuffix))
2558             continue;
2559 
2560           Version = GCCVersion::Parse(ActiveVersion.second);
2561           GCCInstallPath = GentooPath;
2562           GCCParentLibPath = GentooPath + std::string("/../../..");
2563           GCCTriple.setTriple(ActiveVersion.first);
2564           IsValid = true;
2565           return true;
2566         }
2567       }
2568     }
2569   }
2570 
2571   return false;
2572 }
2573 
2574 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2575                          const ArgList &Args)
2576     : ToolChain(D, Triple, Args), GCCInstallation(D),
2577       CudaInstallation(D, Triple, Args) {
2578   getProgramPaths().push_back(getDriver().getInstalledDir());
2579   if (getDriver().getInstalledDir() != getDriver().Dir)
2580     getProgramPaths().push_back(getDriver().Dir);
2581 }
2582 
2583 Generic_GCC::~Generic_GCC() {}
2584 
2585 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2586   switch (AC) {
2587   case Action::PreprocessJobClass:
2588     if (!Preprocess)
2589       Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
2590     return Preprocess.get();
2591   case Action::CompileJobClass:
2592     if (!Compile)
2593       Compile.reset(new tools::gcc::Compiler(*this));
2594     return Compile.get();
2595   default:
2596     return ToolChain::getTool(AC);
2597   }
2598 }
2599 
2600 Tool *Generic_GCC::buildAssembler() const {
2601   return new tools::gnutools::Assembler(*this);
2602 }
2603 
2604 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2605 
2606 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2607   // Print the information about how we detected the GCC installation.
2608   GCCInstallation.print(OS);
2609   CudaInstallation.print(OS);
2610 }
2611 
2612 bool Generic_GCC::IsUnwindTablesDefault(const ArgList &Args) const {
2613   return getArch() == llvm::Triple::x86_64;
2614 }
2615 
2616 bool Generic_GCC::isPICDefault() const {
2617   switch (getArch()) {
2618   case llvm::Triple::x86_64:
2619     return getTriple().isOSWindows();
2620   case llvm::Triple::mips64:
2621   case llvm::Triple::mips64el:
2622     return true;
2623   default:
2624     return false;
2625   }
2626 }
2627 
2628 bool Generic_GCC::isPIEDefault() const { return false; }
2629 
2630 bool Generic_GCC::isPICDefaultForced() const {
2631   return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2632 }
2633 
2634 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2635   switch (getTriple().getArch()) {
2636   case llvm::Triple::x86:
2637   case llvm::Triple::x86_64:
2638   case llvm::Triple::aarch64:
2639   case llvm::Triple::aarch64_be:
2640   case llvm::Triple::arm:
2641   case llvm::Triple::armeb:
2642   case llvm::Triple::avr:
2643   case llvm::Triple::bpfel:
2644   case llvm::Triple::bpfeb:
2645   case llvm::Triple::thumb:
2646   case llvm::Triple::thumbeb:
2647   case llvm::Triple::ppc:
2648   case llvm::Triple::ppc64:
2649   case llvm::Triple::ppc64le:
2650   case llvm::Triple::riscv32:
2651   case llvm::Triple::riscv64:
2652   case llvm::Triple::systemz:
2653   case llvm::Triple::mips:
2654   case llvm::Triple::mipsel:
2655   case llvm::Triple::mips64:
2656   case llvm::Triple::mips64el:
2657   case llvm::Triple::msp430:
2658     return true;
2659   case llvm::Triple::sparc:
2660   case llvm::Triple::sparcel:
2661   case llvm::Triple::sparcv9:
2662     if (getTriple().isOSFreeBSD() || getTriple().isOSOpenBSD() ||
2663         getTriple().isOSSolaris())
2664       return true;
2665     return false;
2666   default:
2667     return false;
2668   }
2669 }
2670 
2671 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2672                                                ArgStringList &CC1Args) const {
2673   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2674       DriverArgs.hasArg(options::OPT_nostdincxx))
2675     return;
2676 
2677   switch (GetCXXStdlibType(DriverArgs)) {
2678   case ToolChain::CST_Libcxx:
2679     addLibCxxIncludePaths(DriverArgs, CC1Args);
2680     break;
2681 
2682   case ToolChain::CST_Libstdcxx:
2683     addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2684     break;
2685   }
2686 }
2687 
2688 static std::string DetectLibcxxIncludePath(llvm::vfs::FileSystem &vfs,
2689                                            StringRef base) {
2690   std::error_code EC;
2691   int MaxVersion = 0;
2692   std::string MaxVersionString;
2693   for (llvm::vfs::directory_iterator LI = vfs.dir_begin(base, EC), LE;
2694        !EC && LI != LE; LI = LI.increment(EC)) {
2695     StringRef VersionText = llvm::sys::path::filename(LI->path());
2696     int Version;
2697     if (VersionText[0] == 'v' &&
2698         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
2699       if (Version > MaxVersion) {
2700         MaxVersion = Version;
2701         MaxVersionString = VersionText;
2702       }
2703     }
2704   }
2705   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
2706 }
2707 
2708 void
2709 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2710                                    llvm::opt::ArgStringList &CC1Args) const {
2711   const std::string& SysRoot = getDriver().SysRoot;
2712   auto AddIncludePath = [&](std::string Path) {
2713     std::string IncludePath = DetectLibcxxIncludePath(getVFS(), Path);
2714     if (IncludePath.empty() || !getVFS().exists(IncludePath))
2715       return false;
2716     addSystemInclude(DriverArgs, CC1Args, IncludePath);
2717     return true;
2718   };
2719   // Android never uses the libc++ headers installed alongside the toolchain,
2720   // which are generally incompatible with the NDK libraries anyway.
2721   if (!getTriple().isAndroid())
2722     if (AddIncludePath(getDriver().Dir + "/../include/c++"))
2723       return;
2724   // If this is a development, non-installed, clang, libcxx will
2725   // not be found at ../include/c++ but it likely to be found at
2726   // one of the following two locations:
2727   if (AddIncludePath(SysRoot + "/usr/local/include/c++"))
2728     return;
2729   if (AddIncludePath(SysRoot + "/usr/include/c++"))
2730     return;
2731 }
2732 
2733 /// Helper to add the variant paths of a libstdc++ installation.
2734 bool Generic_GCC::addLibStdCXXIncludePaths(
2735     Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2736     StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2737     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2738   if (!getVFS().exists(Base + Suffix))
2739     return false;
2740 
2741   addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2742 
2743   // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2744   // that path exists or we have neither a GCC nor target multiarch triple, use
2745   // this vanilla search path.
2746   if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2747       getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2748     addSystemInclude(DriverArgs, CC1Args,
2749                      Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2750   } else {
2751     // Otherwise try to use multiarch naming schemes which have normalized the
2752     // triples and put the triple before the suffix.
2753     //
2754     // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2755     // the target triple, so we support that here.
2756     addSystemInclude(DriverArgs, CC1Args,
2757                      Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2758     addSystemInclude(DriverArgs, CC1Args,
2759                      Base + "/" + TargetMultiarchTriple + Suffix);
2760   }
2761 
2762   addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2763   return true;
2764 }
2765 
2766 bool
2767 Generic_GCC::addGCCLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2768                                          llvm::opt::ArgStringList &CC1Args) const {
2769   // Use GCCInstallation to know where libstdc++ headers are installed.
2770   if (!GCCInstallation.isValid())
2771     return false;
2772 
2773   // By default, look for the C++ headers in an include directory adjacent to
2774   // the lib directory of the GCC installation. Note that this is expect to be
2775   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
2776   StringRef LibDir = GCCInstallation.getParentLibPath();
2777   StringRef InstallDir = GCCInstallation.getInstallPath();
2778   StringRef TripleStr = GCCInstallation.getTriple().str();
2779   const Multilib &Multilib = GCCInstallation.getMultilib();
2780   const std::string GCCMultiarchTriple = getMultiarchTriple(
2781       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
2782   const std::string TargetMultiarchTriple =
2783       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
2784   const GCCVersion &Version = GCCInstallation.getVersion();
2785 
2786   // The primary search for libstdc++ supports multiarch variants.
2787   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
2788                                "/c++/" + Version.Text, TripleStr,
2789                                GCCMultiarchTriple, TargetMultiarchTriple,
2790                                Multilib.includeSuffix(), DriverArgs, CC1Args))
2791     return true;
2792 
2793   // Otherwise, fall back on a bunch of options which don't use multiarch
2794   // layouts for simplicity.
2795   const std::string LibStdCXXIncludePathCandidates[] = {
2796       // Gentoo is weird and places its headers inside the GCC install,
2797       // so if the first attempt to find the headers fails, try these patterns.
2798       InstallDir.str() + "/include/g++-v" + Version.Text,
2799       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
2800           Version.MinorStr,
2801       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
2802   };
2803 
2804   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
2805     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
2806                                  /*GCCMultiarchTriple*/ "",
2807                                  /*TargetMultiarchTriple*/ "",
2808                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
2809       return true;
2810   }
2811   return false;
2812 }
2813 
2814 void
2815 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2816                                       llvm::opt::ArgStringList &CC1Args) const {
2817   addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args);
2818 }
2819 
2820 llvm::opt::DerivedArgList *
2821 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
2822                            Action::OffloadKind DeviceOffloadKind) const {
2823 
2824   // If this tool chain is used for an OpenMP offloading device we have to make
2825   // sure we always generate a shared library regardless of the commands the
2826   // user passed to the host. This is required because the runtime library
2827   // is required to load the device image dynamically at run time.
2828   if (DeviceOffloadKind == Action::OFK_OpenMP) {
2829     DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2830     const OptTable &Opts = getDriver().getOpts();
2831 
2832     // Request the shared library. Given that these options are decided
2833     // implicitly, they do not refer to any base argument.
2834     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
2835     DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
2836 
2837     // Filter all the arguments we don't care passing to the offloading
2838     // toolchain as they can mess up with the creation of a shared library.
2839     for (auto *A : Args) {
2840       switch ((options::ID)A->getOption().getID()) {
2841       default:
2842         DAL->append(A);
2843         break;
2844       case options::OPT_shared:
2845       case options::OPT_dynamic:
2846       case options::OPT_static:
2847       case options::OPT_fPIC:
2848       case options::OPT_fno_PIC:
2849       case options::OPT_fpic:
2850       case options::OPT_fno_pic:
2851       case options::OPT_fPIE:
2852       case options::OPT_fno_PIE:
2853       case options::OPT_fpie:
2854       case options::OPT_fno_pie:
2855         break;
2856       }
2857     }
2858     return DAL;
2859   }
2860   return nullptr;
2861 }
2862 
2863 void Generic_ELF::anchor() {}
2864 
2865 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2866                                         ArgStringList &CC1Args,
2867                                         Action::OffloadKind) const {
2868   if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
2869                           options::OPT_fno_use_init_array, true))
2870     CC1Args.push_back("-fno-use-init-array");
2871 }
2872