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