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