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