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