[Instrumentation] Fix a warning
[llvm-project.git] / clang / lib / Driver / ToolChains / Gnu.cpp
blob8397f1121ec2ceac7b3433ac9591466e705065a6
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 //===----------------------------------------------------------------------===//
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
21 #include "clang/Driver/Compilation.h"
22 #include "clang/Driver/Driver.h"
23 #include "clang/Driver/DriverDiagnostic.h"
24 #include "clang/Driver/MultilibBuilder.h"
25 #include "clang/Driver/Options.h"
26 #include "clang/Driver/Tool.h"
27 #include "clang/Driver/ToolChain.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/VirtualFileSystem.h"
34 #include "llvm/TargetParser/RISCVISAInfo.h"
35 #include "llvm/TargetParser/TargetParser.h"
36 #include <system_error>
38 using namespace clang::driver;
39 using namespace clang::driver::toolchains;
40 using namespace clang;
41 using namespace llvm::opt;
43 using tools::addMultilibFlag;
44 using tools::addPathIfExists;
46 static 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);
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.
56 static 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);
69 void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
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;
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();
85 A->render(Args, CmdArgs);
89 RenderExtraToolArgs(JA, CmdArgs);
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()));
98 // Try to force gcc to match the tool chain we want, if we recognize
99 // the arch.
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;
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");
129 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
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.
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)
143 << getToolChain().getTripleString();
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)
148 << getToolChain().getTripleString();
150 if (types::canTypeBeUserSpecified(II.getType())) {
151 CmdArgs.push_back("-x");
152 CmdArgs.push_back(types::getTypeName(II.getType()));
155 if (II.isFilename())
156 CmdArgs.push_back(II.getFilename());
157 else {
158 const Arg &A = II.getInputArg();
160 // Reverse translate some rewritten options.
161 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
162 CmdArgs.push_back("-lstdc++");
163 continue;
166 // Don't render as input, we need gcc to do the translations.
167 A.render(Args, CmdArgs);
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";
180 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
181 C.addCommand(std::make_unique<Command>(JA, *this,
182 ResponseFileSupport::AtFileCurCP(),
183 Exec, CmdArgs, Inputs, Output));
186 void tools::gcc::Preprocessor::RenderExtraToolArgs(
187 const JobAction &JA, ArgStringList &CmdArgs) const {
188 CmdArgs.push_back("-E");
191 void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
192 ArgStringList &CmdArgs) const {
193 const Driver &D = getToolChain().getDriver();
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());
219 void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
220 ArgStringList &CmdArgs) const {
221 // The types are (hopefully) good enough.
224 static 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") || T.isABIN32())
273 return "elf32btsmipn32";
274 return "elf64btsmip";
275 case llvm::Triple::mips64el:
276 if (tools::mips::hasMipsAbiArg(Args, "n32") || T.isABIN32())
277 return "elf32ltsmipn32";
278 return "elf64ltsmip";
279 case llvm::Triple::systemz:
280 return "elf64_s390";
281 case llvm::Triple::x86_64:
282 if (T.isX32())
283 return "elf32_x86_64";
284 return "elf_x86_64";
285 case llvm::Triple::ve:
286 return "elf64ve";
287 case llvm::Triple::csky:
288 return "cskyelf_linux";
289 default:
290 return nullptr;
294 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) {
295 bool HasStaticPIE = Args.hasArg(options::OPT_static_pie);
296 if (HasStaticPIE && Args.hasArg(options::OPT_no_pie)) {
297 const Driver &D = TC.getDriver();
298 const llvm::opt::OptTable &Opts = D.getOpts();
299 StringRef StaticPIEName = Opts.getOptionName(options::OPT_static_pie);
300 StringRef NoPIEName = Opts.getOptionName(options::OPT_nopie);
301 D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
303 return HasStaticPIE;
306 static bool getStatic(const ArgList &Args) {
307 return Args.hasArg(options::OPT_static) &&
308 !Args.hasArg(options::OPT_static_pie);
311 void tools::gnutools::StaticLibTool::ConstructJob(
312 Compilation &C, const JobAction &JA, const InputInfo &Output,
313 const InputInfoList &Inputs, const ArgList &Args,
314 const char *LinkingOutput) const {
315 const Driver &D = getToolChain().getDriver();
317 // Silence warning for "clang -g foo.o -o foo"
318 Args.ClaimAllArgs(options::OPT_g_Group);
319 // and "clang -emit-llvm foo.o -o foo"
320 Args.ClaimAllArgs(options::OPT_emit_llvm);
321 // and for "clang -w foo.o -o foo". Other warning options are already
322 // handled somewhere else.
323 Args.ClaimAllArgs(options::OPT_w);
324 // Silence warnings when linking C code with a C++ '-stdlib' argument.
325 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
327 // ar tool command "llvm-ar <options> <output_file> <input_files>".
328 ArgStringList CmdArgs;
329 // Create and insert file members with a deterministic index.
330 CmdArgs.push_back("rcsD");
331 CmdArgs.push_back(Output.getFilename());
333 for (const auto &II : Inputs) {
334 if (II.isFilename()) {
335 CmdArgs.push_back(II.getFilename());
339 // Delete old output archive file if it already exists before generating a new
340 // archive file.
341 auto OutputFileName = Output.getFilename();
342 if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
343 if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
344 D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
345 return;
349 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
350 C.addCommand(std::make_unique<Command>(JA, *this,
351 ResponseFileSupport::AtFileCurCP(),
352 Exec, CmdArgs, Inputs, Output));
355 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
356 const InputInfo &Output,
357 const InputInfoList &Inputs,
358 const ArgList &Args,
359 const char *LinkingOutput) const {
360 // FIXME: The Linker class constructor takes a ToolChain and not a
361 // Generic_ELF, so the static_cast might return a reference to a invalid
362 // instance (see PR45061). Ideally, the Linker constructor needs to take a
363 // Generic_ELF instead.
364 const auto &ToolChain = static_cast<const Generic_ELF &>(getToolChain());
365 const Driver &D = ToolChain.getDriver();
367 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
369 const llvm::Triple::ArchType Arch = ToolChain.getArch();
370 const bool isOHOSFamily = ToolChain.getTriple().isOHOSFamily();
371 const bool isAndroid = ToolChain.getTriple().isAndroid();
372 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
373 const bool IsVE = ToolChain.getTriple().isVE();
374 const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
375 const bool IsStatic = getStatic(Args);
376 const bool HasCRTBeginEndFiles =
377 ToolChain.getTriple().hasEnvironment() ||
378 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
380 ArgStringList CmdArgs;
382 // Silence warning for "clang -g foo.o -o foo"
383 Args.ClaimAllArgs(options::OPT_g_Group);
384 // and "clang -emit-llvm foo.o -o foo"
385 Args.ClaimAllArgs(options::OPT_emit_llvm);
386 // and for "clang -w foo.o -o foo". Other warning options are already
387 // handled somewhere else.
388 Args.ClaimAllArgs(options::OPT_w);
390 if (!D.SysRoot.empty())
391 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
393 if (Args.hasArg(options::OPT_s))
394 CmdArgs.push_back("-s");
396 if (Triple.isARM() || Triple.isThumb()) {
397 bool IsBigEndian = arm::isARMBigEndian(Triple, Args);
398 if (IsBigEndian)
399 arm::appendBE8LinkFlag(Args, CmdArgs, Triple);
400 CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL");
401 } else if (Triple.isAArch64()) {
402 CmdArgs.push_back(Arch == llvm::Triple::aarch64_be ? "-EB" : "-EL");
405 // Most Android ARM64 targets should enable the linker fix for erratum
406 // 843419. Only non-Cortex-A53 devices are allowed to skip this flag.
407 if (Arch == llvm::Triple::aarch64 && (isAndroid || isOHOSFamily)) {
408 std::string CPU = getCPUName(D, Args, Triple);
409 if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
410 CmdArgs.push_back("--fix-cortex-a53-843419");
413 ToolChain.addExtraOpts(CmdArgs);
415 CmdArgs.push_back("--eh-frame-hdr");
417 if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) {
418 CmdArgs.push_back("-m");
419 CmdArgs.push_back(LDMOption);
420 } else {
421 D.Diag(diag::err_target_unknown_triple) << Triple.str();
422 return;
425 if (Triple.isRISCV()) {
426 CmdArgs.push_back("-X");
427 if (Args.hasArg(options::OPT_mno_relax))
428 CmdArgs.push_back("--no-relax");
431 const bool IsShared = Args.hasArg(options::OPT_shared);
432 if (IsShared)
433 CmdArgs.push_back("-shared");
434 bool IsPIE = false;
435 if (IsStaticPIE) {
436 CmdArgs.push_back("-static");
437 CmdArgs.push_back("-pie");
438 CmdArgs.push_back("--no-dynamic-linker");
439 CmdArgs.push_back("-z");
440 CmdArgs.push_back("text");
441 } else if (IsStatic) {
442 CmdArgs.push_back("-static");
443 } else if (!Args.hasArg(options::OPT_r)) {
444 if (Args.hasArg(options::OPT_rdynamic))
445 CmdArgs.push_back("-export-dynamic");
446 if (!IsShared) {
447 IsPIE = Args.hasFlag(options::OPT_pie, options::OPT_no_pie,
448 ToolChain.isPIEDefault(Args));
449 if (IsPIE)
450 CmdArgs.push_back("-pie");
451 CmdArgs.push_back("-dynamic-linker");
452 CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) +
453 ToolChain.getDynamicLinker(Args)));
457 CmdArgs.push_back("-o");
458 CmdArgs.push_back(Output.getFilename());
460 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
461 options::OPT_r)) {
462 if (!isAndroid && !IsIAMCU) {
463 const char *crt1 = nullptr;
464 if (!Args.hasArg(options::OPT_shared)) {
465 if (Args.hasArg(options::OPT_pg))
466 crt1 = "gcrt1.o";
467 else if (IsPIE)
468 crt1 = "Scrt1.o";
469 else if (IsStaticPIE)
470 crt1 = "rcrt1.o";
471 else
472 crt1 = "crt1.o";
474 if (crt1)
475 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
477 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
480 if (IsVE) {
481 CmdArgs.push_back("-z");
482 CmdArgs.push_back("max-page-size=0x4000000");
485 if (IsIAMCU)
486 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
487 else if (HasCRTBeginEndFiles) {
488 std::string P;
489 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
490 !isAndroid) {
491 std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin",
492 ToolChain::FT_Object);
493 if (ToolChain.getVFS().exists(crtbegin))
494 P = crtbegin;
496 if (P.empty()) {
497 const char *crtbegin;
498 if (Args.hasArg(options::OPT_shared))
499 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
500 else if (IsStatic)
501 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
502 else if (IsPIE || IsStaticPIE)
503 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
504 else
505 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
506 P = ToolChain.GetFilePath(crtbegin);
508 CmdArgs.push_back(Args.MakeArgString(P));
511 // Add crtfastmath.o if available and fast math is enabled.
512 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
514 if (isAndroid && Args.hasFlag(options::OPT_fandroid_pad_segment,
515 options::OPT_fno_android_pad_segment, false))
516 CmdArgs.push_back(
517 Args.MakeArgString(ToolChain.GetFilePath("crt_pad_segment.o")));
520 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
522 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
524 if (D.isUsingLTO()) {
525 assert(!Inputs.empty() && "Must have at least one input.");
526 // Find the first filename InputInfo object.
527 auto Input = llvm::find_if(
528 Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
529 if (Input == Inputs.end())
530 // For a very rare case, all of the inputs to the linker are
531 // InputArg. If that happens, just use the first InputInfo.
532 Input = Inputs.begin();
534 addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
535 D.getLTOMode() == LTOK_Thin);
538 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
539 CmdArgs.push_back("--no-demangle");
541 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
542 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
543 addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
544 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
546 addHIPRuntimeLibArgs(ToolChain, C, Args, CmdArgs);
548 // The profile runtime also needs access to system libraries.
549 getToolChain().addProfileRTLibs(Args, CmdArgs);
551 if (D.CCCIsCXX() &&
552 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
553 options::OPT_r)) {
554 if (ToolChain.ShouldLinkCXXStdlib(Args)) {
555 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
556 !Args.hasArg(options::OPT_static);
557 if (OnlyLibstdcxxStatic)
558 CmdArgs.push_back("-Bstatic");
559 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
560 if (OnlyLibstdcxxStatic)
561 CmdArgs.push_back("-Bdynamic");
563 CmdArgs.push_back("-lm");
566 // Silence warnings when linking C code with a C++ '-stdlib' argument.
567 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
569 // Additional linker set-up and flags for Fortran. This is required in order
570 // to generate executables. As Fortran runtime depends on the C runtime,
571 // these dependencies need to be listed before the C runtime below (i.e.
572 // AddRunTimeLibs).
573 if (D.IsFlangMode() &&
574 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
575 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs);
576 addFortranRuntimeLibs(ToolChain, Args, CmdArgs);
577 CmdArgs.push_back("-lm");
580 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) {
581 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
582 if (IsStatic || IsStaticPIE)
583 CmdArgs.push_back("--start-group");
585 if (NeedsSanitizerDeps)
586 linkSanitizerRuntimeDeps(ToolChain, Args, CmdArgs);
588 if (NeedsXRayDeps)
589 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs);
591 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
592 Args.hasArg(options::OPT_pthreads);
594 // Use the static OpenMP runtime with -static-openmp
595 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
596 !Args.hasArg(options::OPT_static);
598 // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
599 // require librt. Most modern Linux platforms do, but some may not.
600 if (addOpenMPRuntime(C, CmdArgs, ToolChain, Args, StaticOpenMP,
601 JA.isHostOffloading(Action::OFK_OpenMP),
602 /* GompNeedsRT= */ true))
603 // OpenMP runtimes implies pthreads when using the GNU toolchain.
604 // FIXME: Does this really make sense for all GNU toolchains?
605 WantPthread = true;
607 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
609 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
610 // forcibly link with libatomic as a workaround.
611 // TODO: Issue #41880 and D118021.
612 if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) {
613 CmdArgs.push_back("--push-state");
614 CmdArgs.push_back("--as-needed");
615 CmdArgs.push_back("-latomic");
616 CmdArgs.push_back("--pop-state");
619 // We don't need libpthread neither for bionic (Android) nor for musl,
620 // (used by OHOS as runtime library).
621 if (WantPthread && !isAndroid && !isOHOSFamily)
622 CmdArgs.push_back("-lpthread");
624 if (Args.hasArg(options::OPT_fsplit_stack))
625 CmdArgs.push_back("--wrap=pthread_create");
627 if (!Args.hasArg(options::OPT_nolibc))
628 CmdArgs.push_back("-lc");
630 // Add IAMCU specific libs, if needed.
631 if (IsIAMCU)
632 CmdArgs.push_back("-lgloss");
634 if (IsStatic || IsStaticPIE)
635 CmdArgs.push_back("--end-group");
636 else
637 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
639 // Add IAMCU specific libs (outside the group), if needed.
640 if (IsIAMCU) {
641 CmdArgs.push_back("--as-needed");
642 CmdArgs.push_back("-lsoftfp");
643 CmdArgs.push_back("--no-as-needed");
647 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) {
648 if (HasCRTBeginEndFiles) {
649 std::string P;
650 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT &&
651 !isAndroid) {
652 std::string crtend = ToolChain.getCompilerRT(Args, "crtend",
653 ToolChain::FT_Object);
654 if (ToolChain.getVFS().exists(crtend))
655 P = crtend;
657 if (P.empty()) {
658 const char *crtend;
659 if (Args.hasArg(options::OPT_shared))
660 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
661 else if (IsPIE || IsStaticPIE)
662 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
663 else
664 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
665 P = ToolChain.GetFilePath(crtend);
667 CmdArgs.push_back(Args.MakeArgString(P));
669 if (!isAndroid)
670 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
674 Args.addAllArgs(CmdArgs, {options::OPT_T, options::OPT_t});
676 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
677 C.addCommand(std::make_unique<Command>(JA, *this,
678 ResponseFileSupport::AtFileCurCP(),
679 Exec, CmdArgs, Inputs, Output));
682 void tools::gnutools::Assembler::ConstructJob(Compilation &C,
683 const JobAction &JA,
684 const InputInfo &Output,
685 const InputInfoList &Inputs,
686 const ArgList &Args,
687 const char *LinkingOutput) const {
688 const auto &D = getToolChain().getDriver();
690 claimNoWarnArgs(Args);
692 ArgStringList CmdArgs;
694 llvm::Reloc::Model RelocationModel;
695 unsigned PICLevel;
696 bool IsPIE;
697 const char *DefaultAssembler = "as";
698 // Enforce GNU as on Solaris; the native assembler's input syntax isn't fully
699 // compatible.
700 if (getToolChain().getTriple().isOSSolaris())
701 DefaultAssembler = "gas";
702 std::tie(RelocationModel, PICLevel, IsPIE) =
703 ParsePICArgs(getToolChain(), Args);
705 if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) {
706 if (A->getOption().getID() == options::OPT_gz) {
707 CmdArgs.push_back("--compress-debug-sections");
708 } else {
709 StringRef Value = A->getValue();
710 if (Value == "none" || Value == "zlib" || Value == "zstd") {
711 CmdArgs.push_back(
712 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
713 } else {
714 D.Diag(diag::err_drv_unsupported_option_argument)
715 << A->getSpelling() << Value;
720 switch (getToolChain().getArch()) {
721 default:
722 break;
723 // Add --32/--64 to make sure we get the format we want.
724 // This is incomplete
725 case llvm::Triple::x86:
726 CmdArgs.push_back("--32");
727 break;
728 case llvm::Triple::x86_64:
729 if (getToolChain().getTriple().isX32())
730 CmdArgs.push_back("--x32");
731 else
732 CmdArgs.push_back("--64");
733 break;
734 case llvm::Triple::ppc: {
735 CmdArgs.push_back("-a32");
736 CmdArgs.push_back("-mppc");
737 CmdArgs.push_back("-mbig-endian");
738 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
739 getCPUName(D, Args, getToolChain().getTriple())));
740 break;
742 case llvm::Triple::ppcle: {
743 CmdArgs.push_back("-a32");
744 CmdArgs.push_back("-mppc");
745 CmdArgs.push_back("-mlittle-endian");
746 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
747 getCPUName(D, Args, getToolChain().getTriple())));
748 break;
750 case llvm::Triple::ppc64: {
751 CmdArgs.push_back("-a64");
752 CmdArgs.push_back("-mppc64");
753 CmdArgs.push_back("-mbig-endian");
754 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
755 getCPUName(D, Args, getToolChain().getTriple())));
756 break;
758 case llvm::Triple::ppc64le: {
759 CmdArgs.push_back("-a64");
760 CmdArgs.push_back("-mppc64");
761 CmdArgs.push_back("-mlittle-endian");
762 CmdArgs.push_back(ppc::getPPCAsmModeForCPU(
763 getCPUName(D, Args, getToolChain().getTriple())));
764 break;
766 case llvm::Triple::riscv32:
767 case llvm::Triple::riscv64: {
768 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
769 CmdArgs.push_back("-mabi");
770 CmdArgs.push_back(ABIName.data());
771 std::string MArchName =
772 riscv::getRISCVArch(Args, getToolChain().getTriple());
773 CmdArgs.push_back("-march");
774 CmdArgs.push_back(Args.MakeArgString(MArchName));
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;
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;
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;
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;
813 switch (arm::getARMFloatABI(getToolChain(), Args)) {
814 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
815 case arm::FloatABI::Soft:
816 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
817 break;
818 case arm::FloatABI::SoftFP:
819 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
820 break;
821 case arm::FloatABI::Hard:
822 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
823 break;
826 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
827 normalizeCPUNamesForAssembler(Args, CmdArgs);
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;
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);
844 break;
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;
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);
862 CmdArgs.push_back("-march");
863 CmdArgs.push_back(CPUName.data());
865 CmdArgs.push_back("-mabi");
866 CmdArgs.push_back(ABIName.data());
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");
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");
878 if (getToolChain().getTriple().isLittleEndian())
879 CmdArgs.push_back("-EL");
880 else
881 CmdArgs.push_back("-EB");
883 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
884 if (StringRef(A->getValue()) == "2008")
885 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
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");
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");
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);
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"));
924 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
925 options::OPT_msoft_float);
927 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
928 options::OPT_msingle_float);
930 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
931 options::OPT_mno_odd_spreg);
933 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
934 break;
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 =
940 systemz::getSystemZTargetCPU(Args, getToolChain().getTriple());
941 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
942 break;
944 case llvm::Triple::ve:
945 DefaultAssembler = "nas";
948 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
949 options::OPT_fdebug_prefix_map_EQ)) {
950 StringRef Map = A->getValue();
951 if (!Map.contains('='))
952 D.Diag(diag::err_drv_invalid_argument_to_option)
953 << Map << A->getOption().getName();
954 else {
955 CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map"));
956 CmdArgs.push_back(Args.MakeArgString(Map));
958 A->claim();
961 Args.AddAllArgs(CmdArgs, options::OPT_I);
962 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
964 CmdArgs.push_back("-o");
965 CmdArgs.push_back(Output.getFilename());
967 for (const auto &II : Inputs)
968 CmdArgs.push_back(II.getFilename());
970 if (Arg *A = Args.getLastArg(options::OPT_g_Flag, options::OPT_gN_Group,
971 options::OPT_gdwarf_2, options::OPT_gdwarf_3,
972 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
973 options::OPT_gdwarf))
974 if (!A->getOption().matches(options::OPT_g0)) {
975 Args.AddLastArg(CmdArgs, options::OPT_g_Flag);
977 unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
978 CmdArgs.push_back(Args.MakeArgString("-gdwarf-" + Twine(DwarfVersion)));
981 const char *Exec =
982 Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler));
983 C.addCommand(std::make_unique<Command>(JA, *this,
984 ResponseFileSupport::AtFileCurCP(),
985 Exec, CmdArgs, Inputs, Output));
987 // Handle the debug info splitting at object creation time if we're
988 // creating an object.
989 // TODO: Currently only works on linux with newer objcopy.
990 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
991 getToolChain().getTriple().isOSLinux())
992 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
993 SplitDebugName(JA, Args, Inputs[0], Output));
996 namespace {
997 // Filter to remove Multilibs that don't exist as a suffix to Path
998 class FilterNonExistent {
999 StringRef Base, File;
1000 llvm::vfs::FileSystem &VFS;
1002 public:
1003 FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS)
1004 : Base(Base), File(File), VFS(VFS) {}
1005 bool operator()(const Multilib &M) {
1006 return !VFS.exists(Base + M.gccSuffix() + File);
1009 } // end anonymous namespace
1011 static bool isSoftFloatABI(const ArgList &Args) {
1012 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1013 options::OPT_mfloat_abi_EQ);
1014 if (!A)
1015 return false;
1017 return A->getOption().matches(options::OPT_msoft_float) ||
1018 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
1019 A->getValue() == StringRef("soft"));
1022 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) {
1023 return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb;
1026 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1027 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1030 static bool isMips16(const ArgList &Args) {
1031 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1032 return A && A->getOption().matches(options::OPT_mips16);
1035 static bool isMicroMips(const ArgList &Args) {
1036 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1037 return A && A->getOption().matches(options::OPT_mmicromips);
1040 static bool isMSP430(llvm::Triple::ArchType Arch) {
1041 return Arch == llvm::Triple::msp430;
1044 static bool findMipsCsMultilibs(const Driver &D,
1045 const Multilib::flags_list &Flags,
1046 FilterNonExistent &NonExistent,
1047 DetectedMultilibs &Result) {
1048 // Check for Code Sourcery toolchain multilibs
1049 MultilibSet CSMipsMultilibs;
1051 auto MArchMips16 = MultilibBuilder("/mips16").flag("-m32").flag("-mips16");
1053 auto MArchMicroMips =
1054 MultilibBuilder("/micromips").flag("-m32").flag("-mmicromips");
1056 auto MArchDefault = MultilibBuilder("")
1057 .flag("-mips16", /*Disallow=*/true)
1058 .flag("-mmicromips", /*Disallow=*/true);
1060 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1062 auto SoftFloat = MultilibBuilder("/soft-float").flag("-msoft-float");
1064 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1066 auto DefaultFloat = MultilibBuilder("")
1067 .flag("-msoft-float", /*Disallow=*/true)
1068 .flag("-mnan=2008", /*Disallow=*/true);
1070 auto BigEndian =
1071 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1073 auto LittleEndian =
1074 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1076 // Note that this one's osSuffix is ""
1077 auto MAbi64 = MultilibBuilder("")
1078 .gccSuffix("/64")
1079 .includeSuffix("/64")
1080 .flag("-mabi=n64")
1081 .flag("-mabi=n32", /*Disallow=*/true)
1082 .flag("-m32", /*Disallow=*/true);
1084 CSMipsMultilibs =
1085 MultilibSetBuilder()
1086 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1087 .Maybe(UCLibc)
1088 .Either(SoftFloat, Nan2008, DefaultFloat)
1089 .FilterOut("/micromips/nan2008")
1090 .FilterOut("/mips16/nan2008")
1091 .Either(BigEndian, LittleEndian)
1092 .Maybe(MAbi64)
1093 .FilterOut("/mips16.*/64")
1094 .FilterOut("/micromips.*/64")
1095 .makeMultilibSet()
1096 .FilterOut(NonExistent)
1097 .setIncludeDirsCallback([](const Multilib &M) {
1098 std::vector<std::string> Dirs({"/include"});
1099 if (StringRef(M.includeSuffix()).starts_with("/uclibc"))
1100 Dirs.push_back(
1101 "/../../../../mips-linux-gnu/libc/uclibc/usr/include");
1102 else
1103 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include");
1104 return Dirs;
1108 MultilibSet DebianMipsMultilibs;
1110 MultilibBuilder MAbiN32 =
1111 MultilibBuilder().gccSuffix("/n32").includeSuffix("/n32").flag(
1112 "-mabi=n32");
1114 MultilibBuilder M64 = MultilibBuilder()
1115 .gccSuffix("/64")
1116 .includeSuffix("/64")
1117 .flag("-m64")
1118 .flag("-m32", /*Disallow=*/true)
1119 .flag("-mabi=n32", /*Disallow=*/true);
1121 MultilibBuilder M32 = MultilibBuilder()
1122 .gccSuffix("/32")
1123 .flag("-m64", /*Disallow=*/true)
1124 .flag("-m32")
1125 .flag("-mabi=n32", /*Disallow=*/true);
1127 DebianMipsMultilibs = MultilibSetBuilder()
1128 .Either(M32, M64, MAbiN32)
1129 .makeMultilibSet()
1130 .FilterOut(NonExistent);
1133 // Sort candidates. Toolchain that best meets the directories tree goes first.
1134 // Then select the first toolchains matches command line flags.
1135 MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs};
1136 if (CSMipsMultilibs.size() < DebianMipsMultilibs.size())
1137 std::iter_swap(Candidates, Candidates + 1);
1138 for (const MultilibSet *Candidate : Candidates) {
1139 if (Candidate->select(D, Flags, Result.SelectedMultilibs)) {
1140 if (Candidate == &DebianMipsMultilibs)
1141 Result.BiarchSibling = Multilib();
1142 Result.Multilibs = *Candidate;
1143 return true;
1146 return false;
1149 static bool findMipsAndroidMultilibs(const Driver &D,
1150 llvm::vfs::FileSystem &VFS, StringRef Path,
1151 const Multilib::flags_list &Flags,
1152 FilterNonExistent &NonExistent,
1153 DetectedMultilibs &Result) {
1155 MultilibSet AndroidMipsMultilibs =
1156 MultilibSetBuilder()
1157 .Maybe(MultilibBuilder("/mips-r2", {}, {}).flag("-march=mips32r2"))
1158 .Maybe(MultilibBuilder("/mips-r6", {}, {}).flag("-march=mips32r6"))
1159 .makeMultilibSet()
1160 .FilterOut(NonExistent);
1162 MultilibSet AndroidMipselMultilibs =
1163 MultilibSetBuilder()
1164 .Either(MultilibBuilder().flag("-march=mips32"),
1165 MultilibBuilder("/mips-r2", "", "/mips-r2")
1166 .flag("-march=mips32r2"),
1167 MultilibBuilder("/mips-r6", "", "/mips-r6")
1168 .flag("-march=mips32r6"))
1169 .makeMultilibSet()
1170 .FilterOut(NonExistent);
1172 MultilibSet AndroidMips64elMultilibs =
1173 MultilibSetBuilder()
1174 .Either(MultilibBuilder().flag("-march=mips64r6"),
1175 MultilibBuilder("/32/mips-r1", "", "/mips-r1")
1176 .flag("-march=mips32"),
1177 MultilibBuilder("/32/mips-r2", "", "/mips-r2")
1178 .flag("-march=mips32r2"),
1179 MultilibBuilder("/32/mips-r6", "", "/mips-r6")
1180 .flag("-march=mips32r6"))
1181 .makeMultilibSet()
1182 .FilterOut(NonExistent);
1184 MultilibSet *MS = &AndroidMipsMultilibs;
1185 if (VFS.exists(Path + "/mips-r6"))
1186 MS = &AndroidMipselMultilibs;
1187 else if (VFS.exists(Path + "/32"))
1188 MS = &AndroidMips64elMultilibs;
1189 if (MS->select(D, Flags, Result.SelectedMultilibs)) {
1190 Result.Multilibs = *MS;
1191 return true;
1193 return false;
1196 static bool findMipsMuslMultilibs(const Driver &D,
1197 const Multilib::flags_list &Flags,
1198 FilterNonExistent &NonExistent,
1199 DetectedMultilibs &Result) {
1200 // Musl toolchain multilibs
1201 MultilibSet MuslMipsMultilibs;
1203 auto MArchMipsR2 = MultilibBuilder("")
1204 .osSuffix("/mips-r2-hard-musl")
1205 .flag("-EB")
1206 .flag("-EL", /*Disallow=*/true)
1207 .flag("-march=mips32r2");
1209 auto MArchMipselR2 = MultilibBuilder("/mipsel-r2-hard-musl")
1210 .flag("-EB", /*Disallow=*/true)
1211 .flag("-EL")
1212 .flag("-march=mips32r2");
1214 MuslMipsMultilibs = MultilibSetBuilder()
1215 .Either(MArchMipsR2, MArchMipselR2)
1216 .makeMultilibSet();
1218 // Specify the callback that computes the include directories.
1219 MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) {
1220 return std::vector<std::string>(
1221 {"/../sysroot" + M.osSuffix() + "/usr/include"});
1224 if (MuslMipsMultilibs.select(D, Flags, Result.SelectedMultilibs)) {
1225 Result.Multilibs = MuslMipsMultilibs;
1226 return true;
1228 return false;
1231 static bool findMipsMtiMultilibs(const Driver &D,
1232 const Multilib::flags_list &Flags,
1233 FilterNonExistent &NonExistent,
1234 DetectedMultilibs &Result) {
1235 // CodeScape MTI toolchain v1.2 and early.
1236 MultilibSet MtiMipsMultilibsV1;
1238 auto MArchMips32 = MultilibBuilder("/mips32")
1239 .flag("-m32")
1240 .flag("-m64", /*Disallow=*/true)
1241 .flag("-mmicromips", /*Disallow=*/true)
1242 .flag("-march=mips32");
1244 auto MArchMicroMips = MultilibBuilder("/micromips")
1245 .flag("-m32")
1246 .flag("-m64", /*Disallow=*/true)
1247 .flag("-mmicromips");
1249 auto MArchMips64r2 = MultilibBuilder("/mips64r2")
1250 .flag("-m32", /*Disallow=*/true)
1251 .flag("-m64")
1252 .flag("-march=mips64r2");
1254 auto MArchMips64 = MultilibBuilder("/mips64")
1255 .flag("-m32", /*Disallow=*/true)
1256 .flag("-m64")
1257 .flag("-march=mips64r2", /*Disallow=*/true);
1259 auto MArchDefault = MultilibBuilder("")
1260 .flag("-m32")
1261 .flag("-m64", /*Disallow=*/true)
1262 .flag("-mmicromips", /*Disallow=*/true)
1263 .flag("-march=mips32r2");
1265 auto Mips16 = MultilibBuilder("/mips16").flag("-mips16");
1267 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc");
1269 auto MAbi64 = MultilibBuilder("/64")
1270 .flag("-mabi=n64")
1271 .flag("-mabi=n32", /*Disallow=*/true)
1272 .flag("-m32", /*Disallow=*/true);
1274 auto BigEndian =
1275 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true);
1277 auto LittleEndian =
1278 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1280 auto SoftFloat = MultilibBuilder("/sof").flag("-msoft-float");
1282 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008");
1284 MtiMipsMultilibsV1 =
1285 MultilibSetBuilder()
1286 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1287 MArchDefault)
1288 .Maybe(UCLibc)
1289 .Maybe(Mips16)
1290 .FilterOut("/mips64/mips16")
1291 .FilterOut("/mips64r2/mips16")
1292 .FilterOut("/micromips/mips16")
1293 .Maybe(MAbi64)
1294 .FilterOut("/micromips/64")
1295 .FilterOut("/mips32/64")
1296 .FilterOut("^/64")
1297 .FilterOut("/mips16/64")
1298 .Either(BigEndian, LittleEndian)
1299 .Maybe(SoftFloat)
1300 .Maybe(Nan2008)
1301 .FilterOut(".*sof/nan2008")
1302 .makeMultilibSet()
1303 .FilterOut(NonExistent)
1304 .setIncludeDirsCallback([](const Multilib &M) {
1305 std::vector<std::string> Dirs({"/include"});
1306 if (StringRef(M.includeSuffix()).starts_with("/uclibc"))
1307 Dirs.push_back("/../../../../sysroot/uclibc/usr/include");
1308 else
1309 Dirs.push_back("/../../../../sysroot/usr/include");
1310 return Dirs;
1314 // CodeScape IMG toolchain starting from v1.3.
1315 MultilibSet MtiMipsMultilibsV2;
1317 auto BeHard = MultilibBuilder("/mips-r2-hard")
1318 .flag("-EB")
1319 .flag("-msoft-float", /*Disallow=*/true)
1320 .flag("-mnan=2008", /*Disallow=*/true)
1321 .flag("-muclibc", /*Disallow=*/true);
1322 auto BeSoft = MultilibBuilder("/mips-r2-soft")
1323 .flag("-EB")
1324 .flag("-msoft-float")
1325 .flag("-mnan=2008", /*Disallow=*/true);
1326 auto ElHard = MultilibBuilder("/mipsel-r2-hard")
1327 .flag("-EL")
1328 .flag("-msoft-float", /*Disallow=*/true)
1329 .flag("-mnan=2008", /*Disallow=*/true)
1330 .flag("-muclibc", /*Disallow=*/true);
1331 auto ElSoft = MultilibBuilder("/mipsel-r2-soft")
1332 .flag("-EL")
1333 .flag("-msoft-float")
1334 .flag("-mnan=2008", /*Disallow=*/true)
1335 .flag("-mmicromips", /*Disallow=*/true);
1336 auto BeHardNan = MultilibBuilder("/mips-r2-hard-nan2008")
1337 .flag("-EB")
1338 .flag("-msoft-float", /*Disallow=*/true)
1339 .flag("-mnan=2008")
1340 .flag("-muclibc", /*Disallow=*/true);
1341 auto ElHardNan = MultilibBuilder("/mipsel-r2-hard-nan2008")
1342 .flag("-EL")
1343 .flag("-msoft-float", /*Disallow=*/true)
1344 .flag("-mnan=2008")
1345 .flag("-muclibc", /*Disallow=*/true)
1346 .flag("-mmicromips", /*Disallow=*/true);
1347 auto BeHardNanUclibc = MultilibBuilder("/mips-r2-hard-nan2008-uclibc")
1348 .flag("-EB")
1349 .flag("-msoft-float", /*Disallow=*/true)
1350 .flag("-mnan=2008")
1351 .flag("-muclibc");
1352 auto ElHardNanUclibc = MultilibBuilder("/mipsel-r2-hard-nan2008-uclibc")
1353 .flag("-EL")
1354 .flag("-msoft-float", /*Disallow=*/true)
1355 .flag("-mnan=2008")
1356 .flag("-muclibc");
1357 auto BeHardUclibc = MultilibBuilder("/mips-r2-hard-uclibc")
1358 .flag("-EB")
1359 .flag("-msoft-float", /*Disallow=*/true)
1360 .flag("-mnan=2008", /*Disallow=*/true)
1361 .flag("-muclibc");
1362 auto ElHardUclibc = MultilibBuilder("/mipsel-r2-hard-uclibc")
1363 .flag("-EL")
1364 .flag("-msoft-float", /*Disallow=*/true)
1365 .flag("-mnan=2008", /*Disallow=*/true)
1366 .flag("-muclibc");
1367 auto ElMicroHardNan = MultilibBuilder("/micromipsel-r2-hard-nan2008")
1368 .flag("-EL")
1369 .flag("-msoft-float", /*Disallow=*/true)
1370 .flag("-mnan=2008")
1371 .flag("-mmicromips");
1372 auto ElMicroSoft = MultilibBuilder("/micromipsel-r2-soft")
1373 .flag("-EL")
1374 .flag("-msoft-float")
1375 .flag("-mnan=2008", /*Disallow=*/true)
1376 .flag("-mmicromips");
1378 auto O32 = MultilibBuilder("/lib")
1379 .osSuffix("")
1380 .flag("-mabi=n32", /*Disallow=*/true)
1381 .flag("-mabi=n64", /*Disallow=*/true);
1382 auto N32 = MultilibBuilder("/lib32")
1383 .osSuffix("")
1384 .flag("-mabi=n32")
1385 .flag("-mabi=n64", /*Disallow=*/true);
1386 auto N64 = MultilibBuilder("/lib64")
1387 .osSuffix("")
1388 .flag("-mabi=n32", /*Disallow=*/true)
1389 .flag("-mabi=n64");
1391 MtiMipsMultilibsV2 =
1392 MultilibSetBuilder()
1393 .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan,
1394 BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc,
1395 ElHardUclibc, ElMicroHardNan, ElMicroSoft})
1396 .Either(O32, N32, N64)
1397 .makeMultilibSet()
1398 .FilterOut(NonExistent)
1399 .setIncludeDirsCallback([](const Multilib &M) {
1400 return std::vector<std::string>({"/../../../../sysroot" +
1401 M.includeSuffix() +
1402 "/../usr/include"});
1404 .setFilePathsCallback([](const Multilib &M) {
1405 return std::vector<std::string>(
1406 {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()});
1409 for (auto *Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) {
1410 if (Candidate->select(D, Flags, Result.SelectedMultilibs)) {
1411 Result.Multilibs = *Candidate;
1412 return true;
1415 return false;
1418 static bool findMipsImgMultilibs(const Driver &D,
1419 const Multilib::flags_list &Flags,
1420 FilterNonExistent &NonExistent,
1421 DetectedMultilibs &Result) {
1422 // CodeScape IMG toolchain v1.2 and early.
1423 MultilibSet ImgMultilibsV1;
1425 auto Mips64r6 = MultilibBuilder("/mips64r6")
1426 .flag("-m64")
1427 .flag("-m32", /*Disallow=*/true);
1429 auto LittleEndian =
1430 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true);
1432 auto MAbi64 = MultilibBuilder("/64")
1433 .flag("-mabi=n64")
1434 .flag("-mabi=n32", /*Disallow=*/true)
1435 .flag("-m32", /*Disallow=*/true);
1437 ImgMultilibsV1 =
1438 MultilibSetBuilder()
1439 .Maybe(Mips64r6)
1440 .Maybe(MAbi64)
1441 .Maybe(LittleEndian)
1442 .makeMultilibSet()
1443 .FilterOut(NonExistent)
1444 .setIncludeDirsCallback([](const Multilib &M) {
1445 return std::vector<std::string>(
1446 {"/include", "/../../../../sysroot/usr/include"});
1450 // CodeScape IMG toolchain starting from v1.3.
1451 MultilibSet ImgMultilibsV2;
1453 auto BeHard = MultilibBuilder("/mips-r6-hard")
1454 .flag("-EB")
1455 .flag("-msoft-float", /*Disallow=*/true)
1456 .flag("-mmicromips", /*Disallow=*/true);
1457 auto BeSoft = MultilibBuilder("/mips-r6-soft")
1458 .flag("-EB")
1459 .flag("-msoft-float")
1460 .flag("-mmicromips", /*Disallow=*/true);
1461 auto ElHard = MultilibBuilder("/mipsel-r6-hard")
1462 .flag("-EL")
1463 .flag("-msoft-float", /*Disallow=*/true)
1464 .flag("-mmicromips", /*Disallow=*/true);
1465 auto ElSoft = MultilibBuilder("/mipsel-r6-soft")
1466 .flag("-EL")
1467 .flag("-msoft-float")
1468 .flag("-mmicromips", /*Disallow=*/true);
1469 auto BeMicroHard = MultilibBuilder("/micromips-r6-hard")
1470 .flag("-EB")
1471 .flag("-msoft-float", /*Disallow=*/true)
1472 .flag("-mmicromips");
1473 auto BeMicroSoft = MultilibBuilder("/micromips-r6-soft")
1474 .flag("-EB")
1475 .flag("-msoft-float")
1476 .flag("-mmicromips");
1477 auto ElMicroHard = MultilibBuilder("/micromipsel-r6-hard")
1478 .flag("-EL")
1479 .flag("-msoft-float", /*Disallow=*/true)
1480 .flag("-mmicromips");
1481 auto ElMicroSoft = MultilibBuilder("/micromipsel-r6-soft")
1482 .flag("-EL")
1483 .flag("-msoft-float")
1484 .flag("-mmicromips");
1486 auto O32 = MultilibBuilder("/lib")
1487 .osSuffix("")
1488 .flag("-mabi=n32", /*Disallow=*/true)
1489 .flag("-mabi=n64", /*Disallow=*/true);
1490 auto N32 = MultilibBuilder("/lib32")
1491 .osSuffix("")
1492 .flag("-mabi=n32")
1493 .flag("-mabi=n64", /*Disallow=*/true);
1494 auto N64 = MultilibBuilder("/lib64")
1495 .osSuffix("")
1496 .flag("-mabi=n32", /*Disallow=*/true)
1497 .flag("-mabi=n64");
1499 ImgMultilibsV2 =
1500 MultilibSetBuilder()
1501 .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft,
1502 ElMicroHard, ElMicroSoft})
1503 .Either(O32, N32, N64)
1504 .makeMultilibSet()
1505 .FilterOut(NonExistent)
1506 .setIncludeDirsCallback([](const Multilib &M) {
1507 return std::vector<std::string>({"/../../../../sysroot" +
1508 M.includeSuffix() +
1509 "/../usr/include"});
1511 .setFilePathsCallback([](const Multilib &M) {
1512 return std::vector<std::string>(
1513 {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()});
1516 for (auto *Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) {
1517 if (Candidate->select(D, Flags, Result.SelectedMultilibs)) {
1518 Result.Multilibs = *Candidate;
1519 return true;
1522 return false;
1525 bool clang::driver::findMIPSMultilibs(const Driver &D,
1526 const llvm::Triple &TargetTriple,
1527 StringRef Path, const ArgList &Args,
1528 DetectedMultilibs &Result) {
1529 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1531 StringRef CPUName;
1532 StringRef ABIName;
1533 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
1535 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
1537 Multilib::flags_list Flags;
1538 addMultilibFlag(TargetTriple.isMIPS32(), "-m32", Flags);
1539 addMultilibFlag(TargetTriple.isMIPS64(), "-m64", Flags);
1540 addMultilibFlag(isMips16(Args), "-mips16", Flags);
1541 addMultilibFlag(CPUName == "mips32", "-march=mips32", Flags);
1542 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
1543 CPUName == "mips32r5" || CPUName == "p5600",
1544 "-march=mips32r2", Flags);
1545 addMultilibFlag(CPUName == "mips32r6", "-march=mips32r6", Flags);
1546 addMultilibFlag(CPUName == "mips64", "-march=mips64", Flags);
1547 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
1548 CPUName == "mips64r5" || CPUName == "octeon" ||
1549 CPUName == "octeon+",
1550 "-march=mips64r2", Flags);
1551 addMultilibFlag(CPUName == "mips64r6", "-march=mips64r6", Flags);
1552 addMultilibFlag(isMicroMips(Args), "-mmicromips", Flags);
1553 addMultilibFlag(tools::mips::isUCLibc(Args), "-muclibc", Flags);
1554 addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "-mnan=2008",
1555 Flags);
1556 addMultilibFlag(ABIName == "n32", "-mabi=n32", Flags);
1557 addMultilibFlag(ABIName == "n64", "-mabi=n64", Flags);
1558 addMultilibFlag(isSoftFloatABI(Args), "-msoft-float", Flags);
1559 addMultilibFlag(!isSoftFloatABI(Args), "-mhard-float", Flags);
1560 addMultilibFlag(isMipsEL(TargetArch), "-EL", Flags);
1561 addMultilibFlag(!isMipsEL(TargetArch), "-EB", Flags);
1563 if (TargetTriple.isAndroid())
1564 return findMipsAndroidMultilibs(D, D.getVFS(), Path, Flags, NonExistent,
1565 Result);
1567 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1568 TargetTriple.getOS() == llvm::Triple::Linux &&
1569 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
1570 return findMipsMuslMultilibs(D, Flags, NonExistent, Result);
1572 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
1573 TargetTriple.getOS() == llvm::Triple::Linux &&
1574 TargetTriple.isGNUEnvironment())
1575 return findMipsMtiMultilibs(D, Flags, NonExistent, Result);
1577 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1578 TargetTriple.getOS() == llvm::Triple::Linux &&
1579 TargetTriple.isGNUEnvironment())
1580 return findMipsImgMultilibs(D, Flags, NonExistent, Result);
1582 if (findMipsCsMultilibs(D, Flags, NonExistent, Result))
1583 return true;
1585 // Fallback to the regular toolchain-tree structure.
1586 Multilib Default;
1587 Result.Multilibs.push_back(Default);
1588 Result.Multilibs.FilterOut(NonExistent);
1590 if (Result.Multilibs.select(D, Flags, Result.SelectedMultilibs)) {
1591 Result.BiarchSibling = Multilib();
1592 return true;
1595 return false;
1598 static void findAndroidArmMultilibs(const Driver &D,
1599 const llvm::Triple &TargetTriple,
1600 StringRef Path, const ArgList &Args,
1601 DetectedMultilibs &Result) {
1602 // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb.
1603 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1604 MultilibBuilder ArmV7Multilib = MultilibBuilder("/armv7-a")
1605 .flag("-march=armv7-a")
1606 .flag("-mthumb", /*Disallow=*/true);
1607 MultilibBuilder ThumbMultilib = MultilibBuilder("/thumb")
1608 .flag("-march=armv7-a", /*Disallow=*/true)
1609 .flag("-mthumb");
1610 MultilibBuilder ArmV7ThumbMultilib =
1611 MultilibBuilder("/armv7-a/thumb").flag("-march=armv7-a").flag("-mthumb");
1612 MultilibBuilder DefaultMultilib =
1613 MultilibBuilder("")
1614 .flag("-march=armv7-a", /*Disallow=*/true)
1615 .flag("-mthumb", /*Disallow=*/true);
1616 MultilibSet AndroidArmMultilibs =
1617 MultilibSetBuilder()
1618 .Either(ThumbMultilib, ArmV7Multilib, ArmV7ThumbMultilib,
1619 DefaultMultilib)
1620 .makeMultilibSet()
1621 .FilterOut(NonExistent);
1623 Multilib::flags_list Flags;
1624 llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ);
1625 bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm;
1626 bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb;
1627 bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7;
1628 bool IsThumbMode = IsThumbArch ||
1629 Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) ||
1630 (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB);
1631 bool IsArmV7Mode = (IsArmArch || IsThumbArch) &&
1632 (llvm::ARM::parseArchVersion(Arch) == 7 ||
1633 (IsArmArch && Arch == "" && IsV7SubArch));
1634 addMultilibFlag(IsArmV7Mode, "-march=armv7-a", Flags);
1635 addMultilibFlag(IsThumbMode, "-mthumb", Flags);
1637 if (AndroidArmMultilibs.select(D, Flags, Result.SelectedMultilibs))
1638 Result.Multilibs = AndroidArmMultilibs;
1641 static bool findMSP430Multilibs(const Driver &D,
1642 const llvm::Triple &TargetTriple,
1643 StringRef Path, const ArgList &Args,
1644 DetectedMultilibs &Result) {
1645 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1646 MultilibBuilder WithoutExceptions =
1647 MultilibBuilder("/430").flag("-exceptions", /*Disallow=*/true);
1648 MultilibBuilder WithExceptions =
1649 MultilibBuilder("/430/exceptions").flag("-exceptions");
1651 // FIXME: when clang starts to support msp430x ISA additional logic
1652 // to select between multilib must be implemented
1653 // MultilibBuilder MSP430xMultilib = MultilibBuilder("/large");
1655 Result.Multilibs.push_back(WithoutExceptions.makeMultilib());
1656 Result.Multilibs.push_back(WithExceptions.makeMultilib());
1657 Result.Multilibs.FilterOut(NonExistent);
1659 Multilib::flags_list Flags;
1660 addMultilibFlag(Args.hasFlag(options::OPT_fexceptions,
1661 options::OPT_fno_exceptions, false),
1662 "-exceptions", Flags);
1663 if (Result.Multilibs.select(D, Flags, Result.SelectedMultilibs))
1664 return true;
1666 return false;
1669 static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1670 StringRef Path, const ArgList &Args,
1671 DetectedMultilibs &Result) {
1672 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1674 tools::csky::FloatABI TheFloatABI = tools::csky::getCSKYFloatABI(D, Args);
1675 std::optional<llvm::StringRef> Res =
1676 tools::csky::getCSKYArchName(D, Args, TargetTriple);
1678 if (!Res)
1679 return;
1680 auto ARCHName = *Res;
1682 Multilib::flags_list Flags;
1683 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Hard, "-hard-fp",
1684 Flags);
1685 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::SoftFP, "-soft-fp",
1686 Flags);
1687 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Soft, "-soft", Flags);
1688 addMultilibFlag(ARCHName == "ck801", "-march=ck801", Flags);
1689 addMultilibFlag(ARCHName == "ck802", "-march=ck802", Flags);
1690 addMultilibFlag(ARCHName == "ck803", "-march=ck803", Flags);
1691 addMultilibFlag(ARCHName == "ck804", "-march=ck804", Flags);
1692 addMultilibFlag(ARCHName == "ck805", "-march=ck805", Flags);
1693 addMultilibFlag(ARCHName == "ck807", "-march=ck807", Flags);
1694 addMultilibFlag(ARCHName == "ck810", "-march=ck810", Flags);
1695 addMultilibFlag(ARCHName == "ck810v", "-march=ck810v", Flags);
1696 addMultilibFlag(ARCHName == "ck860", "-march=ck860", Flags);
1697 addMultilibFlag(ARCHName == "ck860v", "-march=ck860v", Flags);
1699 bool isBigEndian = false;
1700 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
1701 options::OPT_mbig_endian))
1702 isBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
1703 addMultilibFlag(isBigEndian, "-EB", Flags);
1705 auto HardFloat = MultilibBuilder("/hard-fp").flag("-hard-fp");
1706 auto SoftFpFloat = MultilibBuilder("/soft-fp").flag("-soft-fp");
1707 auto SoftFloat = MultilibBuilder("").flag("-soft");
1708 auto Arch801 = MultilibBuilder("/ck801").flag("-march=ck801");
1709 auto Arch802 = MultilibBuilder("/ck802").flag("-march=ck802");
1710 auto Arch803 = MultilibBuilder("/ck803").flag("-march=ck803");
1711 // CK804 use the same library as CK803
1712 auto Arch804 = MultilibBuilder("/ck803").flag("-march=ck804");
1713 auto Arch805 = MultilibBuilder("/ck805").flag("-march=ck805");
1714 auto Arch807 = MultilibBuilder("/ck807").flag("-march=ck807");
1715 auto Arch810 = MultilibBuilder("").flag("-march=ck810");
1716 auto Arch810v = MultilibBuilder("/ck810v").flag("-march=ck810v");
1717 auto Arch860 = MultilibBuilder("/ck860").flag("-march=ck860");
1718 auto Arch860v = MultilibBuilder("/ck860v").flag("-march=ck860v");
1719 auto BigEndian = MultilibBuilder("/big").flag("-EB");
1721 MultilibSet CSKYMultilibs =
1722 MultilibSetBuilder()
1723 .Maybe(BigEndian)
1724 .Either({Arch801, Arch802, Arch803, Arch804, Arch805, Arch807,
1725 Arch810, Arch810v, Arch860, Arch860v})
1726 .Either(HardFloat, SoftFpFloat, SoftFloat)
1727 .makeMultilibSet()
1728 .FilterOut(NonExistent);
1730 if (CSKYMultilibs.select(D, Flags, Result.SelectedMultilibs))
1731 Result.Multilibs = CSKYMultilibs;
1734 /// Extend the multi-lib re-use selection mechanism for RISC-V.
1735 /// This function will try to re-use multi-lib if they are compatible.
1736 /// Definition of compatible:
1737 /// - ABI must be the same.
1738 /// - multi-lib is a subset of current arch, e.g. multi-lib=march=rv32im
1739 /// is a subset of march=rv32imc.
1740 /// - march that contains atomic extension can't reuse multi-lib that
1741 /// doesn't have atomic, vice versa. e.g. multi-lib=march=rv32im and
1742 /// march=rv32ima are not compatible, because software and hardware
1743 /// atomic operation can't work together correctly.
1744 static bool
1745 selectRISCVMultilib(const Driver &D, const MultilibSet &RISCVMultilibSet,
1746 StringRef Arch, const Multilib::flags_list &Flags,
1747 llvm::SmallVectorImpl<Multilib> &SelectedMultilibs) {
1748 // Try to find the perfect matching multi-lib first.
1749 if (RISCVMultilibSet.select(D, Flags, SelectedMultilibs))
1750 return true;
1752 Multilib::flags_list NewFlags;
1753 std::vector<MultilibBuilder> NewMultilibs;
1755 llvm::Expected<std::unique_ptr<llvm::RISCVISAInfo>> ParseResult =
1756 llvm::RISCVISAInfo::parseArchString(
1757 Arch, /*EnableExperimentalExtension=*/true,
1758 /*ExperimentalExtensionVersionCheck=*/false);
1759 // Ignore any error here, we assume it will be handled in another place.
1760 if (llvm::errorToBool(ParseResult.takeError()))
1761 return false;
1763 auto &ISAInfo = *ParseResult;
1765 addMultilibFlag(ISAInfo->getXLen() == 32, "-m32", NewFlags);
1766 addMultilibFlag(ISAInfo->getXLen() == 64, "-m64", NewFlags);
1768 // Collect all flags except march=*
1769 for (StringRef Flag : Flags) {
1770 if (Flag.starts_with("!march=") || Flag.starts_with("-march="))
1771 continue;
1773 NewFlags.push_back(Flag.str());
1776 llvm::StringSet<> AllArchExts;
1777 // Reconstruct multi-lib list, and break march option into separated
1778 // extension. e.g. march=rv32im -> +i +m
1779 for (const auto &M : RISCVMultilibSet) {
1780 bool Skip = false;
1782 MultilibBuilder NewMultilib =
1783 MultilibBuilder(M.gccSuffix(), M.osSuffix(), M.includeSuffix());
1784 for (StringRef Flag : M.flags()) {
1785 // Add back all flags except -march.
1786 if (!Flag.consume_front("-march=")) {
1787 NewMultilib.flag(Flag);
1788 continue;
1791 // Break down -march into individual extension.
1792 llvm::Expected<std::unique_ptr<llvm::RISCVISAInfo>> MLConfigParseResult =
1793 llvm::RISCVISAInfo::parseArchString(
1794 Flag, /*EnableExperimentalExtension=*/true,
1795 /*ExperimentalExtensionVersionCheck=*/false);
1796 // Ignore any error here, we assume it will handled in another place.
1797 if (llvm::errorToBool(MLConfigParseResult.takeError())) {
1798 // We might get a parsing error if rv32e in the list, we could just skip
1799 // that and process the rest of multi-lib configs.
1800 Skip = true;
1801 continue;
1803 auto &MLConfigISAInfo = *MLConfigParseResult;
1805 for (auto &MLConfigArchExt : MLConfigISAInfo->getExtensions()) {
1806 auto ExtName = MLConfigArchExt.first;
1807 NewMultilib.flag(Twine("-", ExtName).str());
1809 if (AllArchExts.insert(ExtName).second) {
1810 addMultilibFlag(ISAInfo->hasExtension(ExtName),
1811 Twine("-", ExtName).str(), NewFlags);
1815 // Check the XLEN explicitly.
1816 if (MLConfigISAInfo->getXLen() == 32) {
1817 NewMultilib.flag("-m32");
1818 NewMultilib.flag("-m64", /*Disallow*/ true);
1819 } else {
1820 NewMultilib.flag("-m32", /*Disallow*/ true);
1821 NewMultilib.flag("-m64");
1824 // Atomic extension must be explicitly checked, soft and hard atomic
1825 // operation never co-work correctly.
1826 if (!MLConfigISAInfo->hasExtension("a"))
1827 NewMultilib.flag("-a", /*Disallow*/ true);
1830 if (Skip)
1831 continue;
1833 NewMultilibs.emplace_back(NewMultilib);
1836 // Build an internal used only multi-lib list, used for checking any
1837 // compatible multi-lib.
1838 MultilibSet NewRISCVMultilibs =
1839 MultilibSetBuilder().Either(NewMultilibs).makeMultilibSet();
1841 if (NewRISCVMultilibs.select(D, NewFlags, SelectedMultilibs))
1842 for (const Multilib &NewSelectedM : SelectedMultilibs)
1843 for (const auto &M : RISCVMultilibSet)
1844 // Look up the corresponding multi-lib entry in original multi-lib set.
1845 if (M.gccSuffix() == NewSelectedM.gccSuffix())
1846 return true;
1848 return false;
1851 static void findRISCVBareMetalMultilibs(const Driver &D,
1852 const llvm::Triple &TargetTriple,
1853 StringRef Path, const ArgList &Args,
1854 DetectedMultilibs &Result) {
1855 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1856 struct RiscvMultilib {
1857 StringRef march;
1858 StringRef mabi;
1860 // currently only support the set of multilibs like riscv-gnu-toolchain does.
1861 // TODO: support MULTILIB_REUSE
1862 constexpr RiscvMultilib RISCVMultilibSet[] = {
1863 {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
1864 {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
1865 {"rv64imafdc", "lp64d"}};
1867 std::vector<MultilibBuilder> Ms;
1868 for (auto Element : RISCVMultilibSet) {
1869 // multilib path rule is ${march}/${mabi}
1870 Ms.emplace_back(
1871 MultilibBuilder(
1872 (Twine(Element.march) + "/" + Twine(Element.mabi)).str())
1873 .flag(Twine("-march=", Element.march).str())
1874 .flag(Twine("-mabi=", Element.mabi).str()));
1876 MultilibSet RISCVMultilibs =
1877 MultilibSetBuilder()
1878 .Either(Ms)
1879 .makeMultilibSet()
1880 .FilterOut(NonExistent)
1881 .setFilePathsCallback([](const Multilib &M) {
1882 return std::vector<std::string>(
1883 {M.gccSuffix(),
1884 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(),
1885 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()});
1888 Multilib::flags_list Flags;
1889 llvm::StringSet<> Added_ABIs;
1890 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1891 std::string MArch = tools::riscv::getRISCVArch(Args, TargetTriple);
1892 for (auto Element : RISCVMultilibSet) {
1893 addMultilibFlag(MArch == Element.march,
1894 Twine("-march=", Element.march).str().c_str(), Flags);
1895 if (!Added_ABIs.count(Element.mabi)) {
1896 Added_ABIs.insert(Element.mabi);
1897 addMultilibFlag(ABIName == Element.mabi,
1898 Twine("-mabi=", Element.mabi).str().c_str(), Flags);
1902 if (selectRISCVMultilib(D, RISCVMultilibs, MArch, Flags,
1903 Result.SelectedMultilibs))
1904 Result.Multilibs = RISCVMultilibs;
1907 static void findRISCVMultilibs(const Driver &D,
1908 const llvm::Triple &TargetTriple, StringRef Path,
1909 const ArgList &Args, DetectedMultilibs &Result) {
1910 if (TargetTriple.getOS() == llvm::Triple::UnknownOS)
1911 return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result);
1913 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
1914 MultilibBuilder Ilp32 =
1915 MultilibBuilder("lib32/ilp32").flag("-m32").flag("-mabi=ilp32");
1916 MultilibBuilder Ilp32f =
1917 MultilibBuilder("lib32/ilp32f").flag("-m32").flag("-mabi=ilp32f");
1918 MultilibBuilder Ilp32d =
1919 MultilibBuilder("lib32/ilp32d").flag("-m32").flag("-mabi=ilp32d");
1920 MultilibBuilder Lp64 =
1921 MultilibBuilder("lib64/lp64").flag("-m64").flag("-mabi=lp64");
1922 MultilibBuilder Lp64f =
1923 MultilibBuilder("lib64/lp64f").flag("-m64").flag("-mabi=lp64f");
1924 MultilibBuilder Lp64d =
1925 MultilibBuilder("lib64/lp64d").flag("-m64").flag("-mabi=lp64d");
1926 MultilibSet RISCVMultilibs =
1927 MultilibSetBuilder()
1928 .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d})
1929 .makeMultilibSet()
1930 .FilterOut(NonExistent);
1932 Multilib::flags_list Flags;
1933 bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64;
1934 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple);
1936 addMultilibFlag(!IsRV64, "-m32", Flags);
1937 addMultilibFlag(IsRV64, "-m64", Flags);
1938 addMultilibFlag(ABIName == "ilp32", "-mabi=ilp32", Flags);
1939 addMultilibFlag(ABIName == "ilp32f", "-mabi=ilp32f", Flags);
1940 addMultilibFlag(ABIName == "ilp32d", "-mabi=ilp32d", Flags);
1941 addMultilibFlag(ABIName == "lp64", "-mabi=lp64", Flags);
1942 addMultilibFlag(ABIName == "lp64f", "-mabi=lp64f", Flags);
1943 addMultilibFlag(ABIName == "lp64d", "-mabi=lp64d", Flags);
1945 if (RISCVMultilibs.select(D, Flags, Result.SelectedMultilibs))
1946 Result.Multilibs = RISCVMultilibs;
1949 static bool findBiarchMultilibs(const Driver &D,
1950 const llvm::Triple &TargetTriple,
1951 StringRef Path, const ArgList &Args,
1952 bool NeedsBiarchSuffix,
1953 DetectedMultilibs &Result) {
1954 MultilibBuilder DefaultBuilder;
1956 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
1957 // in what would normally be GCCInstallPath and put the 64-bit
1958 // libs in a subdirectory named 64. The simple logic we follow is that
1959 // *if* there is a subdirectory of the right name with crtbegin.o in it,
1960 // we use that. If not, and if not a biarch triple alias, we look for
1961 // crtbegin.o without the subdirectory.
1963 StringRef Suff64 = "/64";
1964 // Solaris uses platform-specific suffixes instead of /64.
1965 if (TargetTriple.isOSSolaris()) {
1966 switch (TargetTriple.getArch()) {
1967 case llvm::Triple::x86:
1968 case llvm::Triple::x86_64:
1969 Suff64 = "/amd64";
1970 break;
1971 case llvm::Triple::sparc:
1972 case llvm::Triple::sparcv9:
1973 Suff64 = "/sparcv9";
1974 break;
1975 default:
1976 break;
1980 Multilib Alt64 = MultilibBuilder()
1981 .gccSuffix(Suff64)
1982 .includeSuffix(Suff64)
1983 .flag("-m32", /*Disallow=*/true)
1984 .flag("-m64")
1985 .flag("-mx32", /*Disallow=*/true)
1986 .makeMultilib();
1987 Multilib Alt32 = MultilibBuilder()
1988 .gccSuffix("/32")
1989 .includeSuffix("/32")
1990 .flag("-m32")
1991 .flag("-m64", /*Disallow=*/true)
1992 .flag("-mx32", /*Disallow=*/true)
1993 .makeMultilib();
1994 Multilib Altx32 = MultilibBuilder()
1995 .gccSuffix("/x32")
1996 .includeSuffix("/x32")
1997 .flag("-m32", /*Disallow=*/true)
1998 .flag("-m64", /*Disallow=*/true)
1999 .flag("-mx32")
2000 .makeMultilib();
2001 Multilib Alt32sparc = MultilibBuilder()
2002 .gccSuffix("/sparcv8plus")
2003 .includeSuffix("/sparcv8plus")
2004 .flag("-m32")
2005 .flag("-m64", /*Disallow=*/true)
2006 .makeMultilib();
2008 // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a.
2009 FilterNonExistent NonExistent(
2010 Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS());
2012 // Determine default multilib from: 32, 64, x32
2013 // Also handle cases such as 64 on 32, 32 on 64, etc.
2014 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2015 const bool IsX32 = TargetTriple.isX32();
2016 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2017 Want = WANT64;
2018 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32sparc))
2019 Want = WANT64;
2020 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2021 Want = WANT64;
2022 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2023 Want = WANT32;
2024 else if (TargetTriple.isArch64Bit() && !NonExistent(Alt32sparc))
2025 Want = WANT64;
2026 else {
2027 if (TargetTriple.isArch32Bit())
2028 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2029 else if (IsX32)
2030 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2031 else
2032 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2035 if (Want == WANT32)
2036 DefaultBuilder.flag("-m32")
2037 .flag("-m64", /*Disallow=*/true)
2038 .flag("-mx32", /*Disallow=*/true);
2039 else if (Want == WANT64)
2040 DefaultBuilder.flag("-m32", /*Disallow=*/true)
2041 .flag("-m64")
2042 .flag("-mx32", /*Disallow=*/true);
2043 else if (Want == WANTX32)
2044 DefaultBuilder.flag("-m32", /*Disallow=*/true)
2045 .flag("-m64", /*Disallow=*/true)
2046 .flag("-mx32");
2047 else
2048 return false;
2050 Multilib Default = DefaultBuilder.makeMultilib();
2052 Result.Multilibs.push_back(Default);
2053 Result.Multilibs.push_back(Alt64);
2054 Result.Multilibs.push_back(Alt32);
2055 Result.Multilibs.push_back(Altx32);
2056 Result.Multilibs.push_back(Alt32sparc);
2058 Result.Multilibs.FilterOut(NonExistent);
2060 Multilib::flags_list Flags;
2061 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "-m64", Flags);
2062 addMultilibFlag(TargetTriple.isArch32Bit(), "-m32", Flags);
2063 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "-mx32", Flags);
2065 if (!Result.Multilibs.select(D, Flags, Result.SelectedMultilibs))
2066 return false;
2068 if (Result.SelectedMultilibs.back() == Alt64 ||
2069 Result.SelectedMultilibs.back() == Alt32 ||
2070 Result.SelectedMultilibs.back() == Altx32 ||
2071 Result.SelectedMultilibs.back() == Alt32sparc)
2072 Result.BiarchSibling = Default;
2074 return true;
2077 /// Generic_GCC - A tool chain using the 'gcc' command to perform
2078 /// all subcommands; this relies on gcc translating the majority of
2079 /// command line options.
2081 /// Less-than for GCCVersion, implementing a Strict Weak Ordering.
2082 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
2083 int RHSPatch,
2084 StringRef RHSPatchSuffix) const {
2085 if (Major != RHSMajor)
2086 return Major < RHSMajor;
2087 if (Minor != RHSMinor) {
2088 // Note that versions without a specified minor sort higher than those with
2089 // a minor.
2090 if (RHSMinor == -1)
2091 return true;
2092 if (Minor == -1)
2093 return false;
2094 return Minor < RHSMinor;
2096 if (Patch != RHSPatch) {
2097 // Note that versions without a specified patch sort higher than those with
2098 // a patch.
2099 if (RHSPatch == -1)
2100 return true;
2101 if (Patch == -1)
2102 return false;
2104 // Otherwise just sort on the patch itself.
2105 return Patch < RHSPatch;
2107 if (PatchSuffix != RHSPatchSuffix) {
2108 // Sort empty suffixes higher.
2109 if (RHSPatchSuffix.empty())
2110 return true;
2111 if (PatchSuffix.empty())
2112 return false;
2114 // Provide a lexicographic sort to make this a total ordering.
2115 return PatchSuffix < RHSPatchSuffix;
2118 // The versions are equal.
2119 return false;
2122 /// Parse a GCCVersion object out of a string of text.
2124 /// This is the primary means of forming GCCVersion objects.
2125 /*static*/
2126 Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) {
2127 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2128 std::pair<StringRef, StringRef> First = VersionText.split('.');
2129 std::pair<StringRef, StringRef> Second = First.second.split('.');
2131 StringRef MajorStr = First.first;
2132 StringRef MinorStr = Second.first;
2133 StringRef PatchStr = Second.second;
2135 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
2137 // Parse version number strings such as:
2138 // 5
2139 // 4.4
2140 // 4.4-patched
2141 // 4.4.0
2142 // 4.4.x
2143 // 4.4.2-rc4
2144 // 4.4.x-patched
2145 // 10-win32
2146 // Split on '.', handle 1, 2 or 3 such segments. Each segment must contain
2147 // purely a number, except for the last one, where a non-number suffix
2148 // is stored in PatchSuffix. The third segment is allowed to not contain
2149 // a number at all.
2151 auto TryParseLastNumber = [&](StringRef Segment, int &Number,
2152 std::string &OutStr) -> bool {
2153 // Look for a number prefix and parse that, and split out any trailing
2154 // string into GoodVersion.PatchSuffix.
2156 if (size_t EndNumber = Segment.find_first_not_of("0123456789")) {
2157 StringRef NumberStr = Segment.slice(0, EndNumber);
2158 if (NumberStr.getAsInteger(10, Number) || Number < 0)
2159 return false;
2160 OutStr = NumberStr;
2161 GoodVersion.PatchSuffix = Segment.substr(EndNumber);
2162 return true;
2164 return false;
2166 auto TryParseNumber = [](StringRef Segment, int &Number) -> bool {
2167 if (Segment.getAsInteger(10, Number) || Number < 0)
2168 return false;
2169 return true;
2172 if (MinorStr.empty()) {
2173 // If no minor string, major is the last segment
2174 if (!TryParseLastNumber(MajorStr, GoodVersion.Major, GoodVersion.MajorStr))
2175 return BadVersion;
2176 return GoodVersion;
2179 if (!TryParseNumber(MajorStr, GoodVersion.Major))
2180 return BadVersion;
2181 GoodVersion.MajorStr = MajorStr;
2183 if (PatchStr.empty()) {
2184 // If no patch string, minor is the last segment
2185 if (!TryParseLastNumber(MinorStr, GoodVersion.Minor, GoodVersion.MinorStr))
2186 return BadVersion;
2187 return GoodVersion;
2190 if (!TryParseNumber(MinorStr, GoodVersion.Minor))
2191 return BadVersion;
2192 GoodVersion.MinorStr = MinorStr;
2194 // For the last segment, tolerate a missing number.
2195 std::string DummyStr;
2196 TryParseLastNumber(PatchStr, GoodVersion.Patch, DummyStr);
2197 return GoodVersion;
2200 static llvm::StringRef getGCCToolchainDir(const ArgList &Args,
2201 llvm::StringRef SysRoot) {
2202 const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain);
2203 if (A)
2204 return A->getValue();
2206 // If we have a SysRoot, ignore GCC_INSTALL_PREFIX.
2207 // GCC_INSTALL_PREFIX specifies the gcc installation for the default
2208 // sysroot and is likely not valid with a different sysroot.
2209 if (!SysRoot.empty())
2210 return "";
2212 return GCC_INSTALL_PREFIX;
2215 /// Initialize a GCCInstallationDetector from the driver.
2217 /// This performs all of the autodetection and sets up the various paths.
2218 /// Once constructed, a GCCInstallationDetector is essentially immutable.
2220 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
2221 /// should instead pull the target out of the driver. This is currently
2222 /// necessary because the driver doesn't store the final version of the target
2223 /// triple.
2224 void Generic_GCC::GCCInstallationDetector::init(
2225 const llvm::Triple &TargetTriple, const ArgList &Args) {
2226 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
2227 ? TargetTriple.get64BitArchVariant()
2228 : TargetTriple.get32BitArchVariant();
2229 // The library directories which may contain GCC installations.
2230 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
2231 // The compatible GCC triples for this particular architecture.
2232 SmallVector<StringRef, 16> CandidateTripleAliases;
2233 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
2234 // Add some triples that we want to check first.
2235 CandidateTripleAliases.push_back(TargetTriple.str());
2236 std::string TripleNoVendor, BiarchTripleNoVendor;
2237 if (TargetTriple.getVendor() == llvm::Triple::UnknownVendor) {
2238 StringRef OSEnv = TargetTriple.getOSAndEnvironmentName();
2239 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32)
2240 OSEnv = "linux-gnu";
2241 TripleNoVendor = (TargetTriple.getArchName().str() + '-' + OSEnv).str();
2242 CandidateTripleAliases.push_back(TripleNoVendor);
2243 if (BiarchVariantTriple.getArch() != llvm::Triple::UnknownArch) {
2244 BiarchTripleNoVendor =
2245 (BiarchVariantTriple.getArchName().str() + '-' + OSEnv).str();
2246 CandidateBiarchTripleAliases.push_back(BiarchTripleNoVendor);
2250 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
2251 CandidateTripleAliases, CandidateBiarchLibDirs,
2252 CandidateBiarchTripleAliases);
2254 // If --gcc-install-dir= is specified, skip filesystem detection.
2255 if (const Arg *A =
2256 Args.getLastArg(clang::driver::options::OPT_gcc_install_dir_EQ);
2257 A && A->getValue()[0]) {
2258 StringRef InstallDir = A->getValue();
2259 if (!ScanGCCForMultilibs(TargetTriple, Args, InstallDir, false)) {
2260 D.Diag(diag::err_drv_invalid_gcc_install_dir) << InstallDir;
2261 } else {
2262 (void)InstallDir.consume_back("/");
2263 StringRef VersionText = llvm::sys::path::filename(InstallDir);
2264 StringRef TripleText =
2265 llvm::sys::path::filename(llvm::sys::path::parent_path(InstallDir));
2267 Version = GCCVersion::Parse(VersionText);
2268 GCCTriple.setTriple(TripleText);
2269 GCCInstallPath = std::string(InstallDir);
2270 GCCParentLibPath = GCCInstallPath + "/../../..";
2271 IsValid = true;
2273 return;
2276 // If --gcc-triple is specified use this instead of trying to
2277 // auto-detect a triple.
2278 if (const Arg *A =
2279 Args.getLastArg(clang::driver::options::OPT_gcc_triple_EQ)) {
2280 StringRef GCCTriple = A->getValue();
2281 CandidateTripleAliases.clear();
2282 CandidateTripleAliases.push_back(GCCTriple);
2285 // Compute the set of prefixes for our search.
2286 SmallVector<std::string, 8> Prefixes;
2287 StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot);
2288 if (GCCToolchainDir != "") {
2289 if (GCCToolchainDir.back() == '/')
2290 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
2292 Prefixes.push_back(std::string(GCCToolchainDir));
2293 } else {
2294 // If we have a SysRoot, try that first.
2295 if (!D.SysRoot.empty()) {
2296 Prefixes.push_back(D.SysRoot);
2297 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2300 // Then look for gcc installed alongside clang.
2301 Prefixes.push_back(D.Dir + "/..");
2303 // Next, look for prefix(es) that correspond to distribution-supplied gcc
2304 // installations.
2305 if (D.SysRoot.empty()) {
2306 // Typically /usr.
2307 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot);
2310 // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided.
2311 // This avoids accidentally enforcing the system GCC version when using a
2312 // custom toolchain.
2313 SmallVector<StringRef, 16> GentooTestTriples;
2314 // Try to match an exact triple as target triple first.
2315 // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for
2316 // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu"
2317 // may pick the libraries for x86_64-pc-linux-gnu even when exact matching
2318 // triple x86_64-gentoo-linux-gnu is present.
2319 GentooTestTriples.push_back(TargetTriple.str());
2320 GentooTestTriples.append(CandidateTripleAliases.begin(),
2321 CandidateTripleAliases.end());
2322 if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples,
2323 CandidateBiarchTripleAliases))
2324 return;
2327 // Loop over the various components which exist and select the best GCC
2328 // installation available. GCC installs are ranked by version number.
2329 const GCCVersion VersionZero = GCCVersion::Parse("0.0.0");
2330 Version = VersionZero;
2331 for (const std::string &Prefix : Prefixes) {
2332 auto &VFS = D.getVFS();
2333 if (!VFS.exists(Prefix))
2334 continue;
2335 for (StringRef Suffix : CandidateLibDirs) {
2336 const std::string LibDir = concat(Prefix, Suffix);
2337 if (!VFS.exists(LibDir))
2338 continue;
2339 // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross.
2340 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2341 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2342 for (StringRef Candidate : CandidateTripleAliases)
2343 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false,
2344 GCCDirExists, GCCCrossDirExists);
2346 for (StringRef Suffix : CandidateBiarchLibDirs) {
2347 const std::string LibDir = Prefix + Suffix.str();
2348 if (!VFS.exists(LibDir))
2349 continue;
2350 bool GCCDirExists = VFS.exists(LibDir + "/gcc");
2351 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross");
2352 for (StringRef Candidate : CandidateBiarchTripleAliases)
2353 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true,
2354 GCCDirExists, GCCCrossDirExists);
2357 // Skip other prefixes once a GCC installation is found.
2358 if (Version > VersionZero)
2359 break;
2363 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
2364 for (const auto &InstallPath : CandidateGCCInstallPaths)
2365 OS << "Found candidate GCC installation: " << InstallPath << "\n";
2367 if (!GCCInstallPath.empty())
2368 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
2370 for (const auto &Multilib : Multilibs)
2371 OS << "Candidate multilib: " << Multilib << "\n";
2373 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
2374 OS << "Selected multilib: " << SelectedMultilib << "\n";
2377 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
2378 if (BiarchSibling) {
2379 M = *BiarchSibling;
2380 return true;
2382 return false;
2385 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
2386 const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes,
2387 StringRef SysRoot) {
2389 if (TargetTriple.isOSHaiku()) {
2390 Prefixes.push_back(concat(SysRoot, "/boot/system/develop/tools"));
2391 return;
2394 if (TargetTriple.isOSSolaris()) {
2395 // Solaris is a special case.
2396 // The GCC installation is under
2397 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/
2398 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
2399 // /usr/gcc/<version> as a prefix.
2401 SmallVector<std::pair<GCCVersion, std::string>, 8> SolarisPrefixes;
2402 std::string PrefixDir = concat(SysRoot, "/usr/gcc");
2403 std::error_code EC;
2404 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC),
2406 !EC && LI != LE; LI = LI.increment(EC)) {
2407 StringRef VersionText = llvm::sys::path::filename(LI->path());
2408 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2410 // Filter out obviously bad entries.
2411 if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1))
2412 continue;
2414 std::string CandidatePrefix = PrefixDir + "/" + VersionText.str();
2415 std::string CandidateLibPath = CandidatePrefix + "/lib/gcc";
2416 if (!D.getVFS().exists(CandidateLibPath))
2417 continue;
2419 SolarisPrefixes.emplace_back(
2420 std::make_pair(CandidateVersion, CandidatePrefix));
2422 // Sort in reverse order so GCCInstallationDetector::init picks the latest.
2423 std::sort(SolarisPrefixes.rbegin(), SolarisPrefixes.rend());
2424 for (auto p : SolarisPrefixes)
2425 Prefixes.emplace_back(p.second);
2426 return;
2429 // For Linux, if --sysroot is not specified, look for RHEL/CentOS devtoolsets
2430 // and gcc-toolsets.
2431 if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux &&
2432 D.getVFS().exists("/opt/rh")) {
2433 // TODO: We may want to remove this, since the functionality
2434 // can be achieved using config files.
2435 Prefixes.push_back("/opt/rh/gcc-toolset-12/root/usr");
2436 Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr");
2437 Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr");
2438 Prefixes.push_back("/opt/rh/devtoolset-12/root/usr");
2439 Prefixes.push_back("/opt/rh/devtoolset-11/root/usr");
2440 Prefixes.push_back("/opt/rh/devtoolset-10/root/usr");
2441 Prefixes.push_back("/opt/rh/devtoolset-9/root/usr");
2442 Prefixes.push_back("/opt/rh/devtoolset-8/root/usr");
2443 Prefixes.push_back("/opt/rh/devtoolset-7/root/usr");
2444 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr");
2445 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr");
2446 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr");
2447 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr");
2450 // Fall back to /usr which is used by most non-Solaris systems.
2451 Prefixes.push_back(concat(SysRoot, "/usr"));
2454 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
2455 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
2456 SmallVectorImpl<StringRef> &LibDirs,
2457 SmallVectorImpl<StringRef> &TripleAliases,
2458 SmallVectorImpl<StringRef> &BiarchLibDirs,
2459 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
2460 // Declare a bunch of static data sets that we'll select between below. These
2461 // are specifically designed to always refer to string literals to avoid any
2462 // lifetime or initialization issues.
2464 // The *Triples variables hard code some triples so that, for example,
2465 // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu.
2466 // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE
2467 // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The
2468 // lists should shrink over time. Please don't add more elements to *Triples.
2469 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
2470 static const char *const AArch64Triples[] = {
2471 "aarch64-none-linux-gnu", "aarch64-redhat-linux", "aarch64-suse-linux"};
2472 static const char *const AArch64beLibDirs[] = {"/lib"};
2473 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu"};
2475 static const char *const ARMLibDirs[] = {"/lib"};
2476 static const char *const ARMTriples[] = {"arm-linux-gnueabi"};
2477 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
2478 "armv7hl-redhat-linux-gnueabi",
2479 "armv6hl-suse-linux-gnueabi",
2480 "armv7hl-suse-linux-gnueabi"};
2481 static const char *const ARMebLibDirs[] = {"/lib"};
2482 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"};
2483 static const char *const ARMebHFTriples[] = {
2484 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
2486 static const char *const AVRLibDirs[] = {"/lib"};
2487 static const char *const AVRTriples[] = {"avr"};
2489 static const char *const CSKYLibDirs[] = {"/lib"};
2490 static const char *const CSKYTriples[] = {
2491 "csky-linux-gnuabiv2", "csky-linux-uclibcabiv2", "csky-elf-noneabiv2"};
2493 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
2494 static const char *const X86_64Triples[] = {
2495 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
2496 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
2497 "x86_64-redhat-linux", "x86_64-suse-linux",
2498 "x86_64-manbo-linux-gnu", "x86_64-slackware-linux",
2499 "x86_64-unknown-linux", "x86_64-amazon-linux"};
2500 static const char *const X32Triples[] = {"x86_64-linux-gnux32",
2501 "x86_64-pc-linux-gnux32"};
2502 static const char *const X32LibDirs[] = {"/libx32", "/lib"};
2503 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
2504 static const char *const X86Triples[] = {
2505 "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu",
2506 "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux",
2507 "i586-suse-linux", "i686-montavista-linux",
2510 static const char *const LoongArch64LibDirs[] = {"/lib64", "/lib"};
2511 static const char *const LoongArch64Triples[] = {
2512 "loongarch64-linux-gnu", "loongarch64-unknown-linux-gnu"};
2514 static const char *const M68kLibDirs[] = {"/lib"};
2515 static const char *const M68kTriples[] = {"m68k-unknown-linux-gnu",
2516 "m68k-suse-linux"};
2518 static const char *const MIPSLibDirs[] = {"/libo32", "/lib"};
2519 static const char *const MIPSTriples[] = {
2520 "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu",
2521 "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"};
2522 static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"};
2523 static const char *const MIPSELTriples[] = {"mipsel-linux-gnu",
2524 "mips-img-linux-gnu"};
2526 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
2527 static const char *const MIPS64Triples[] = {
2528 "mips-mti-linux-gnu", "mips-img-linux-gnu", "mips64-linux-gnuabi64",
2529 "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"};
2530 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
2531 static const char *const MIPS64ELTriples[] = {
2532 "mips-mti-linux-gnu", "mips-img-linux-gnu", "mips64el-linux-gnuabi64",
2533 "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"};
2535 static const char *const MIPSN32LibDirs[] = {"/lib32"};
2536 static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32",
2537 "mipsisa64r6-linux-gnuabin32"};
2538 static const char *const MIPSN32ELLibDirs[] = {"/lib32"};
2539 static const char *const MIPSN32ELTriples[] = {
2540 "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"};
2542 static const char *const MSP430LibDirs[] = {"/lib"};
2543 static const char *const MSP430Triples[] = {"msp430-elf"};
2545 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
2546 static const char *const PPCTriples[] = {
2547 "powerpc-unknown-linux-gnu",
2548 // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a
2549 // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux".
2550 "powerpc64-suse-linux", "powerpc-montavista-linuxspe"};
2551 static const char *const PPCLELibDirs[] = {"/lib32", "/lib"};
2552 static const char *const PPCLETriples[] = {"powerpcle-unknown-linux-gnu",
2553 "powerpcle-linux-musl"};
2555 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
2556 static const char *const PPC64Triples[] = {"powerpc64-unknown-linux-gnu",
2557 "powerpc64-suse-linux",
2558 "ppc64-redhat-linux"};
2559 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
2560 static const char *const PPC64LETriples[] = {
2561 "powerpc64le-unknown-linux-gnu", "powerpc64le-none-linux-gnu",
2562 "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
2564 static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"};
2565 static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu",
2566 "riscv32-unknown-elf"};
2567 static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"};
2568 static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu",
2569 "riscv64-unknown-elf"};
2571 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
2572 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
2573 "sparcv8-linux-gnu"};
2574 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
2575 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
2576 "sparcv9-linux-gnu"};
2578 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
2579 static const char *const SystemZTriples[] = {
2580 "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", "s390x-suse-linux",
2581 "s390x-redhat-linux"};
2583 using std::begin;
2584 using std::end;
2586 if (TargetTriple.isOSSolaris()) {
2587 static const char *const SolarisLibDirs[] = {"/lib"};
2588 static const char *const SolarisSparcV8Triples[] = {
2589 "sparc-sun-solaris2.11"};
2590 static const char *const SolarisSparcV9Triples[] = {
2591 "sparcv9-sun-solaris2.11"};
2592 static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11"};
2593 static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11"};
2594 LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2595 BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs));
2596 switch (TargetTriple.getArch()) {
2597 case llvm::Triple::x86:
2598 TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples));
2599 BiarchTripleAliases.append(begin(SolarisX86_64Triples),
2600 end(SolarisX86_64Triples));
2601 break;
2602 case llvm::Triple::x86_64:
2603 TripleAliases.append(begin(SolarisX86_64Triples),
2604 end(SolarisX86_64Triples));
2605 BiarchTripleAliases.append(begin(SolarisX86Triples),
2606 end(SolarisX86Triples));
2607 break;
2608 case llvm::Triple::sparc:
2609 TripleAliases.append(begin(SolarisSparcV8Triples),
2610 end(SolarisSparcV8Triples));
2611 BiarchTripleAliases.append(begin(SolarisSparcV9Triples),
2612 end(SolarisSparcV9Triples));
2613 break;
2614 case llvm::Triple::sparcv9:
2615 TripleAliases.append(begin(SolarisSparcV9Triples),
2616 end(SolarisSparcV9Triples));
2617 BiarchTripleAliases.append(begin(SolarisSparcV8Triples),
2618 end(SolarisSparcV8Triples));
2619 break;
2620 default:
2621 break;
2623 return;
2626 // Android targets should not use GNU/Linux tools or libraries.
2627 if (TargetTriple.isAndroid()) {
2628 static const char *const AArch64AndroidTriples[] = {
2629 "aarch64-linux-android"};
2630 static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"};
2631 static const char *const X86AndroidTriples[] = {"i686-linux-android"};
2632 static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"};
2634 switch (TargetTriple.getArch()) {
2635 case llvm::Triple::aarch64:
2636 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2637 TripleAliases.append(begin(AArch64AndroidTriples),
2638 end(AArch64AndroidTriples));
2639 break;
2640 case llvm::Triple::arm:
2641 case llvm::Triple::thumb:
2642 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2643 TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples));
2644 break;
2645 case llvm::Triple::x86_64:
2646 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2647 TripleAliases.append(begin(X86_64AndroidTriples),
2648 end(X86_64AndroidTriples));
2649 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2650 BiarchTripleAliases.append(begin(X86AndroidTriples),
2651 end(X86AndroidTriples));
2652 break;
2653 case llvm::Triple::x86:
2654 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2655 TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples));
2656 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2657 BiarchTripleAliases.append(begin(X86_64AndroidTriples),
2658 end(X86_64AndroidTriples));
2659 break;
2660 default:
2661 break;
2664 return;
2667 if (TargetTriple.isOSHurd()) {
2668 switch (TargetTriple.getArch()) {
2669 case llvm::Triple::x86_64:
2670 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2671 TripleAliases.push_back("x86_64-gnu");
2672 break;
2673 case llvm::Triple::x86:
2674 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2675 TripleAliases.push_back("i686-gnu");
2676 break;
2677 default:
2678 break;
2681 return;
2684 switch (TargetTriple.getArch()) {
2685 case llvm::Triple::aarch64:
2686 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2687 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2688 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
2689 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
2690 break;
2691 case llvm::Triple::aarch64_be:
2692 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2693 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2694 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
2695 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
2696 break;
2697 case llvm::Triple::arm:
2698 case llvm::Triple::thumb:
2699 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
2700 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF ||
2701 TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHFT64 ||
2702 TargetTriple.getEnvironment() == llvm::Triple::MuslEABIHF ||
2703 TargetTriple.getEnvironment() == llvm::Triple::EABIHF) {
2704 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
2705 } else {
2706 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
2708 break;
2709 case llvm::Triple::armeb:
2710 case llvm::Triple::thumbeb:
2711 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
2712 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF ||
2713 TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHFT64 ||
2714 TargetTriple.getEnvironment() == llvm::Triple::MuslEABIHF ||
2715 TargetTriple.getEnvironment() == llvm::Triple::EABIHF) {
2716 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
2717 } else {
2718 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
2720 break;
2721 case llvm::Triple::avr:
2722 LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
2723 TripleAliases.append(begin(AVRTriples), end(AVRTriples));
2724 break;
2725 case llvm::Triple::csky:
2726 LibDirs.append(begin(CSKYLibDirs), end(CSKYLibDirs));
2727 TripleAliases.append(begin(CSKYTriples), end(CSKYTriples));
2728 break;
2729 case llvm::Triple::x86_64:
2730 if (TargetTriple.isX32()) {
2731 LibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2732 TripleAliases.append(begin(X32Triples), end(X32Triples));
2733 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2734 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2735 } else {
2736 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2737 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2738 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2739 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2741 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2742 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
2743 break;
2744 case llvm::Triple::x86:
2745 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
2746 // MCU toolchain is 32 bit only and its triple alias is TargetTriple
2747 // itself, which will be appended below.
2748 if (!TargetTriple.isOSIAMCU()) {
2749 TripleAliases.append(begin(X86Triples), end(X86Triples));
2750 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
2751 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
2752 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
2753 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples));
2755 break;
2756 // TODO: Handle loongarch32.
2757 case llvm::Triple::loongarch64:
2758 LibDirs.append(begin(LoongArch64LibDirs), end(LoongArch64LibDirs));
2759 TripleAliases.append(begin(LoongArch64Triples), end(LoongArch64Triples));
2760 break;
2761 case llvm::Triple::m68k:
2762 LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs));
2763 TripleAliases.append(begin(M68kTriples), end(M68kTriples));
2764 break;
2765 case llvm::Triple::mips:
2766 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2767 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2768 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2769 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2770 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2771 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2772 break;
2773 case llvm::Triple::mipsel:
2774 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2775 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2776 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2777 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2778 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2779 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2780 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2781 break;
2782 case llvm::Triple::mips64:
2783 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
2784 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
2785 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
2786 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2787 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs));
2788 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples));
2789 break;
2790 case llvm::Triple::mips64el:
2791 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
2792 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
2793 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
2794 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
2795 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs));
2796 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples));
2797 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
2798 break;
2799 case llvm::Triple::msp430:
2800 LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs));
2801 TripleAliases.append(begin(MSP430Triples), end(MSP430Triples));
2802 break;
2803 case llvm::Triple::ppc:
2804 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2805 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
2806 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2807 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2808 break;
2809 case llvm::Triple::ppcle:
2810 LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2811 TripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2812 BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2813 BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2814 break;
2815 case llvm::Triple::ppc64:
2816 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
2817 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
2818 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
2819 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
2820 break;
2821 case llvm::Triple::ppc64le:
2822 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
2823 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
2824 BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs));
2825 BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples));
2826 break;
2827 case llvm::Triple::riscv32:
2828 LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2829 TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2830 BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2831 BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2832 break;
2833 case llvm::Triple::riscv64:
2834 LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs));
2835 TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples));
2836 BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs));
2837 BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples));
2838 break;
2839 case llvm::Triple::sparc:
2840 case llvm::Triple::sparcel:
2841 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2842 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2843 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2844 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2845 break;
2846 case llvm::Triple::sparcv9:
2847 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
2848 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
2849 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
2850 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
2851 break;
2852 case llvm::Triple::systemz:
2853 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
2854 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
2855 break;
2856 default:
2857 // By default, just rely on the standard lib directories and the original
2858 // triple.
2859 break;
2862 // Also include the multiarch variant if it's different.
2863 if (TargetTriple.str() != BiarchTriple.str())
2864 BiarchTripleAliases.push_back(BiarchTriple.str());
2867 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs(
2868 const llvm::Triple &TargetTriple, const ArgList &Args,
2869 StringRef Path, bool NeedsBiarchSuffix) {
2870 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2871 DetectedMultilibs Detected;
2873 // Android standalone toolchain could have multilibs for ARM and Thumb.
2874 // Debian mips multilibs behave more like the rest of the biarch ones,
2875 // so handle them there
2876 if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) {
2877 // It should also work without multilibs in a simplified toolchain.
2878 findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected);
2879 } else if (TargetTriple.isCSKY()) {
2880 findCSKYMultilibs(D, TargetTriple, Path, Args, Detected);
2881 } else if (TargetTriple.isMIPS()) {
2882 if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected))
2883 return false;
2884 } else if (TargetTriple.isRISCV()) {
2885 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
2886 } else if (isMSP430(TargetArch)) {
2887 findMSP430Multilibs(D, TargetTriple, Path, Args, Detected);
2888 } else if (TargetArch == llvm::Triple::avr) {
2889 // AVR has no multilibs.
2890 } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
2891 NeedsBiarchSuffix, Detected)) {
2892 return false;
2895 Multilibs = Detected.Multilibs;
2896 SelectedMultilib = Detected.SelectedMultilibs.empty()
2897 ? Multilib()
2898 : Detected.SelectedMultilibs.back();
2899 BiarchSibling = Detected.BiarchSibling;
2901 return true;
2904 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2905 const llvm::Triple &TargetTriple, const ArgList &Args,
2906 const std::string &LibDir, StringRef CandidateTriple,
2907 bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) {
2908 // Locations relative to the system lib directory where GCC's triple-specific
2909 // directories might reside.
2910 struct GCCLibSuffix {
2911 // Path from system lib directory to GCC triple-specific directory.
2912 std::string LibSuffix;
2913 // Path from GCC triple-specific directory back to system lib directory.
2914 // This is one '..' component per component in LibSuffix.
2915 StringRef ReversePath;
2916 // Whether this library suffix is relevant for the triple.
2917 bool Active;
2918 } Suffixes[] = {
2919 // This is the normal place.
2920 {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists},
2922 // Debian puts cross-compilers in gcc-cross.
2923 {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists},
2925 // The Freescale PPC SDK has the gcc libraries in
2926 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do
2927 // this on Freescale triples, though, since some systems put a *lot* of
2928 // files in that location, not just GCC installation data.
2929 {CandidateTriple.str(), "..",
2930 TargetTriple.getVendor() == llvm::Triple::Freescale ||
2931 TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}};
2933 for (auto &Suffix : Suffixes) {
2934 if (!Suffix.Active)
2935 continue;
2937 StringRef LibSuffix = Suffix.LibSuffix;
2938 std::error_code EC;
2939 for (llvm::vfs::directory_iterator
2940 LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC),
2942 !EC && LI != LE; LI = LI.increment(EC)) {
2943 StringRef VersionText = llvm::sys::path::filename(LI->path());
2944 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2945 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2946 if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second)
2947 continue; // Saw this path before; no need to look at it again.
2948 if (CandidateVersion.isOlderThan(4, 1, 1))
2949 continue;
2950 if (CandidateVersion <= Version)
2951 continue;
2953 if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(),
2954 NeedsBiarchSuffix))
2955 continue;
2957 Version = CandidateVersion;
2958 GCCTriple.setTriple(CandidateTriple);
2959 // FIXME: We hack together the directory name here instead of
2960 // using LI to ensure stable path separators across Windows and
2961 // Linux.
2962 GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str();
2963 GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str();
2964 IsValid = true;
2969 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
2970 const llvm::Triple &TargetTriple, const ArgList &Args,
2971 const SmallVectorImpl<StringRef> &CandidateTriples,
2972 const SmallVectorImpl<StringRef> &CandidateBiarchTriples) {
2973 if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir)))
2974 return false;
2976 for (StringRef CandidateTriple : CandidateTriples) {
2977 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple))
2978 return true;
2981 for (StringRef CandidateTriple : CandidateBiarchTriples) {
2982 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true))
2983 return true;
2985 return false;
2988 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
2989 const llvm::Triple &TargetTriple, const ArgList &Args,
2990 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
2991 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
2992 D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir,
2993 "/config-" + CandidateTriple.str()));
2994 if (File) {
2995 SmallVector<StringRef, 2> Lines;
2996 File.get()->getBuffer().split(Lines, "\n");
2997 for (StringRef Line : Lines) {
2998 Line = Line.trim();
2999 // CURRENT=triple-version
3000 if (!Line.consume_front("CURRENT="))
3001 continue;
3002 // Process the config file pointed to by CURRENT.
3003 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile =
3004 D.getVFS().getBufferForFile(
3005 concat(D.SysRoot, GentooConfigDir, "/" + Line));
3006 std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-');
3007 // List of paths to scan for libraries.
3008 SmallVector<StringRef, 4> GentooScanPaths;
3009 // Scan the Config file to find installed GCC libraries path.
3010 // Typical content of the GCC config file:
3011 // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/
3012 // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32"
3013 // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man"
3014 // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info"
3015 // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4"
3016 // We are looking for the paths listed in LDPATH=... .
3017 if (ConfigFile) {
3018 SmallVector<StringRef, 2> ConfigLines;
3019 ConfigFile.get()->getBuffer().split(ConfigLines, "\n");
3020 for (StringRef ConfLine : ConfigLines) {
3021 ConfLine = ConfLine.trim();
3022 if (ConfLine.consume_front("LDPATH=")) {
3023 // Drop '"' from front and back if present.
3024 ConfLine.consume_back("\"");
3025 ConfLine.consume_front("\"");
3026 // Get all paths sperated by ':'
3027 ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false);
3031 // Test the path based on the version in /etc/env.d/gcc/config-{tuple}.
3032 std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/"
3033 + ActiveVersion.second.str();
3034 GentooScanPaths.push_back(StringRef(basePath));
3036 // Scan all paths for GCC libraries.
3037 for (const auto &GentooScanPath : GentooScanPaths) {
3038 std::string GentooPath = concat(D.SysRoot, GentooScanPath);
3039 if (D.getVFS().exists(GentooPath + "/crtbegin.o")) {
3040 if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath,
3041 NeedsBiarchSuffix))
3042 continue;
3044 Version = GCCVersion::Parse(ActiveVersion.second);
3045 GCCInstallPath = GentooPath;
3046 GCCParentLibPath = GentooPath + std::string("/../../..");
3047 GCCTriple.setTriple(ActiveVersion.first);
3048 IsValid = true;
3049 return true;
3055 return false;
3058 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
3059 const ArgList &Args)
3060 : ToolChain(D, Triple, Args), GCCInstallation(D),
3061 CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) {
3062 getProgramPaths().push_back(getDriver().Dir);
3065 Generic_GCC::~Generic_GCC() {}
3067 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
3068 switch (AC) {
3069 case Action::PreprocessJobClass:
3070 if (!Preprocess)
3071 Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this));
3072 return Preprocess.get();
3073 case Action::CompileJobClass:
3074 if (!Compile)
3075 Compile.reset(new tools::gcc::Compiler(*this));
3076 return Compile.get();
3077 default:
3078 return ToolChain::getTool(AC);
3082 Tool *Generic_GCC::buildAssembler() const {
3083 return new tools::gnutools::Assembler(*this);
3086 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
3088 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
3089 // Print the information about how we detected the GCC installation.
3090 GCCInstallation.print(OS);
3091 CudaInstallation->print(OS);
3092 RocmInstallation->print(OS);
3095 ToolChain::UnwindTableLevel
3096 Generic_GCC::getDefaultUnwindTableLevel(const ArgList &Args) const {
3097 switch (getArch()) {
3098 case llvm::Triple::aarch64:
3099 case llvm::Triple::aarch64_be:
3100 case llvm::Triple::ppc:
3101 case llvm::Triple::ppcle:
3102 case llvm::Triple::ppc64:
3103 case llvm::Triple::ppc64le:
3104 case llvm::Triple::riscv32:
3105 case llvm::Triple::riscv64:
3106 case llvm::Triple::x86:
3107 case llvm::Triple::x86_64:
3108 return UnwindTableLevel::Asynchronous;
3109 default:
3110 return UnwindTableLevel::None;
3114 bool Generic_GCC::isPICDefault() const {
3115 switch (getArch()) {
3116 case llvm::Triple::x86_64:
3117 return getTriple().isOSWindows();
3118 case llvm::Triple::mips64:
3119 case llvm::Triple::mips64el:
3120 return true;
3121 default:
3122 return false;
3126 bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const {
3127 return false;
3130 bool Generic_GCC::isPICDefaultForced() const {
3131 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
3134 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
3135 switch (getTriple().getArch()) {
3136 case llvm::Triple::nvptx:
3137 case llvm::Triple::nvptx64:
3138 case llvm::Triple::xcore:
3139 return false;
3140 default:
3141 return true;
3145 void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) {
3146 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3147 // least) put various tools in a triple-prefixed directory off of the parent
3148 // of the GCC installation. We use the GCC triple here to ensure that we end
3149 // up with tools that support the same amount of cross compiling as the
3150 // detected GCC installation. For example, if we find a GCC installation
3151 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3152 // used to target i386.
3153 if (GCCInstallation.isValid()) {
3154 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3155 GCCInstallation.getTriple().str() + "/bin")
3156 .str());
3160 void Generic_GCC::AddMultilibPaths(const Driver &D,
3161 const std::string &SysRoot,
3162 const std::string &OSLibDir,
3163 const std::string &MultiarchTriple,
3164 path_list &Paths) {
3165 // Add the multilib suffixed paths where they are available.
3166 if (GCCInstallation.isValid()) {
3167 assert(!SelectedMultilibs.empty());
3168 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3169 const std::string &LibPath =
3170 std::string(GCCInstallation.getParentLibPath());
3172 // Sourcery CodeBench MIPS toolchain holds some libraries under
3173 // a biarch-like suffix of the GCC installation.
3174 if (const auto &PathsCallback = Multilibs.filePathsCallback())
3175 for (const auto &Path : PathsCallback(SelectedMultilibs.back()))
3176 addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths);
3178 // Add lib/gcc/$triple/$version, with an optional /multilib suffix.
3179 addPathIfExists(D,
3180 GCCInstallation.getInstallPath() +
3181 SelectedMultilibs.back().gccSuffix(),
3182 Paths);
3184 // Add lib/gcc/$triple/$libdir
3185 // For GCC built with --enable-version-specific-runtime-libs.
3186 addPathIfExists(D, GCCInstallation.getInstallPath() + "/../" + OSLibDir,
3187 Paths);
3189 // GCC cross compiling toolchains will install target libraries which ship
3190 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3191 // any part of the GCC installation in
3192 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3193 // debatable, but is the reality today. We need to search this tree even
3194 // when we have a sysroot somewhere else. It is the responsibility of
3195 // whomever is doing the cross build targeting a sysroot using a GCC
3196 // installation that is *not* within the system root to ensure two things:
3198 // 1) Any DSOs that are linked in from this tree or from the install path
3199 // above must be present on the system root and found via an
3200 // appropriate rpath.
3201 // 2) There must not be libraries installed into
3202 // <prefix>/<triple>/<libdir> unless they should be preferred over
3203 // those within the system root.
3205 // Note that this matches the GCC behavior. See the below comment for where
3206 // Clang diverges from GCC's behavior.
3207 addPathIfExists(D,
3208 LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir +
3209 SelectedMultilibs.back().osSuffix(),
3210 Paths);
3212 // If the GCC installation we found is inside of the sysroot, we want to
3213 // prefer libraries installed in the parent prefix of the GCC installation.
3214 // It is important to *not* use these paths when the GCC installation is
3215 // outside of the system root as that can pick up unintended libraries.
3216 // This usually happens when there is an external cross compiler on the
3217 // host system, and a more minimal sysroot available that is the target of
3218 // the cross. Note that GCC does include some of these directories in some
3219 // configurations but this seems somewhere between questionable and simply
3220 // a bug.
3221 if (StringRef(LibPath).starts_with(SysRoot))
3222 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3226 void Generic_GCC::AddMultiarchPaths(const Driver &D,
3227 const std::string &SysRoot,
3228 const std::string &OSLibDir,
3229 path_list &Paths) {
3230 if (GCCInstallation.isValid()) {
3231 const std::string &LibPath =
3232 std::string(GCCInstallation.getParentLibPath());
3233 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3234 const Multilib &Multilib = GCCInstallation.getMultilib();
3235 addPathIfExists(
3236 D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(),
3237 Paths);
3241 void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs,
3242 ArgStringList &CC1Args) const {
3243 // Add include directories specific to the selected multilib set and multilib.
3244 if (!GCCInstallation.isValid())
3245 return;
3246 // gcc TOOL_INCLUDE_DIR.
3247 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3248 std::string LibPath(GCCInstallation.getParentLibPath());
3249 addSystemInclude(DriverArgs, CC1Args,
3250 Twine(LibPath) + "/../" + GCCTriple.str() + "/include");
3252 const auto &Callback = Multilibs.includeDirsCallback();
3253 if (Callback) {
3254 for (const auto &Path : Callback(GCCInstallation.getMultilib()))
3255 addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
3256 GCCInstallation.getInstallPath() + Path);
3260 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3261 ArgStringList &CC1Args) const {
3262 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
3263 options::OPT_nostdlibinc))
3264 return;
3266 switch (GetCXXStdlibType(DriverArgs)) {
3267 case ToolChain::CST_Libcxx:
3268 addLibCxxIncludePaths(DriverArgs, CC1Args);
3269 break;
3271 case ToolChain::CST_Libstdcxx:
3272 addLibStdCxxIncludePaths(DriverArgs, CC1Args);
3273 break;
3277 void
3278 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3279 llvm::opt::ArgStringList &CC1Args) const {
3280 const Driver &D = getDriver();
3281 std::string SysRoot = computeSysRoot();
3282 if (SysRoot.empty())
3283 SysRoot = llvm::sys::path::get_separator();
3285 auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) {
3286 std::string Version = detectLibcxxVersion(Path);
3287 if (Version.empty())
3288 return false;
3290 // First add the per-target include path if it exists.
3291 bool TargetDirExists = false;
3292 std::optional<std::string> TargetIncludeDir = getTargetSubDirPath(Path);
3293 if (TargetIncludeDir) {
3294 SmallString<128> TargetDir(*TargetIncludeDir);
3295 llvm::sys::path::append(TargetDir, "c++", Version);
3296 if (D.getVFS().exists(TargetDir)) {
3297 addSystemInclude(DriverArgs, CC1Args, TargetDir);
3298 TargetDirExists = true;
3301 if (TargetDirRequired && !TargetDirExists)
3302 return false;
3304 // Second add the generic one.
3305 SmallString<128> GenericDir(Path);
3306 llvm::sys::path::append(GenericDir, "c++", Version);
3307 addSystemInclude(DriverArgs, CC1Args, GenericDir);
3308 return true;
3311 // Android only uses the libc++ headers installed alongside the toolchain if
3312 // they contain an Android-specific target include path, otherwise they're
3313 // incompatible with the NDK libraries.
3314 SmallString<128> DriverIncludeDir(getDriver().Dir);
3315 llvm::sys::path::append(DriverIncludeDir, "..", "include");
3316 if (AddIncludePath(DriverIncludeDir,
3317 /*TargetDirRequired=*/getTriple().isAndroid()))
3318 return;
3319 // If this is a development, non-installed, clang, libcxx will
3320 // not be found at ../include/c++ but it likely to be found at
3321 // one of the following two locations:
3322 SmallString<128> UsrLocalIncludeDir(SysRoot);
3323 llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include");
3324 if (AddIncludePath(UsrLocalIncludeDir))
3325 return;
3326 SmallString<128> UsrIncludeDir(SysRoot);
3327 llvm::sys::path::append(UsrIncludeDir, "usr", "include");
3328 if (AddIncludePath(UsrIncludeDir))
3329 return;
3332 bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple,
3333 Twine IncludeSuffix,
3334 const llvm::opt::ArgList &DriverArgs,
3335 llvm::opt::ArgStringList &CC1Args,
3336 bool DetectDebian) const {
3337 if (!getVFS().exists(IncludeDir))
3338 return false;
3340 // Debian native gcc uses g++-multiarch-incdir.diff which uses
3341 // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of
3342 // include/c++/10/x86_64-linux-gnu$IncludeSuffix.
3343 std::string Dir = IncludeDir.str();
3344 StringRef Include =
3345 llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir));
3346 std::string Path =
3347 (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix)
3348 .str();
3349 if (DetectDebian && !getVFS().exists(Path))
3350 return false;
3352 // GPLUSPLUS_INCLUDE_DIR
3353 addSystemInclude(DriverArgs, CC1Args, IncludeDir);
3354 // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent
3355 // include directory.
3356 if (DetectDebian)
3357 addSystemInclude(DriverArgs, CC1Args, Path);
3358 else if (!Triple.empty())
3359 addSystemInclude(DriverArgs, CC1Args,
3360 IncludeDir + "/" + Triple + IncludeSuffix);
3361 // GPLUSPLUS_BACKWARD_INCLUDE_DIR
3362 addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward");
3363 return true;
3366 bool Generic_GCC::addGCCLibStdCxxIncludePaths(
3367 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3368 StringRef DebianMultiarch) const {
3369 assert(GCCInstallation.isValid());
3371 // By default, look for the C++ headers in an include directory adjacent to
3372 // the lib directory of the GCC installation. Note that this is expect to be
3373 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
3374 StringRef LibDir = GCCInstallation.getParentLibPath();
3375 StringRef InstallDir = GCCInstallation.getInstallPath();
3376 StringRef TripleStr = GCCInstallation.getTriple().str();
3377 const Multilib &Multilib = GCCInstallation.getMultilib();
3378 const GCCVersion &Version = GCCInstallation.getVersion();
3380 // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty).
3381 if (addLibStdCXXIncludePaths(
3382 LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text,
3383 TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args))
3384 return true;
3386 // Try /gcc/$triple/$version/include/c++/ (gcc --print-multiarch is not
3387 // empty). Like above but for GCC built with
3388 // --enable-version-specific-runtime-libs.
3389 if (addLibStdCXXIncludePaths(LibDir.str() + "/gcc/" + TripleStr + "/" +
3390 Version.Text + "/include/c++/",
3391 TripleStr, Multilib.includeSuffix(), DriverArgs,
3392 CC1Args))
3393 return true;
3395 // Detect Debian g++-multiarch-incdir.diff.
3396 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3397 DebianMultiarch, Multilib.includeSuffix(),
3398 DriverArgs, CC1Args, /*Debian=*/true))
3399 return true;
3401 // Try /../include/c++/$version (gcc --print-multiarch is empty).
3402 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text,
3403 TripleStr, Multilib.includeSuffix(), DriverArgs,
3404 CC1Args))
3405 return true;
3407 // Otherwise, fall back on a bunch of options which don't use multiarch
3408 // layouts for simplicity.
3409 const std::string LibStdCXXIncludePathCandidates[] = {
3410 // Gentoo is weird and places its headers inside the GCC install,
3411 // so if the first attempt to find the headers fails, try these patterns.
3412 InstallDir.str() + "/include/g++-v" + Version.Text,
3413 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
3414 Version.MinorStr,
3415 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
3418 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
3419 if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
3420 Multilib.includeSuffix(), DriverArgs, CC1Args))
3421 return true;
3423 return false;
3426 void
3427 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
3428 llvm::opt::ArgStringList &CC1Args) const {
3429 if (GCCInstallation.isValid()) {
3430 addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
3431 GCCInstallation.getTriple().str());
3435 llvm::opt::DerivedArgList *
3436 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef,
3437 Action::OffloadKind DeviceOffloadKind) const {
3439 // If this tool chain is used for an OpenMP offloading device we have to make
3440 // sure we always generate a shared library regardless of the commands the
3441 // user passed to the host. This is required because the runtime library
3442 // is required to load the device image dynamically at run time.
3443 if (DeviceOffloadKind == Action::OFK_OpenMP) {
3444 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3445 const OptTable &Opts = getDriver().getOpts();
3447 // Request the shared library. Given that these options are decided
3448 // implicitly, they do not refer to any base argument.
3449 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared));
3450 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC));
3452 // Filter all the arguments we don't care passing to the offloading
3453 // toolchain as they can mess up with the creation of a shared library.
3454 for (auto *A : Args) {
3455 switch ((options::ID)A->getOption().getID()) {
3456 default:
3457 DAL->append(A);
3458 break;
3459 case options::OPT_shared:
3460 case options::OPT_dynamic:
3461 case options::OPT_static:
3462 case options::OPT_fPIC:
3463 case options::OPT_fno_PIC:
3464 case options::OPT_fpic:
3465 case options::OPT_fno_pic:
3466 case options::OPT_fPIE:
3467 case options::OPT_fno_PIE:
3468 case options::OPT_fpie:
3469 case options::OPT_fno_pie:
3470 break;
3473 return DAL;
3475 return nullptr;
3478 void Generic_ELF::anchor() {}
3480 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
3481 ArgStringList &CC1Args,
3482 Action::OffloadKind) const {
3483 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
3484 options::OPT_fno_use_init_array, true))
3485 CC1Args.push_back("-fno-use-init-array");