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