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 bool isMSP430(llvm::Triple::ArchType Arch) {
882  return Arch == llvm::Triple::msp430;
883 }
884 
885 static Multilib makeMultilib(StringRef commonSuffix) {
886  return Multilib(commonSuffix, commonSuffix, commonSuffix);
887 }
888 
889 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags,
890  FilterNonExistent &NonExistent,
891  DetectedMultilibs &Result) {
892  // Check for Code Sourcery toolchain multilibs
893  MultilibSet CSMipsMultilibs;
894  {
895  auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
896 
897  auto MArchMicroMips =
898  makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
899 
900  auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
901 
902  auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
903 
904  auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
905 
906  auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
907 
908  auto DefaultFloat =
909  makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
910 
911  auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
912 
913  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
914 
915  // Note that this one's osSuffix is ""
916  auto MAbi64 = makeMultilib("")
917  .gccSuffix("/64")
918  .includeSuffix("/64")
919  .flag("+mabi=n64")
920  .flag("-mabi=n32")
921  .flag("-m32");
922 
923  CSMipsMultilibs =
924  MultilibSet()
925  .Either(MArchMips16, MArchMicroMips, MArchDefault)
926  .Maybe(UCLibc)
927  .Either(SoftFloat, Nan2008, DefaultFloat)
928  .FilterOut("/micromips/nan2008")
929  .FilterOut("/mips16/nan2008")
930  .Either(BigEndian, LittleEndian)
931  .Maybe(MAbi64)
932  .FilterOut("/mips16.*/64")
933  .FilterOut("/micromips.*/64")
934  .FilterOut(NonExistent)
935  .setIncludeDirsCallback([](const Multilib &M) {
936  std::vector<std::string> Dirs({"/include"});
937  if (StringRef(M.includeSuffix()).startswith("/uclibc"))
938  Dirs.push_back(
939  "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
940  else
941  Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
942  return Dirs;
943  });
944  }
945 
946  MultilibSet DebianMipsMultilibs;
947  {
948  Multilib MAbiN32 =
949  Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
950 
951  Multilib M64 = Multilib()
952  .gccSuffix("/64")
953  .includeSuffix("/64")
954  .flag("+m64")
955  .flag("-m32")
956  .flag("-mabi=n32");
957 
958  Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
959 
960  DebianMipsMultilibs =
961  MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
962  }
963 
964  // Sort candidates. Toolchain that best meets the directories tree goes first.
965  // Then select the first toolchains matches command line flags.
966  MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
967  if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
968  std::iter_swap(Candidates, Candidates + 1);
969  for (const MultilibSet *Candidate : Candidates) {
970  if (Candidate->select(Flags, Result.SelectedMultilib)) {
971  if (Candidate == &DebianMipsMultilibs)
972  Result.BiarchSibling = Multilib();
973  Result.Multilibs = *Candidate;
974  return true;
975  }
976  }
977  return false;
978 }
979 
980 static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path,
981  const Multilib::flags_list &Flags,
982  FilterNonExistent &NonExistent,
983  DetectedMultilibs &Result) {
984 
985  MultilibSet AndroidMipsMultilibs =
986  MultilibSet()
987  .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
988  .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
989  .FilterOut(NonExistent);
990 
991  MultilibSet AndroidMipselMultilibs =
992  MultilibSet()
993  .Either(Multilib().flag("+march=mips32"),
994  Multilib("/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
995  Multilib("/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
996  .FilterOut(NonExistent);
997 
998  MultilibSet AndroidMips64elMultilibs =
999  MultilibSet()
1000  .Either(
1001  Multilib().flag("+march=mips64r6"),
1002  Multilib("/32/mips-r1", "", "/mips-r1").flag("+march=mips32"),
1003  Multilib("/32/mips-r2", "", "/mips-r2").flag("+march=mips32r2"),
1004  Multilib("/32/mips-r6", "", "/mips-r6").flag("+march=mips32r6"))
1005  .FilterOut(NonExistent);
1006 
1007  MultilibSet *MS = &AndroidMipsMultilibs;
1008  if (VFS.exists(Path + "/mips-r6"))
1009  MS = &AndroidMipselMultilibs;
1010  else if (VFS.exists(Path + "/32"))
1011  MS = &AndroidMips64elMultilibs;
1012  if (MS->select(Flags, Result.SelectedMultilib)) {
1013  Result.Multilibs = *MS;
1014  return true;
1015  }
1016  return false;
1017 }
1018 
1020  FilterNonExistent &NonExistent,
1021  DetectedMultilibs &Result) {
1022  // Musl toolchain multilibs
1023  MultilibSet MuslMipsMultilibs;
1024  {
1025  auto MArchMipsR2 = makeMultilib("")
1026  .osSuffix("/mips-r2-hard-musl")
1027  .flag("+EB")
1028  .flag("-EL")
1029  .flag("+march=mips32r2");
1030 
1031  auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1032  .flag("-EB")
1033  .flag("+EL")
1034  .flag("+march=mips32r2");
1035 
1036  MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1037 
1038  // Specify the callback that computes the include directories.
1039  MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1040  return std::vector<std::string>(
1041  {"/../sysroot" + M.osSuffix() + "/usr/include"});
1042  });
1043  }
1044  if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
1045  Result.Multilibs = MuslMipsMultilibs;
1046  return true;
1047  }
1048  return false;
1049 }
1050 
1052  FilterNonExistent &NonExistent,
1053  DetectedMultilibs &Result) {
1054  // CodeScape MTI toolchain v1.2 and early.
1055  MultilibSet MtiMipsMultilibsV1;
1056  {
1057  auto MArchMips32 = makeMultilib("/mips32")
1058  .flag("+m32")
1059  .flag("-m64")
1060  .flag("-mmicromips")
1061  .flag("+march=mips32");
1062 
1063  auto MArchMicroMips = makeMultilib("/micromips")
1064  .flag("+m32")
1065  .flag("-m64")
1066  .flag("+mmicromips");
1067 
1068  auto MArchMips64r2 = makeMultilib("/mips64r2")
1069  .flag("-m32")
1070  .flag("+m64")
1071  .flag("+march=mips64r2");
1072 
1073  auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1074  "-march=mips64r2");
1075 
1076  auto MArchDefault = makeMultilib("")
1077  .flag("+m32")
1078  .flag("-m64")
1079  .flag("-mmicromips")
1080  .flag("+march=mips32r2");
1081 
1082  auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1083 
1084  auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1085 
1086  auto MAbi64 =
1087  makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1088 
1089  auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1090 
1091  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1092 
1093  auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1094 
1095  auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1096 
1097  MtiMipsMultilibsV1 =
1098  MultilibSet()
1099  .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1100  MArchDefault)
1101  .Maybe(UCLibc)
1102  .Maybe(Mips16)
1103  .FilterOut("/mips64/mips16")
1104  .FilterOut("/mips64r2/mips16")
1105  .FilterOut("/micromips/mips16")
1106  .Maybe(MAbi64)
1107  .FilterOut("/micromips/64")
1108  .FilterOut("/mips32/64")
1109  .FilterOut("^/64")
1110  .FilterOut("/mips16/64")
1111  .Either(BigEndian, LittleEndian)
1112  .Maybe(SoftFloat)
1113  .Maybe(Nan2008)
1114  .FilterOut(".*sof/nan2008")
1115  .FilterOut(NonExistent)
1116  .setIncludeDirsCallback([](const Multilib &M) {
1117  std::vector<std::string> Dirs({"/include"});
1118  if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1119  Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1120  else
1121  Dirs.push_back("/../../../../sysroot/usr/include");
1122  return Dirs;
1123  });
1124  }
1125 
1126  // CodeScape IMG toolchain starting from v1.3.
1127  MultilibSet MtiMipsMultilibsV2;
1128  {
1129  auto BeHard = makeMultilib("/mips-r2-hard")
1130  .flag("+EB")
1131  .flag("-msoft-float")
1132  .flag("-mnan=2008")
1133  .flag("-muclibc");
1134  auto BeSoft = makeMultilib("/mips-r2-soft")
1135  .flag("+EB")
1136  .flag("+msoft-float")
1137  .flag("-mnan=2008");
1138  auto ElHard = makeMultilib("/mipsel-r2-hard")
1139  .flag("+EL")
1140  .flag("-msoft-float")
1141  .flag("-mnan=2008")
1142  .flag("-muclibc");
1143  auto ElSoft = makeMultilib("/mipsel-r2-soft")
1144  .flag("+EL")
1145  .flag("+msoft-float")
1146  .flag("-mnan=2008")
1147  .flag("-mmicromips");
1148  auto BeHardNan = makeMultilib("/mips-r2-hard-nan2008")
1149  .flag("+EB")
1150  .flag("-msoft-float")
1151  .flag("+mnan=2008")
1152  .flag("-muclibc");
1153  auto ElHardNan = makeMultilib("/mipsel-r2-hard-nan2008")
1154  .flag("+EL")
1155  .flag("-msoft-float")
1156  .flag("+mnan=2008")
1157  .flag("-muclibc")
1158  .flag("-mmicromips");
1159  auto BeHardNanUclibc = makeMultilib("/mips-r2-hard-nan2008-uclibc")
1160  .flag("+EB")
1161  .flag("-msoft-float")
1162  .flag("+mnan=2008")
1163  .flag("+muclibc");
1164  auto ElHardNanUclibc = makeMultilib("/mipsel-r2-hard-nan2008-uclibc")
1165  .flag("+EL")
1166  .flag("-msoft-float")
1167  .flag("+mnan=2008")
1168  .flag("+muclibc");
1169  auto BeHardUclibc = makeMultilib("/mips-r2-hard-uclibc")
1170  .flag("+EB")
1171  .flag("-msoft-float")
1172  .flag("-mnan=2008")
1173  .flag("+muclibc");
1174  auto ElHardUclibc = makeMultilib("/mipsel-r2-hard-uclibc")
1175  .flag("+EL")
1176  .flag("-msoft-float")
1177  .flag("-mnan=2008")
1178  .flag("+muclibc");
1179  auto ElMicroHardNan = makeMultilib("/micromipsel-r2-hard-nan2008")
1180  .flag("+EL")
1181  .flag("-msoft-float")
1182  .flag("+mnan=2008")
1183  .flag("+mmicromips");
1184  auto ElMicroSoft = makeMultilib("/micromipsel-r2-soft")
1185  .flag("+EL")
1186  .flag("+msoft-float")
1187  .flag("-mnan=2008")
1188  .flag("+mmicromips");
1189 
1190  auto O32 =
1191  makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1192  auto N32 =
1193  makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1194  auto N64 =
1195  makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1196 
1197  MtiMipsMultilibsV2 =
1198  MultilibSet()
1199  .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1200  BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1201  ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1202  .Either(O32, N32, N64)
1203  .FilterOut(NonExistent)
1204  .setIncludeDirsCallback([](const Multilib &M) {
1205  return std::vector<std::string>({"/../../../../sysroot" +
1206  M.includeSuffix() +
1207  "/../usr/include"});
1208  })
1209  .setFilePathsCallback([](const Multilib &M) {
1210  return std::vector<std::string>(
1211  {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1212  });
1213  }
1214  for (auto Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1215  if (Candidate->select(Flags, Result.SelectedMultilib)) {
1216  Result.Multilibs = *Candidate;
1217  return true;
1218  }
1219  }
1220  return false;
1221 }
1222 
1224  FilterNonExistent &NonExistent,
1225  DetectedMultilibs &Result) {
1226  // CodeScape IMG toolchain v1.2 and early.
1227  MultilibSet ImgMultilibsV1;
1228  {
1229  auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1230 
1231  auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1232 
1233  auto MAbi64 =
1234  makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1235 
1236  ImgMultilibsV1 =
1237  MultilibSet()
1238  .Maybe(Mips64r6)
1239  .Maybe(MAbi64)
1240  .Maybe(LittleEndian)
1241  .FilterOut(NonExistent)
1242  .setIncludeDirsCallback([](const Multilib &M) {
1243  return std::vector<std::string>(
1244  {"/include", "/../../../../sysroot/usr/include"});
1245  });
1246  }
1247 
1248  // CodeScape IMG toolchain starting from v1.3.
1249  MultilibSet ImgMultilibsV2;
1250  {
1251  auto BeHard = makeMultilib("/mips-r6-hard")
1252  .flag("+EB")
1253  .flag("-msoft-float")
1254  .flag("-mmicromips");
1255  auto BeSoft = makeMultilib("/mips-r6-soft")
1256  .flag("+EB")
1257  .flag("+msoft-float")
1258  .flag("-mmicromips");
1259  auto ElHard = makeMultilib("/mipsel-r6-hard")
1260  .flag("+EL")
1261  .flag("-msoft-float")
1262  .flag("-mmicromips");
1263  auto ElSoft = makeMultilib("/mipsel-r6-soft")
1264  .flag("+EL")
1265  .flag("+msoft-float")
1266  .flag("-mmicromips");
1267  auto BeMicroHard = makeMultilib("/micromips-r6-hard")
1268  .flag("+EB")
1269  .flag("-msoft-float")
1270  .flag("+mmicromips");
1271  auto BeMicroSoft = makeMultilib("/micromips-r6-soft")
1272  .flag("+EB")
1273  .flag("+msoft-float")
1274  .flag("+mmicromips");
1275  auto ElMicroHard = makeMultilib("/micromipsel-r6-hard")
1276  .flag("+EL")
1277  .flag("-msoft-float")
1278  .flag("+mmicromips");
1279  auto ElMicroSoft = makeMultilib("/micromipsel-r6-soft")
1280  .flag("+EL")
1281  .flag("+msoft-float")
1282  .flag("+mmicromips");
1283 
1284  auto O32 =
1285  makeMultilib("/lib").osSuffix("").flag("-mabi=n32").flag("-mabi=n64");
1286  auto N32 =
1287  makeMultilib("/lib32").osSuffix("").flag("+mabi=n32").flag("-mabi=n64");
1288  auto N64 =
1289  makeMultilib("/lib64").osSuffix("").flag("-mabi=n32").flag("+mabi=n64");
1290 
1291  ImgMultilibsV2 =
1292  MultilibSet()
1293  .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1294  ElMicroHard, ElMicroSoft})
1295  .Either(O32, N32, N64)
1296  .FilterOut(NonExistent)
1297  .setIncludeDirsCallback([](const Multilib &M) {
1298  return std::vector<std::string>({"/../../../../sysroot" +
1299  M.includeSuffix() +
1300  "/../usr/include"});
1301  })
1302  .setFilePathsCallback([](const Multilib &M) {
1303  return std::vector<std::string>(
1304  {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1305  });
1306  }
1307  for (auto Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1308  if (Candidate->select(Flags, Result.SelectedMultilib)) {
1309  Result.Multilibs = *Candidate;
1310  return true;
1311  }
1312  }
1313  return false;
1314 }
1315 
1317  const llvm::Triple &TargetTriple,
1318  StringRef Path, const ArgList &Args,
1319  DetectedMultilibs &Result) {
1320  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1321 
1322  StringRef CPUName;
1323  StringRef ABIName;
1324  tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1325 
1326  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1327 
1328  Multilib::flags_list Flags;
1329  addMultilibFlag(TargetTriple.isMIPS32(), "m32", Flags);
1330  addMultilibFlag(TargetTriple.isMIPS64(), "m64", Flags);
1331  addMultilibFlag(isMips16(Args), "mips16", Flags);
1332  addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
1333  addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1334  CPUName == "mips32r5" || CPUName == "p5600",
1335  "march=mips32r2", Flags);
1336  addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
1337  addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
1338  addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1339  CPUName == "mips64r5" || CPUName == "octeon",
1340  "march=mips64r2", Flags);
1341  addMultilibFlag(CPUName == "mips64r6", "march=mips64r6", Flags);
1342  addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
1343  addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
1344  addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
1345  Flags);
1346  addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
1347  addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
1348  addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
1349  addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
1350  addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
1351  addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
1352 
1353  if (TargetTriple.isAndroid())
1354  return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent,
1355  Result);
1356 
1357  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1358  TargetTriple.getOS() == llvm::Triple::Linux &&
1359  TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1360  return findMipsMuslMultilibs(Flags, NonExistent, Result);
1361 
1362  if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1363  TargetTriple.getOS() == llvm::Triple::Linux &&
1364  TargetTriple.isGNUEnvironment())
1365  return findMipsMtiMultilibs(Flags, NonExistent, Result);
1366 
1367  if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1368  TargetTriple.getOS() == llvm::Triple::Linux &&
1369  TargetTriple.isGNUEnvironment())
1370  return findMipsImgMultilibs(Flags, NonExistent, Result);
1371 
1372  if (findMipsCsMultilibs(Flags, NonExistent, Result))
1373  return true;
1374 
1375  // Fallback to the regular toolchain-tree structure.
1376  Multilib Default;
1377  Result.Multilibs.push_back(Default);
1378  Result.Multilibs.FilterOut(NonExistent);
1379 
1380  if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
1381  Result.BiarchSibling = Multilib();
1382  return true;
1383  }
1384 
1385  return false;
1386 }
1387 
1388 static void findAndroidArmMultilibs(const Driver &D,
1389  const llvm::Triple &TargetTriple,
1390  StringRef Path, const ArgList &Args,
1391  DetectedMultilibs &Result) {
1392  // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1393  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1394  Multilib ArmV7Multilib = makeMultilib("/armv7-a")
1395  .flag("+march=armv7-a")
1396  .flag("-mthumb");
1397  Multilib ThumbMultilib = makeMultilib("/thumb")
1398  .flag("-march=armv7-a")
1399  .flag("+mthumb");
1400  Multilib ArmV7ThumbMultilib = makeMultilib("/armv7-a/thumb")
1401  .flag("+march=armv7-a")
1402  .flag("+mthumb");
1403  Multilib DefaultMultilib = makeMultilib("")
1404  .flag("-march=armv7-a")
1405  .flag("-mthumb");
1406  MultilibSet AndroidArmMultilibs =
1407  MultilibSet()
1408  .Either(ThumbMultilib, ArmV7Multilib,
1409  ArmV7ThumbMultilib, DefaultMultilib)
1410  .FilterOut(NonExistent);
1411 
1412  Multilib::flags_list Flags;
1413  llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1414  bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1415  bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1416  bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1417  bool IsThumbMode = IsThumbArch ||
1418  Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1419  (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1420  bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1421  (llvm::ARM::parseArchVersion(Arch) == 7 ||
1422  (IsArmArch && Arch == "" && IsV7SubArch));
1423  addMultilibFlag(IsArmV7Mode, "march=armv7-a", Flags);
1424  addMultilibFlag(IsThumbMode, "mthumb", Flags);
1425 
1426  if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilib))
1427  Result.Multilibs = AndroidArmMultilibs;
1428 }
1429 
1430 static bool findMSP430Multilibs(const Driver &D,
1431  const llvm::Triple &TargetTriple,
1432  StringRef Path, const ArgList &Args,
1433  DetectedMultilibs &Result) {
1434  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1435  Multilib MSP430Multilib = makeMultilib("/430");
1436  // FIXME: when clang starts to support msp430x ISA additional logic
1437  // to select between multilib must be implemented
1438  // Multilib MSP430xMultilib = makeMultilib("/large");
1439 
1440  Result.Multilibs.push_back(MSP430Multilib);
1441  Result.Multilibs.FilterOut(NonExistent);
1442 
1443  Multilib::flags_list Flags;
1444  if (Result.Multilibs.select(Flags, Result.SelectedMultilib))
1445  return true;
1446 
1447  return false;
1448 }
1449 
1450 static void findRISCVMultilibs(const Driver &D,
1451  const llvm::Triple &TargetTriple, StringRef Path,
1452  const ArgList &Args, DetectedMultilibs &Result) {
1453 
1454  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1455  Multilib Ilp32 = makeMultilib("lib32/ilp32").flag("+m32").flag("+mabi=ilp32");
1456  Multilib Ilp32f =
1457  makeMultilib("lib32/ilp32f").flag("+m32").flag("+mabi=ilp32f");
1458  Multilib Ilp32d =
1459  makeMultilib("lib32/ilp32d").flag("+m32").flag("+mabi=ilp32d");
1460  Multilib Lp64 = makeMultilib("lib64/lp64").flag("+m64").flag("+mabi=lp64");
1461  Multilib Lp64f = makeMultilib("lib64/lp64f").flag("+m64").flag("+mabi=lp64f");
1462  Multilib Lp64d = makeMultilib("lib64/lp64d").flag("+m64").flag("+mabi=lp64d");
1463  MultilibSet RISCVMultilibs =
1464  MultilibSet()
1465  .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1466  .FilterOut(NonExistent);
1467 
1468  Multilib::flags_list Flags;
1469  bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1470  StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1471 
1472  addMultilibFlag(!IsRV64, "m32", Flags);
1473  addMultilibFlag(IsRV64, "m64", Flags);
1474  addMultilibFlag(ABIName == "ilp32", "mabi=ilp32", Flags);
1475  addMultilibFlag(ABIName == "ilp32f", "mabi=ilp32f", Flags);
1476  addMultilibFlag(ABIName == "ilp32d", "mabi=ilp32d", Flags);
1477  addMultilibFlag(ABIName == "lp64", "mabi=lp64", Flags);
1478  addMultilibFlag(ABIName == "lp64f", "mabi=lp64f", Flags);
1479  addMultilibFlag(ABIName == "lp64d", "mabi=lp64d", Flags);
1480 
1481  if (RISCVMultilibs.select(Flags, Result.SelectedMultilib))
1482  Result.Multilibs = RISCVMultilibs;
1483 }
1484 
1485 static bool findBiarchMultilibs(const Driver &D,
1486  const llvm::Triple &TargetTriple,
1487  StringRef Path, const ArgList &Args,
1488  bool NeedsBiarchSuffix,
1489  DetectedMultilibs &Result) {
1490  Multilib Default;
1491 
1492  // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1493  // in what would normally be GCCInstallPath and put the 64-bit
1494  // libs in a subdirectory named 64. The simple logic we follow is that
1495  // *if* there is a subdirectory of the right name with crtbegin.o in it,
1496  // we use that. If not, and if not a biarch triple alias, we look for
1497  // crtbegin.o without the subdirectory.
1498 
1499  StringRef Suff64 = "/64";
1500  // Solaris uses platform-specific suffixes instead of /64.
1501  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1502  switch (TargetTriple.getArch()) {
1503  case llvm::Triple::x86:
1504  case llvm::Triple::x86_64:
1505  Suff64 = "/amd64";
1506  break;
1507  case llvm::Triple::sparc:
1508  case llvm::Triple::sparcv9:
1509  Suff64 = "/sparcv9";
1510  break;
1511  default:
1512  break;
1513  }
1514  }
1515 
1516  Multilib Alt64 = Multilib()
1517  .gccSuffix(Suff64)
1518  .includeSuffix(Suff64)
1519  .flag("-m32")
1520  .flag("+m64")
1521  .flag("-mx32");
1522  Multilib Alt32 = Multilib()
1523  .gccSuffix("/32")
1524  .includeSuffix("/32")
1525  .flag("+m32")
1526  .flag("-m64")
1527  .flag("-mx32");
1528  Multilib Altx32 = Multilib()
1529  .gccSuffix("/x32")
1530  .includeSuffix("/x32")
1531  .flag("-m32")
1532  .flag("-m64")
1533  .flag("+mx32");
1534 
1535  // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
1536  FilterNonExistent NonExistent(
1537  Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
1538 
1539  // Determine default multilib from: 32, 64, x32
1540  // Also handle cases such as 64 on 32, 32 on 64, etc.
1541  enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
1542  const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
1543  if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
1544  Want = WANT64;
1545  else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
1546  Want = WANT64;
1547  else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
1548  Want = WANT32;
1549  else {
1550  if (TargetTriple.isArch32Bit())
1551  Want = NeedsBiarchSuffix ? WANT64 : WANT32;
1552  else if (IsX32)
1553  Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
1554  else
1555  Want = NeedsBiarchSuffix ? WANT32 : WANT64;
1556  }
1557 
1558  if (Want == WANT32)
1559  Default.flag("+m32").flag("-m64").flag("-mx32");
1560  else if (Want == WANT64)
1561  Default.flag("-m32").flag("+m64").flag("-mx32");
1562  else if (Want == WANTX32)
1563  Default.flag("-m32").flag("-m64").flag("+mx32");
1564  else
1565  return false;
1566 
1567  Result.Multilibs.push_back(Default);
1568  Result.Multilibs.push_back(Alt64);
1569  Result.Multilibs.push_back(Alt32);
1570  Result.Multilibs.push_back(Altx32);
1571 
1572  Result.Multilibs.FilterOut(NonExistent);
1573 
1574  Multilib::flags_list Flags;
1575  addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
1576  addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
1577  addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
1578 
1579  if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
1580  return false;
1581 
1582  if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
1583  Result.SelectedMultilib == Altx32)
1584  Result.BiarchSibling = Default;
1585 
1586  return true;
1587 }
1588 
1589 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1590 /// all subcommands; this relies on gcc translating the majority of
1591 /// command line options.
1592 
1593 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
1594 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1595  int RHSPatch,
1596  StringRef RHSPatchSuffix) const {
1597  if (Major != RHSMajor)
1598  return Major < RHSMajor;
1599  if (Minor != RHSMinor)
1600  return Minor < RHSMinor;
1601  if (Patch != RHSPatch) {
1602  // Note that versions without a specified patch sort higher than those with
1603  // a patch.
1604  if (RHSPatch == -1)
1605  return true;
1606  if (Patch == -1)
1607  return false;
1608 
1609  // Otherwise just sort on the patch itself.
1610  return Patch < RHSPatch;
1611  }
1612  if (PatchSuffix != RHSPatchSuffix) {
1613  // Sort empty suffixes higher.
1614  if (RHSPatchSuffix.empty())
1615  return true;
1616  if (PatchSuffix.empty())
1617  return false;
1618 
1619  // Provide a lexicographic sort to make this a total ordering.
1620  return PatchSuffix < RHSPatchSuffix;
1621  }
1622 
1623  // The versions are equal.
1624  return false;
1625 }
1626 
1627 /// Parse a GCCVersion object out of a string of text.
1628 ///
1629 /// This is the primary means of forming GCCVersion objects.
1630 /*static*/
1632  const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1633  std::pair<StringRef, StringRef> First = VersionText.split('.');
1634  std::pair<StringRef, StringRef> Second = First.second.split('.');
1635 
1636  GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1637  if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1638  return BadVersion;
1639  GoodVersion.MajorStr = First.first.str();
1640  if (First.second.empty())
1641  return GoodVersion;
1642  StringRef MinorStr = Second.first;
1643  if (Second.second.empty()) {
1644  if (size_t EndNumber = MinorStr.find_first_not_of("0123456789")) {
1645  GoodVersion.PatchSuffix = MinorStr.substr(EndNumber);
1646  MinorStr = MinorStr.slice(0, EndNumber);
1647  }
1648  }
1649  if (MinorStr.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1650  return BadVersion;
1651  GoodVersion.MinorStr = MinorStr.str();
1652 
1653  // First look for a number prefix and parse that if present. Otherwise just
1654  // stash the entire patch string in the suffix, and leave the number
1655  // unspecified. This covers versions strings such as:
1656  // 5 (handled above)
1657  // 4.4
1658  // 4.4-patched
1659  // 4.4.0
1660  // 4.4.x
1661  // 4.4.2-rc4
1662  // 4.4.x-patched
1663  // And retains any patch number it finds.
1664  StringRef PatchText = Second.second;
1665  if (!PatchText.empty()) {
1666  if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1667  // Try to parse the number and any suffix.
1668  if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1669  GoodVersion.Patch < 0)
1670  return BadVersion;
1671  GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1672  }
1673  }
1674 
1675  return GoodVersion;
1676 }
1677 
1678 static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
1679  llvm::StringRef SysRoot) {
1680  const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
1681  if (A)
1682  return A->getValue();
1683 
1684  // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
1685  // GCC_INSTALL_PREFIX specifies the gcc installation for the default
1686  // sysroot and is likely not valid with a different sysroot.
1687  if (!SysRoot.empty())
1688  return "";
1689 
1690  return GCC_INSTALL_PREFIX;
1691 }
1692 
1693 /// Initialize a GCCInstallationDetector from the driver.
1694 ///
1695 /// This performs all of the autodetection and sets up the various paths.
1696 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1697 ///
1698 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1699 /// should instead pull the target out of the driver. This is currently
1700 /// necessary because the driver doesn't store the final version of the target
1701 /// triple.
1703  const llvm::Triple &TargetTriple, const ArgList &Args,
1704  ArrayRef<std::string> ExtraTripleAliases) {
1705  llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1706  ? TargetTriple.get64BitArchVariant()
1707  : TargetTriple.get32BitArchVariant();
1708  // The library directories which may contain GCC installations.
1709  SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1710  // The compatible GCC triples for this particular architecture.
1711  SmallVector<StringRef, 16> CandidateTripleAliases;
1712  SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1713  CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1714  CandidateTripleAliases, CandidateBiarchLibDirs,
1715  CandidateBiarchTripleAliases);
1716 
1717  // Compute the set of prefixes for our search.
1718  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1719  D.PrefixDirs.end());
1720 
1721  StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
1722  if (GCCToolchainDir != "") {
1723  if (GCCToolchainDir.back() == '/')
1724  GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1725 
1726  Prefixes.push_back(GCCToolchainDir);
1727  } else {
1728  // If we have a SysRoot, try that first.
1729  if (!D.SysRoot.empty()) {
1730  Prefixes.push_back(D.SysRoot);
1731  AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1732  }
1733 
1734  // Then look for gcc installed alongside clang.
1735  Prefixes.push_back(D.InstalledDir + "/..");
1736 
1737  // Next, look for prefix(es) that correspond to distribution-supplied gcc
1738  // installations.
1739  if (D.SysRoot.empty()) {
1740  // Typically /usr.
1741  AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
1742  }
1743  }
1744 
1745  // Try to respect gcc-config on Gentoo. However, do that only
1746  // if --gcc-toolchain is not provided or equal to the Gentoo install
1747  // in /usr. This avoids accidentally enforcing the system GCC version
1748  // when using a custom toolchain.
1749  if (GCCToolchainDir == "" || GCCToolchainDir == D.SysRoot + "/usr") {
1750  SmallVector<StringRef, 16> GentooTestTriples;
1751  // Try to match an exact triple as target triple first.
1752  // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
1753  // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
1754  // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
1755  // triple x86_64-gentoo-linux-gnu is present.
1756  GentooTestTriples.push_back(TargetTriple.str());
1757  // Check rest of triples.
1758  GentooTestTriples.append(ExtraTripleAliases.begin(),
1759  ExtraTripleAliases.end());
1760  GentooTestTriples.append(CandidateTripleAliases.begin(),
1761  CandidateTripleAliases.end());
1762  if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
1763  CandidateBiarchTripleAliases))
1764  return;
1765  }
1766 
1767  // Loop over the various components which exist and select the best GCC
1768  // installation available. GCC installs are ranked by version number.
1769  Version = GCCVersion::Parse("0.0.0");
1770  for (const std::string &Prefix : Prefixes) {
1771  if (!D.getVFS().exists(Prefix))
1772  continue;
1773  for (StringRef Suffix : CandidateLibDirs) {
1774  const std::string LibDir = Prefix + Suffix.str();
1775  if (!D.getVFS().exists(LibDir))
1776  continue;
1777  // Try to match the exact target triple first.
1778  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, TargetTriple.str());
1779  // Try rest of possible triples.
1780  for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1781  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1782  for (StringRef Candidate : CandidateTripleAliases)
1783  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1784  }
1785  for (StringRef Suffix : CandidateBiarchLibDirs) {
1786  const std::string LibDir = Prefix + Suffix.str();
1787  if (!D.getVFS().exists(LibDir))
1788  continue;
1789  for (StringRef Candidate : CandidateBiarchTripleAliases)
1790  ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1791  /*NeedsBiarchSuffix=*/ true);
1792  }
1793  }
1794 }
1795 
1796 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1797  for (const auto &InstallPath : CandidateGCCInstallPaths)
1798  OS << "Found candidate GCC installation: " << InstallPath << "\n";
1799 
1800  if (!GCCInstallPath.empty())
1801  OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1802 
1803  for (const auto &Multilib : Multilibs)
1804  OS << "Candidate multilib: " << Multilib << "\n";
1805 
1806  if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1807  OS << "Selected multilib: " << SelectedMultilib << "\n";
1808 }
1809 
1811  if (BiarchSibling.hasValue()) {
1812  M = BiarchSibling.getValue();
1813  return true;
1814  }
1815  return false;
1816 }
1817 
1818 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
1819  const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
1820  StringRef SysRoot) {
1821  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1822  // Solaris is a special case.
1823  // The GCC installation is under
1824  // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
1825  // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
1826  // /usr/gcc/<version> as a prefix.
1827 
1828  std::string PrefixDir = SysRoot.str() + "/usr/gcc";
1829  std::error_code EC;
1830  for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
1831  LE;
1832  !EC && LI != LE; LI = LI.increment(EC)) {
1833  StringRef VersionText = llvm::sys::path::filename(LI->path());
1834  GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
1835 
1836  // Filter out obviously bad entries.
1837  if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
1838  continue;
1839 
1840  std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
1841  std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
1842  if (!D.getVFS().exists(CandidateLibPath))
1843  continue;
1844 
1845  Prefixes.push_back(CandidatePrefix);
1846  }
1847  return;
1848  }
1849 
1850  // Non-Solaris is much simpler - most systems just go with "/usr".
1851  if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux) {
1852  // Yet, still look for RHEL devtoolsets.
1853  Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
1854  Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
1855  Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
1856  Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
1857  Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
1858  }
1859  Prefixes.push_back(SysRoot.str() + "/usr");
1860 }
1861 
1862 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1863  const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1864  SmallVectorImpl<StringRef> &LibDirs,
1865  SmallVectorImpl<StringRef> &TripleAliases,
1866  SmallVectorImpl<StringRef> &BiarchLibDirs,
1867  SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1868  // Declare a bunch of static data sets that we'll select between below. These
1869  // are specifically designed to always refer to string literals to avoid any
1870  // lifetime or initialization issues.
1871  static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1872  static const char *const AArch64Triples[] = {
1873  "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
1874  "aarch64-suse-linux", "aarch64-linux-android"};
1875  static const char *const AArch64beLibDirs[] = {"/lib"};
1876  static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1877  "aarch64_be-linux-gnu"};
1878 
1879  static const char *const ARMLibDirs[] = {"/lib"};
1880  static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1881  "arm-linux-androideabi"};
1882  static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1883  "armv7hl-redhat-linux-gnueabi",
1884  "armv6hl-suse-linux-gnueabi",
1885  "armv7hl-suse-linux-gnueabi"};
1886  static const char *const ARMebLibDirs[] = {"/lib"};
1887  static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1888  "armeb-linux-androideabi"};
1889  static const char *const ARMebHFTriples[] = {
1890  "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1891 
1892  static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1893  static const char *const X86_64Triples[] = {
1894  "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1895  "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1896  "x86_64-redhat-linux", "x86_64-suse-linux",
1897  "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1898  "x86_64-slackware-linux", "x86_64-unknown-linux",
1899  "x86_64-amazon-linux", "x86_64-linux-android"};
1900  static const char *const X32LibDirs[] = {"/libx32"};
1901  static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1902  static const char *const X86Triples[] = {
1903  "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1904  "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1905  "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1906  "i486-slackware-linux", "i686-montavista-linux", "i586-linux-gnu",
1907  "i686-linux-android", "i386-gnu", "i486-gnu",
1908  "i586-gnu", "i686-gnu"};
1909 
1910  static const char *const MIPSLibDirs[] = {"/lib"};
1911  static const char *const MIPSTriples[] = {
1912  "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
1913  "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
1914  static const char *const MIPSELLibDirs[] = {"/lib"};
1915  static const char *const MIPSELTriples[] = {
1916  "mipsel-linux-gnu", "mips-img-linux-gnu", "mipsisa32r6el-linux-gnu",
1917  "mipsel-linux-android"};
1918 
1919  static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1920  static const char *const MIPS64Triples[] = {
1921  "mips64-linux-gnu", "mips-mti-linux-gnu",
1922  "mips-img-linux-gnu", "mips64-linux-gnuabi64",
1923  "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
1924  static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1925  static const char *const MIPS64ELTriples[] = {
1926  "mips64el-linux-gnu", "mips-mti-linux-gnu",
1927  "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
1928  "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64",
1929  "mips64el-linux-android"};
1930 
1931  static const char *const MIPSN32LibDirs[] = {"/lib32"};
1932  static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
1933  "mipsisa64r6-linux-gnuabin32"};
1934  static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
1935  static const char *const MIPSN32ELTriples[] = {
1936  "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
1937 
1938  static const char *const MSP430LibDirs[] = {"/lib"};
1939  static const char *const MSP430Triples[] = {"msp430-elf"};
1940 
1941  static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1942  static const char *const PPCTriples[] = {
1943  "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1944  "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1945  static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1946  static const char *const PPC64Triples[] = {
1947  "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1948  "powerpc64-suse-linux", "ppc64-redhat-linux"};
1949  static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1950  static const char *const PPC64LETriples[] = {
1951  "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1952  "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1953 
1954  static const char *const RISCV32LibDirs[] = {"/lib", "/lib32"};
1955  static const char *const RISCVTriples[] = {"riscv32-unknown-linux-gnu",
1956  "riscv64-unknown-linux-gnu",
1957  "riscv32-unknown-elf"};
1958 
1959  static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1960  static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1961  "sparcv8-linux-gnu"};
1962  static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1963  static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1964  "sparcv9-linux-gnu"};
1965 
1966  static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1967  static const char *const SystemZTriples[] = {
1968  "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1969  "s390x-suse-linux", "s390x-redhat-linux"};
1970 
1971 
1972  using std::begin;
1973  using std::end;
1974 
1975  if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1976  static const char *const SolarisLibDirs[] = {"/lib"};
1977  static const char *const SolarisSparcV8Triples[] = {
1978  "sparc-sun-solaris2.11", "sparc-sun-solaris2.12"};
1979  static const char *const SolarisSparcV9Triples[] = {
1980  "sparcv9-sun-solaris2.11", "sparcv9-sun-solaris2.12"};
1981  static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11",
1982  "i386-pc-solaris2.12"};
1983  static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11",
1984  "x86_64-pc-solaris2.12"};
1985  LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
1986  BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
1987  switch (TargetTriple.getArch()) {
1988  case llvm::Triple::x86:
1989  TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
1990  BiarchTripleAliases.append(begin(SolarisX86_64Triples),
1991  end(SolarisX86_64Triples));
1992  break;
1993  case llvm::Triple::x86_64:
1994  TripleAliases.append(begin(SolarisX86_64Triples),
1995  end(SolarisX86_64Triples));
1996  BiarchTripleAliases.append(begin(SolarisX86Triples),
1997  end(SolarisX86Triples));
1998  break;
1999  case llvm::Triple::sparc:
2000  TripleAliases.append(begin(SolarisSparcV8Triples),
2001  end(SolarisSparcV8Triples));
2002  BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2003  end(SolarisSparcV9Triples));
2004  break;
2005  case llvm::Triple::sparcv9:
2006  TripleAliases.append(begin(SolarisSparcV9Triples),
2007  end(SolarisSparcV9Triples));
2008  BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2009  end(SolarisSparcV8Triples));
2010  break;
2011  default:
2012  break;
2013  }
2014  return;
2015  }
2016 
2017  // Android targets should not use GNU/Linux tools or libraries.
2018  if (TargetTriple.isAndroid()) {
2019  static const char *const AArch64AndroidTriples[] = {
2020  "aarch64-linux-android"};
2021  static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2022  static const char *const MIPSELAndroidTriples[] = {"mipsel-linux-android"};
2023  static const char *const MIPS64ELAndroidTriples[] = {
2024  "mips64el-linux-android"};
2025  static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2026  static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2027 
2028  switch (TargetTriple.getArch()) {
2029  case llvm::Triple::aarch64:
2030  LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2031  TripleAliases.append(begin(AArch64AndroidTriples),
2032  end(AArch64AndroidTriples));
2033  break;
2034  case llvm::Triple::arm:
2035  case llvm::Triple::thumb:
2036  LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2037  TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2038  break;
2039  case llvm::Triple::mipsel:
2040  LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2041  TripleAliases.append(begin(MIPSELAndroidTriples),
2042  end(MIPSELAndroidTriples));
2043  BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2044  BiarchTripleAliases.append(begin(MIPS64ELAndroidTriples),
2045  end(MIPS64ELAndroidTriples));
2046  break;
2047  case llvm::Triple::mips64el:
2048  LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2049  TripleAliases.append(begin(MIPS64ELAndroidTriples),
2050  end(MIPS64ELAndroidTriples));
2051  BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2052  BiarchTripleAliases.append(begin(MIPSELAndroidTriples),
2053  end(MIPSELAndroidTriples));
2054  break;
2055  case llvm::Triple::x86_64:
2056  LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2057  TripleAliases.append(begin(X86_64AndroidTriples),
2058  end(X86_64AndroidTriples));
2059  BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2060  BiarchTripleAliases.append(begin(X86AndroidTriples),
2061  end(X86AndroidTriples));
2062  break;
2063  case llvm::Triple::x86:
2064  LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2065  TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2066  BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2067  BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2068  end(X86_64AndroidTriples));
2069  break;
2070  default:
2071  break;
2072  }
2073 
2074  return;
2075  }
2076 
2077  switch (TargetTriple.getArch()) {
2078  case llvm::Triple::aarch64:
2079  LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2080  TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2081  BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2082  BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2083  break;
2084  case llvm::Triple::aarch64_be:
2085  LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2086  TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2087  BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2088  BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2089  break;
2090  case llvm::Triple::arm:
2091  case llvm::Triple::thumb:
2092  LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2093  if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2094  TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2095  } else {
2096  TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2097  }
2098  break;
2099  case llvm::Triple::armeb:
2100  case llvm::Triple::thumbeb:
2101  LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2102  if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
2103  TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2104  } else {
2105  TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2106  }
2107  break;
2108  case llvm::Triple::x86_64:
2109  LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2110  TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2111  // x32 is always available when x86_64 is available, so adding it as
2112  // secondary arch with x86_64 triples
2113  if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
2114  BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2115  BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2116  } else {
2117  BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2118  BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2119  }
2120  break;
2121  case llvm::Triple::x86:
2122  LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2123  // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2124  // itself, which will be appended below.
2125  if (!TargetTriple.isOSIAMCU()) {
2126  TripleAliases.append(begin(X86Triples), end(X86Triples));
2127  BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2128  BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2129  }
2130  break;
2131  case llvm::Triple::mips:
2132  LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2133  TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2134  BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2135  BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2136  BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2137  BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2138  break;
2139  case llvm::Triple::mipsel:
2140  LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2141  TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2142  TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2143  BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2144  BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2145  BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2146  BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2147  break;
2148  case llvm::Triple::mips64:
2149  LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2150  TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2151  BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2152  BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2153  BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2154  BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2155  break;
2156  case llvm::Triple::mips64el:
2157  LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2158  TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2159  BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2160  BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2161  BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2162  BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2163  BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2164  break;
2165  case llvm::Triple::msp430:
2166  LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2167  TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2168  break;
2169  case llvm::Triple::ppc:
2170  LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2171  TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2172  BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2173  BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2174  break;
2175  case llvm::Triple::ppc64:
2176  LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2177  TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2178  BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2179  BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2180  break;
2181  case llvm::Triple::ppc64le:
2182  LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2183  TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2184  break;
2185  case llvm::Triple::riscv32:
2186  LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2187  BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2188  TripleAliases.append(begin(RISCVTriples), end(RISCVTriples));
2189  BiarchTripleAliases.append(begin(RISCVTriples), end(RISCVTriples));
2190  break;
2191  case llvm::Triple::sparc:
2192  case llvm::Triple::sparcel:
2193  LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2194  TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2195  BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2196  BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2197  break;
2198  case llvm::Triple::sparcv9:
2199  LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2200  TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2201  BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2202  BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2203  break;
2204  case llvm::Triple::systemz:
2205  LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2206  TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2207  break;
2208  default:
2209  // By default, just rely on the standard lib directories and the original
2210  // triple.
2211  break;
2212  }
2213 
2214  // Always append the drivers target triple to the end, in case it doesn't
2215  // match any of our aliases.
2216  TripleAliases.push_back(TargetTriple.str());
2217 
2218  // Also include the multiarch variant if it's different.
2219  if (TargetTriple.str() != BiarchTriple.str())
2220  BiarchTripleAliases.push_back(BiarchTriple.str());
2221 }
2222 
2223 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2224  const llvm::Triple &TargetTriple, const ArgList &Args,
2225  StringRef Path, bool NeedsBiarchSuffix) {
2226  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2227  DetectedMultilibs Detected;
2228 
2229  // Android standalone toolchain could have multilibs for ARM and Thumb.
2230  // Debian mips multilibs behave more like the rest of the biarch ones,
2231  // so handle them there
2232  if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2233  // It should also work without multilibs in a simplified toolchain.
2234  findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2235  } else if (TargetTriple.isMIPS()) {
2236  if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2237  return false;
2238  } else if (isRISCV(TargetArch)) {
2239  findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2240  } else if (isMSP430(TargetArch)) {
2241  findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2242  } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2243  NeedsBiarchSuffix, Detected)) {
2244  return false;
2245  }
2246 
2247  Multilibs = Detected.Multilibs;
2248  SelectedMultilib = Detected.SelectedMultilib;
2249  BiarchSibling = Detected.BiarchSibling;
2250 
2251  return true;
2252 }
2253 
2254 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2255  const llvm::Triple &TargetTriple, const ArgList &Args,
2256  const std::string &LibDir, StringRef CandidateTriple,
2257  bool NeedsBiarchSuffix) {
2258  llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2259  // Locations relative to the system lib directory where GCC's triple-specific
2260  // directories might reside.
2261  struct GCCLibSuffix {
2262  // Path from system lib directory to GCC triple-specific directory.
2263  std::string LibSuffix;
2264  // Path from GCC triple-specific directory back to system lib directory.
2265  // This is one '..' component per component in LibSuffix.
2266  StringRef ReversePath;
2267  // Whether this library suffix is relevant for the triple.
2268  bool Active;
2269  } Suffixes[] = {
2270  // This is the normal place.
2271  {"gcc/" + CandidateTriple.str(), "../..", true},
2272 
2273  // Debian puts cross-compilers in gcc-cross.
2274  {"gcc-cross/" + CandidateTriple.str(), "../..",
2275  TargetTriple.getOS() != llvm::Triple::Solaris},
2276 
2277  // The Freescale PPC SDK has the gcc libraries in
2278  // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2279  // this on Freescale triples, though, since some systems put a *lot* of
2280  // files in that location, not just GCC installation data.
2281  {CandidateTriple.str(), "..",
2282  TargetTriple.getVendor() == llvm::Triple::Freescale ||
2283  TargetTriple.getVendor() == llvm::Triple::OpenEmbedded},
2284 
2285  // Natively multiarch systems sometimes put the GCC triple-specific
2286  // directory within their multiarch lib directory, resulting in the
2287  // triple appearing twice.
2288  {CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), "../../..",
2289  TargetTriple.getOS() != llvm::Triple::Solaris},
2290 
2291  // Deal with cases (on Ubuntu) where the system architecture could be i386
2292  // but the GCC target architecture could be (say) i686.
2293  // FIXME: It may be worthwhile to generalize this and look for a second
2294  // triple.
2295  {"i386-linux-gnu/gcc/" + CandidateTriple.str(), "../../..",
2296  (TargetArch == llvm::Triple::x86 &&
2297  TargetTriple.getOS() != llvm::Triple::Solaris)},
2298  {"i386-gnu/gcc/" + CandidateTriple.str(), "../../..",
2299  (TargetArch == llvm::Triple::x86 &&
2300  TargetTriple.getOS() != llvm::Triple::Solaris)}};
2301 
2302  for (auto &Suffix : Suffixes) {
2303  if (!Suffix.Active)
2304  continue;
2305 
2306  StringRef LibSuffix = Suffix.LibSuffix;
2307  std::error_code EC;
2308  for (llvm::vfs::directory_iterator
2309  LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2310  LE;
2311  !EC && LI != LE; LI = LI.increment(EC)) {
2312  StringRef VersionText = llvm::sys::path::filename(LI->path());
2313  GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2314  if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2315  if (!CandidateGCCInstallPaths.insert(LI->path()).second)
2316  continue; // Saw this path before; no need to look at it again.
2317  if (CandidateVersion.isOlderThan(4, 1, 1))
2318  continue;
2319  if (CandidateVersion <= Version)
2320  continue;
2321 
2322  if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2323  NeedsBiarchSuffix))
2324  continue;
2325 
2326  Version = CandidateVersion;
2327  GCCTriple.setTriple(CandidateTriple);
2328  // FIXME: We hack together the directory name here instead of
2329  // using LI to ensure stable path separators across Windows and
2330  // Linux.
2331  GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2332  GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2333  IsValid = true;
2334  }
2335  }
2336 }
2337 
2338 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2339  const llvm::Triple &TargetTriple, const ArgList &Args,
2340  const SmallVectorImpl<StringRef> &CandidateTriples,
2341  const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2342  for (StringRef CandidateTriple : CandidateTriples) {
2343  if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2344  return true;
2345  }
2346 
2347  for (StringRef CandidateTriple : CandidateBiarchTriples) {
2348  if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2349  return true;
2350  }
2351  return false;
2352 }
2353 
2354 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2355  const llvm::Triple &TargetTriple, const ArgList &Args,
2356  StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2357  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2358  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/config-" +
2359  CandidateTriple.str());
2360  if (File) {
2362  File.get()->getBuffer().split(Lines, "\n");
2363  for (StringRef Line : Lines) {
2364  Line = Line.trim();
2365  // CURRENT=triple-version
2366  if (!Line.consume_front("CURRENT="))
2367  continue;
2368  // Process the config file pointed to by CURRENT.
2369  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
2370  D.getVFS().getBufferForFile(D.SysRoot + "/etc/env.d/gcc/" +
2371  Line.str());
2372  std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
2373  // List of paths to scan for libraries.
2374  SmallVector<StringRef, 4> GentooScanPaths;
2375  // Scan the Config file to find installed GCC libraries path.
2376  // Typical content of the GCC config file:
2377  // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
2378  // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
2379  // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
2380  // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
2381  // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
2382  // We are looking for the paths listed in LDPATH=... .
2383  if (ConfigFile) {
2384  SmallVector<StringRef, 2> ConfigLines;
2385  ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
2386  for (StringRef ConfLine : ConfigLines) {
2387  ConfLine = ConfLine.trim();
2388  if (ConfLine.consume_front("LDPATH=")) {
2389  // Drop '"' from front and back if present.
2390  ConfLine.consume_back("\"");
2391  ConfLine.consume_front("\"");
2392  // Get all paths sperated by ':'
2393  ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
2394  }
2395  }
2396  }
2397  // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
2398  std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
2399  + ActiveVersion.second.str();
2400  GentooScanPaths.push_back(StringRef(basePath));
2401 
2402  // Scan all paths for GCC libraries.
2403  for (const auto &GentooScanPath : GentooScanPaths) {
2404  std::string GentooPath = D.SysRoot + std::string(GentooScanPath);
2405  if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
2406  if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
2407  NeedsBiarchSuffix))
2408  continue;
2409 
2410  Version = GCCVersion::Parse(ActiveVersion.second);
2411  GCCInstallPath = GentooPath;
2412  GCCParentLibPath = GentooPath + std::string("/../../..");
2413  GCCTriple.setTriple(ActiveVersion.first);
2414  IsValid = true;
2415  return true;
2416  }
2417  }
2418  }
2419  }
2420 
2421  return false;
2422 }
2423 
2424 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2425  const ArgList &Args)
2426  : ToolChain(D, Triple, Args), GCCInstallation(D),
2427  CudaInstallation(D, Triple, Args) {
2428  getProgramPaths().push_back(getDriver().getInstalledDir());
2429  if (getDriver().getInstalledDir() != getDriver().Dir)
2430  getProgramPaths().push_back(getDriver().Dir);
2431 }
2432 
2434 
2436  switch (AC) {
2438  if (!Preprocess)
2439  Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
2440  return Preprocess.get();
2442  if (!Compile)
2443  Compile.reset(new tools::gcc::Compiler(*this));
2444  return Compile.get();
2445  default:
2446  return ToolChain::getTool(AC);
2447  }
2448 }
2449 
2451  return new tools::gnutools::Assembler(*this);
2452 }
2453 
2454 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2455 
2456 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2457  // Print the information about how we detected the GCC installation.
2458  GCCInstallation.print(OS);
2459  CudaInstallation.print(OS);
2460 }
2461 
2462 bool Generic_GCC::IsUnwindTablesDefault(const ArgList &Args) const {
2463  return getArch() == llvm::Triple::x86_64;
2464 }
2465 
2467  switch (getArch()) {
2468  case llvm::Triple::x86_64:
2469  return getTriple().isOSWindows();
2470  case llvm::Triple::ppc64:
2471  // Big endian PPC is PIC by default
2472  return !getTriple().isOSBinFormatMachO() && !getTriple().isMacOSX();
2473  case llvm::Triple::mips64:
2474  case llvm::Triple::mips64el:
2475  return true;
2476  default:
2477  return false;
2478  }
2479 }
2480 
2481 bool Generic_GCC::isPIEDefault() const { return false; }
2482 
2484  return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2485 }
2486 
2488  switch (getTriple().getArch()) {
2489  case llvm::Triple::x86:
2490  case llvm::Triple::x86_64:
2491  case llvm::Triple::aarch64:
2492  case llvm::Triple::aarch64_be:
2493  case llvm::Triple::arm:
2494  case llvm::Triple::armeb:
2495  case llvm::Triple::avr:
2496  case llvm::Triple::bpfel:
2497  case llvm::Triple::bpfeb:
2498  case llvm::Triple::thumb:
2499  case llvm::Triple::thumbeb:
2500  case llvm::Triple::ppc:
2501  case llvm::Triple::ppc64:
2502  case llvm::Triple::ppc64le:
2503  case llvm::Triple::riscv32:
2504  case llvm::Triple::riscv64:
2505  case llvm::Triple::systemz:
2506  case llvm::Triple::mips:
2507  case llvm::Triple::mipsel:
2508  case llvm::Triple::mips64:
2509  case llvm::Triple::mips64el:
2510  case llvm::Triple::msp430:
2511  return true;
2512  case llvm::Triple::sparc:
2513  case llvm::Triple::sparcel:
2514  case llvm::Triple::sparcv9:
2515  if (getTriple().isOSSolaris() || getTriple().isOSOpenBSD())
2516  return true;
2517  return false;
2518  default:
2519  return false;
2520  }
2521 }
2522 
2523 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2524  ArgStringList &CC1Args) const {
2525  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2526  DriverArgs.hasArg(options::OPT_nostdincxx))
2527  return;
2528 
2529  switch (GetCXXStdlibType(DriverArgs)) {
2530  case ToolChain::CST_Libcxx:
2531  addLibCxxIncludePaths(DriverArgs, CC1Args);
2532  break;
2533 
2535  addLibStdCxxIncludePaths(DriverArgs, CC1Args);
2536  break;
2537  }
2538 }
2539 
2540 void
2541 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2542  llvm::opt::ArgStringList &CC1Args) const {
2543  // FIXME: The Linux behavior would probaby be a better approach here.
2544  addSystemInclude(DriverArgs, CC1Args,
2545  getDriver().SysRoot + "/usr/include/c++/v1");
2546 }
2547 
2548 void
2549 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
2550  llvm::opt::ArgStringList &CC1Args) const {
2551  // By default, we don't assume we know where libstdc++ might be installed.
2552  // FIXME: If we have a valid GCCInstallation, use it.
2553 }
2554 
2555 /// Helper to add the variant paths of a libstdc++ installation.
2557  Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2558  StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2559  const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2560  if (!getVFS().exists(Base + Suffix))
2561  return false;
2562 
2563  addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2564 
2565  // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2566  // that path exists or we have neither a GCC nor target multiarch triple, use
2567  // this vanilla search path.
2568  if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2569  getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2570  addSystemInclude(DriverArgs, CC1Args,
2571  Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2572  } else {
2573  // Otherwise try to use multiarch naming schemes which have normalized the
2574  // triples and put the triple before the suffix.
2575  //
2576  // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2577  // the target triple, so we support that here.
2578  addSystemInclude(DriverArgs, CC1Args,
2579  Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2580  addSystemInclude(DriverArgs, CC1Args,
2581  Base + "/" + TargetMultiarchTriple + Suffix);
2582  }
2583 
2584  addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2585  return true;
2586 }
2587 
2588 llvm::opt::DerivedArgList *
2589 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
2590  Action::OffloadKind DeviceOffloadKind) const {
2591 
2592  // If this tool chain is used for an OpenMP offloading device we have to make
2593  // sure we always generate a shared library regardless of the commands the
2594  // user passed to the host. This is required because the runtime library
2595  // is required to load the device image dynamically at run time.
2596  if (DeviceOffloadKind == Action::OFK_OpenMP) {
2597  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2598  const OptTable &Opts = getDriver().getOpts();
2599 
2600  // Request the shared library. Given that these options are decided
2601  // implicitly, they do not refer to any base argument.
2602  DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
2603  DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
2604 
2605  // Filter all the arguments we don't care passing to the offloading
2606  // toolchain as they can mess up with the creation of a shared library.
2607  for (auto *A : Args) {
2608  switch ((options::ID)A->getOption().getID()) {
2609  default:
2610  DAL->append(A);
2611  break;
2612  case options::OPT_shared:
2613  case options::OPT_dynamic:
2614  case options::OPT_static:
2615  case options::OPT_fPIC:
2616  case options::OPT_fno_PIC:
2617  case options::OPT_fpic:
2618  case options::OPT_fno_pic:
2619  case options::OPT_fPIE:
2620  case options::OPT_fno_PIE:
2621  case options::OPT_fpie:
2622  case options::OPT_fno_pie:
2623  break;
2624  }
2625  }
2626  return DAL;
2627  }
2628  return nullptr;
2629 }
2630 
2631 void Generic_ELF::anchor() {}
2632 
2633 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2634  ArgStringList &CC1Args,
2635  Action::OffloadKind) const {
2637  bool UseInitArrayDefault =
2638  getTriple().getArch() == llvm::Triple::aarch64 ||
2639  getTriple().getArch() == llvm::Triple::aarch64_be ||
2640  (getTriple().isOSFreeBSD() &&
2641  getTriple().getOSMajorVersion() >= 12) ||
2642  (getTriple().getOS() == llvm::Triple::Linux &&
2643  ((!GCCInstallation.isValid() || !V.isOlderThan(4, 7, 0)) ||
2644  getTriple().isAndroid())) ||
2645  getTriple().getOS() == llvm::Triple::NaCl ||
2646  (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
2647  !getTriple().hasEnvironment()) ||
2648  getTriple().getOS() == llvm::Triple::Solaris ||
2649  getTriple().getArch() == llvm::Triple::riscv32 ||
2650  getTriple().getArch() == llvm::Triple::riscv64;
2651 
2652  if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2653  options::OPT_fno_use_init_array, UseInitArrayDefault))
2654  CC1Args.push_back("-fuse-init-array");
2655 }
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:970
virtual std::string getDynamicLinker(const llvm::opt::ArgList &Args) const
Definition: Linux.cpp:507
Tool * buildLinker() const override
Definition: Gnu.cpp:2454
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:2435
bool getBiarchSibling(Multilib &M) const
Get the biarch sibling multilib (if it exists).
Definition: Gnu.cpp:1810
static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path, const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:980
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:520
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition: Gnu.cpp:1631
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:523
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:439
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:2481
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:1796
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:227
static Multilib makeMultilib(StringRef commonSuffix)
Definition: Gnu.cpp:885
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:431
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:794
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:297
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:2523
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:1019
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:2466
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:1051
Tool * buildAssembler() const override
Definition: Gnu.cpp:2450
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:2462
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:202
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: Gnu.cpp:2456
static bool findMipsImgMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:1223
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:778
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:1678
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
const Driver & getDriver() const
Definition: ToolChain.h:186
virtual void addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:2541
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 bool findMSP430Multilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1430
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:702
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:1594
static bool findBiarchMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, bool NeedsBiarchSuffix, DetectedMultilibs &Result)
Definition: Gnu.cpp:1485
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: Gnu.cpp:2483
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:755
Dataflow Directional Tag Classes.
Generic_GCC(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: Gnu.cpp:2424
static bool isRISCV(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:877
static bool isMSP430(llvm::Triple::ArchType Arch)
Definition: Gnu.cpp:881
const std::string & getCCCGenericGCCName() const
Name to use when invoking gcc/g++.
Definition: Driver.h:289
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:2633
static bool findMipsCsMultilibs(const Multilib::flags_list &Flags, FilterNonExistent &NonExistent, DetectedMultilibs &Result)
Definition: Gnu.cpp:889
bool IsIntegratedAssemblerDefault() const override
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition: Gnu.cpp:2487
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:2589
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:46
const llvm::Triple & getTriple() const
Definition: ToolChain.h:188
virtual void addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: Gnu.cpp:2549
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:293
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:683
static constexpr CPUSuffix Suffixes[]
Definition: Hexagon.cpp:148
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:2556
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:1702
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:1388
static void findRISCVMultilibs(const Driver &D, const llvm::Triple &TargetTriple, StringRef Path, const ArgList &Args, DetectedMultilibs &Result)
Definition: Gnu.cpp:1450
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:761
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:89
bool isValid() const
Check whether we detected a valid GCC install.
Definition: Gnu.h:217