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