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

source code of clang/lib/Driver/ToolChains/Gnu.cpp