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