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