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