1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- 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 "CommonArgs.h" 10 #include "Arch/AArch64.h" 11 #include "Arch/ARM.h" 12 #include "Arch/CSKY.h" 13 #include "Arch/LoongArch.h" 14 #include "Arch/M68k.h" 15 #include "Arch/Mips.h" 16 #include "Arch/PPC.h" 17 #include "Arch/RISCV.h" 18 #include "Arch/Sparc.h" 19 #include "Arch/SystemZ.h" 20 #include "Arch/VE.h" 21 #include "Arch/X86.h" 22 #include "HIPAMD.h" 23 #include "Hexagon.h" 24 #include "MSP430.h" 25 #include "Solaris.h" 26 #include "clang/Basic/CharInfo.h" 27 #include "clang/Basic/CodeGenOptions.h" 28 #include "clang/Basic/LangOptions.h" 29 #include "clang/Basic/ObjCRuntime.h" 30 #include "clang/Basic/Version.h" 31 #include "clang/Config/config.h" 32 #include "clang/Driver/Action.h" 33 #include "clang/Driver/Compilation.h" 34 #include "clang/Driver/Driver.h" 35 #include "clang/Driver/DriverDiagnostic.h" 36 #include "clang/Driver/InputInfo.h" 37 #include "clang/Driver/Job.h" 38 #include "clang/Driver/Options.h" 39 #include "clang/Driver/SanitizerArgs.h" 40 #include "clang/Driver/ToolChain.h" 41 #include "clang/Driver/Util.h" 42 #include "clang/Driver/XRayArgs.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/SmallSet.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/StringExtras.h" 47 #include "llvm/ADT/StringSwitch.h" 48 #include "llvm/ADT/Twine.h" 49 #include "llvm/BinaryFormat/Magic.h" 50 #include "llvm/Config/llvm-config.h" 51 #include "llvm/Option/Arg.h" 52 #include "llvm/Option/ArgList.h" 53 #include "llvm/Option/Option.h" 54 #include "llvm/Support/CodeGen.h" 55 #include "llvm/Support/Compression.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/FileSystem.h" 59 #include "llvm/Support/Path.h" 60 #include "llvm/Support/Process.h" 61 #include "llvm/Support/Program.h" 62 #include "llvm/Support/ScopedPrinter.h" 63 #include "llvm/Support/Threading.h" 64 #include "llvm/Support/VirtualFileSystem.h" 65 #include "llvm/Support/YAMLParser.h" 66 #include "llvm/TargetParser/Host.h" 67 #include "llvm/TargetParser/TargetParser.h" 68 #include <optional> 69 70 using namespace clang::driver; 71 using namespace clang::driver::tools; 72 using namespace clang; 73 using namespace llvm::opt; 74 75 static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args, 76 const llvm::Triple &Triple) { 77 if (Args.hasArg(clang::driver::options::OPT_pg) && 78 !Args.hasArg(clang::driver::options::OPT_mfentry)) 79 return true; 80 81 if (Triple.isAndroid()) { 82 switch (Triple.getArch()) { 83 case llvm::Triple::aarch64: 84 case llvm::Triple::arm: 85 case llvm::Triple::armeb: 86 case llvm::Triple::thumb: 87 case llvm::Triple::thumbeb: 88 case llvm::Triple::riscv64: 89 return true; 90 default: 91 break; 92 } 93 } 94 95 switch (Triple.getArch()) { 96 case llvm::Triple::xcore: 97 case llvm::Triple::wasm32: 98 case llvm::Triple::wasm64: 99 case llvm::Triple::msp430: 100 // XCore never wants frame pointers, regardless of OS. 101 // WebAssembly never wants frame pointers. 102 return false; 103 case llvm::Triple::ppc: 104 case llvm::Triple::ppcle: 105 case llvm::Triple::ppc64: 106 case llvm::Triple::ppc64le: 107 case llvm::Triple::riscv32: 108 case llvm::Triple::riscv64: 109 case llvm::Triple::sparc: 110 case llvm::Triple::sparcel: 111 case llvm::Triple::sparcv9: 112 case llvm::Triple::amdgcn: 113 case llvm::Triple::r600: 114 case llvm::Triple::csky: 115 case llvm::Triple::loongarch32: 116 case llvm::Triple::loongarch64: 117 return !clang::driver::tools::areOptimizationsEnabled(Args); 118 default: 119 break; 120 } 121 122 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) { 123 return !clang::driver::tools::areOptimizationsEnabled(Args); 124 } 125 126 if (Triple.isOSLinux() || Triple.isOSHurd()) { 127 switch (Triple.getArch()) { 128 // Don't use a frame pointer on linux if optimizing for certain targets. 129 case llvm::Triple::arm: 130 case llvm::Triple::armeb: 131 case llvm::Triple::thumb: 132 case llvm::Triple::thumbeb: 133 case llvm::Triple::mips64: 134 case llvm::Triple::mips64el: 135 case llvm::Triple::mips: 136 case llvm::Triple::mipsel: 137 case llvm::Triple::systemz: 138 case llvm::Triple::x86: 139 case llvm::Triple::x86_64: 140 return !clang::driver::tools::areOptimizationsEnabled(Args); 141 default: 142 return true; 143 } 144 } 145 146 if (Triple.isOSWindows()) { 147 switch (Triple.getArch()) { 148 case llvm::Triple::x86: 149 return !clang::driver::tools::areOptimizationsEnabled(Args); 150 case llvm::Triple::x86_64: 151 return Triple.isOSBinFormatMachO(); 152 case llvm::Triple::arm: 153 case llvm::Triple::thumb: 154 // Windows on ARM builds with FPO disabled to aid fast stack walking 155 return true; 156 default: 157 // All other supported Windows ISAs use xdata unwind information, so frame 158 // pointers are not generally useful. 159 return false; 160 } 161 } 162 163 return true; 164 } 165 166 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) { 167 switch (Triple.getArch()) { 168 default: 169 return false; 170 case llvm::Triple::arm: 171 case llvm::Triple::thumb: 172 // ARM Darwin targets require a frame pointer to be always present to aid 173 // offline debugging via backtraces. 174 return Triple.isOSDarwin(); 175 } 176 } 177 178 clang::CodeGenOptions::FramePointerKind 179 getFramePointerKind(const llvm::opt::ArgList &Args, 180 const llvm::Triple &Triple) { 181 // We have 4 states: 182 // 183 // 00) leaf retained, non-leaf retained 184 // 01) leaf retained, non-leaf omitted (this is invalid) 185 // 10) leaf omitted, non-leaf retained 186 // (what -momit-leaf-frame-pointer was designed for) 187 // 11) leaf omitted, non-leaf omitted 188 // 189 // "omit" options taking precedence over "no-omit" options is the only way 190 // to make 3 valid states representable 191 llvm::opt::Arg *A = 192 Args.getLastArg(clang::driver::options::OPT_fomit_frame_pointer, 193 clang::driver::options::OPT_fno_omit_frame_pointer); 194 195 bool OmitFP = A && A->getOption().matches( 196 clang::driver::options::OPT_fomit_frame_pointer); 197 bool NoOmitFP = A && A->getOption().matches( 198 clang::driver::options::OPT_fno_omit_frame_pointer); 199 bool OmitLeafFP = 200 Args.hasFlag(clang::driver::options::OPT_momit_leaf_frame_pointer, 201 clang::driver::options::OPT_mno_omit_leaf_frame_pointer, 202 Triple.isAArch64() || Triple.isPS() || Triple.isVE() || 203 (Triple.isAndroid() && Triple.isRISCV64())); 204 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) || 205 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) { 206 if (OmitLeafFP) 207 return clang::CodeGenOptions::FramePointerKind::NonLeaf; 208 return clang::CodeGenOptions::FramePointerKind::All; 209 } 210 return clang::CodeGenOptions::FramePointerKind::None; 211 } 212 213 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs, 214 const StringRef PluginOptPrefix) { 215 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) 216 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 217 "-pass-remarks=" + A->getValue())); 218 219 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) 220 CmdArgs.push_back(Args.MakeArgString( 221 Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue())); 222 223 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) 224 CmdArgs.push_back(Args.MakeArgString( 225 Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue())); 226 } 227 228 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, 229 const llvm::Triple &Triple, 230 const InputInfo &Input, 231 const InputInfo &Output, 232 const StringRef PluginOptPrefix) { 233 StringRef Format = "yaml"; 234 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) 235 Format = A->getValue(); 236 237 SmallString<128> F; 238 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ); 239 if (A) 240 F = A->getValue(); 241 else if (Output.isFilename()) 242 F = Output.getFilename(); 243 244 assert(!F.empty() && "Cannot determine remarks output name."); 245 // Append "opt.ld.<format>" to the end of the file name. 246 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 247 "opt-remarks-filename=" + F + 248 ".opt.ld." + Format)); 249 250 if (const Arg *A = 251 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) 252 CmdArgs.push_back(Args.MakeArgString( 253 Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue())); 254 255 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 256 "opt-remarks-format=" + Format.data())); 257 } 258 259 static void renderRemarksHotnessOptions(const ArgList &Args, 260 ArgStringList &CmdArgs, 261 const StringRef PluginOptPrefix) { 262 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 263 options::OPT_fno_diagnostics_show_hotness, false)) 264 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 265 "opt-remarks-with-hotness")); 266 267 if (const Arg *A = 268 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) 269 CmdArgs.push_back( 270 Args.MakeArgString(Twine(PluginOptPrefix) + 271 "opt-remarks-hotness-threshold=" + A->getValue())); 272 } 273 274 static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg, 275 llvm::Triple T, 276 StringRef Processor) { 277 // Warn no-cumode for AMDGCN processors not supporing WGP mode. 278 if (!T.isAMDGPU()) 279 return false; 280 auto GPUKind = T.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(Processor) 281 : llvm::AMDGPU::parseArchR600(Processor); 282 auto GPUFeatures = T.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(GPUKind) 283 : llvm::AMDGPU::getArchAttrR600(GPUKind); 284 if (GPUFeatures & llvm::AMDGPU::FEATURE_WGP) 285 return false; 286 return TargetFeatureArg.getOption().matches(options::OPT_mno_cumode); 287 } 288 289 void tools::addPathIfExists(const Driver &D, const Twine &Path, 290 ToolChain::path_list &Paths) { 291 if (D.getVFS().exists(Path)) 292 Paths.push_back(Path.str()); 293 } 294 295 void tools::handleTargetFeaturesGroup(const Driver &D, 296 const llvm::Triple &Triple, 297 const ArgList &Args, 298 std::vector<StringRef> &Features, 299 OptSpecifier Group) { 300 std::set<StringRef> Warned; 301 for (const Arg *A : Args.filtered(Group)) { 302 StringRef Name = A->getOption().getName(); 303 A->claim(); 304 305 // Skip over "-m". 306 assert(Name.starts_with("m") && "Invalid feature name."); 307 Name = Name.substr(1); 308 309 auto Proc = getCPUName(D, Args, Triple); 310 if (shouldIgnoreUnsupportedTargetFeature(*A, Triple, Proc)) { 311 if (Warned.count(Name) == 0) { 312 D.getDiags().Report( 313 clang::diag::warn_drv_unsupported_option_for_processor) 314 << A->getAsString(Args) << Proc; 315 Warned.insert(Name); 316 } 317 continue; 318 } 319 320 bool IsNegative = Name.starts_with("no-"); 321 if (IsNegative) 322 Name = Name.substr(3); 323 324 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 325 } 326 } 327 328 SmallVector<StringRef> 329 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) { 330 // Only add a feature if it hasn't been seen before starting from the end. 331 SmallVector<StringRef> UnifiedFeatures; 332 llvm::DenseSet<StringRef> UsedFeatures; 333 for (StringRef Feature : llvm::reverse(Features)) { 334 if (UsedFeatures.insert(Feature.drop_front()).second) 335 UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature); 336 } 337 338 return UnifiedFeatures; 339 } 340 341 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 342 const char *ArgName, const char *EnvVar) { 343 const char *DirList = ::getenv(EnvVar); 344 bool CombinedArg = false; 345 346 if (!DirList) 347 return; // Nothing to do. 348 349 StringRef Name(ArgName); 350 if (Name.equals("-I") || Name.equals("-L") || Name.empty()) 351 CombinedArg = true; 352 353 StringRef Dirs(DirList); 354 if (Dirs.empty()) // Empty string should not add '.'. 355 return; 356 357 StringRef::size_type Delim; 358 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 359 if (Delim == 0) { // Leading colon. 360 if (CombinedArg) { 361 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 362 } else { 363 CmdArgs.push_back(ArgName); 364 CmdArgs.push_back("."); 365 } 366 } else { 367 if (CombinedArg) { 368 CmdArgs.push_back( 369 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 370 } else { 371 CmdArgs.push_back(ArgName); 372 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 373 } 374 } 375 Dirs = Dirs.substr(Delim + 1); 376 } 377 378 if (Dirs.empty()) { // Trailing colon. 379 if (CombinedArg) { 380 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 381 } else { 382 CmdArgs.push_back(ArgName); 383 CmdArgs.push_back("."); 384 } 385 } else { // Add the last path. 386 if (CombinedArg) { 387 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 388 } else { 389 CmdArgs.push_back(ArgName); 390 CmdArgs.push_back(Args.MakeArgString(Dirs)); 391 } 392 } 393 } 394 395 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 396 const ArgList &Args, ArgStringList &CmdArgs, 397 const JobAction &JA) { 398 const Driver &D = TC.getDriver(); 399 400 // Add extra linker input arguments which are not treated as inputs 401 // (constructed via -Xarch_). 402 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 403 404 // LIBRARY_PATH are included before user inputs and only supported on native 405 // toolchains. 406 if (!TC.isCrossCompiling()) 407 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 408 409 for (const auto &II : Inputs) { 410 // If the current tool chain refers to an OpenMP offloading host, we 411 // should ignore inputs that refer to OpenMP offloading devices - 412 // they will be embedded according to a proper linker script. 413 if (auto *IA = II.getAction()) 414 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 415 IA->isDeviceOffloading(Action::OFK_OpenMP))) 416 continue; 417 418 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 419 // Don't try to pass LLVM inputs unless we have native support. 420 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 421 422 // Add filenames immediately. 423 if (II.isFilename()) { 424 CmdArgs.push_back(II.getFilename()); 425 continue; 426 } 427 428 // In some error cases, the input could be Nothing; skip those. 429 if (II.isNothing()) 430 continue; 431 432 // Otherwise, this is a linker input argument. 433 const Arg &A = II.getInputArg(); 434 435 // Handle reserved library options. 436 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 437 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 438 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 439 TC.AddCCKextLibArgs(Args, CmdArgs); 440 else 441 A.renderAsInput(Args, CmdArgs); 442 } 443 } 444 445 void tools::addLinkerCompressDebugSectionsOption( 446 const ToolChain &TC, const llvm::opt::ArgList &Args, 447 llvm::opt::ArgStringList &CmdArgs) { 448 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi 449 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore 450 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz 451 // is not translated since ld --compress-debug-sections option requires an 452 // argument. 453 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) { 454 StringRef V = A->getValue(); 455 if (V == "none" || V == "zlib" || V == "zstd") 456 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V)); 457 else 458 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument) 459 << A->getSpelling() << V; 460 } 461 } 462 463 void tools::AddTargetFeature(const ArgList &Args, 464 std::vector<StringRef> &Features, 465 OptSpecifier OnOpt, OptSpecifier OffOpt, 466 StringRef FeatureName) { 467 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 468 if (A->getOption().matches(OnOpt)) 469 Features.push_back(Args.MakeArgString("+" + FeatureName)); 470 else 471 Features.push_back(Args.MakeArgString("-" + FeatureName)); 472 } 473 } 474 475 /// Get the (LLVM) name of the AMDGPU gpu we are targeting. 476 static std::string getAMDGPUTargetGPU(const llvm::Triple &T, 477 const ArgList &Args) { 478 Arg *MArch = Args.getLastArg(options::OPT_march_EQ); 479 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 480 auto GPUName = getProcessorFromTargetID(T, A->getValue()); 481 return llvm::StringSwitch<std::string>(GPUName) 482 .Cases("rv630", "rv635", "r600") 483 .Cases("rv610", "rv620", "rs780", "rs880") 484 .Case("rv740", "rv770") 485 .Case("palm", "cedar") 486 .Cases("sumo", "sumo2", "sumo") 487 .Case("hemlock", "cypress") 488 .Case("aruba", "cayman") 489 .Default(GPUName.str()); 490 } 491 if (MArch) 492 return getProcessorFromTargetID(T, MArch->getValue()).str(); 493 return ""; 494 } 495 496 static std::string getLanaiTargetCPU(const ArgList &Args) { 497 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 498 return A->getValue(); 499 } 500 return ""; 501 } 502 503 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 504 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 505 // If we have -mcpu=, use that. 506 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 507 StringRef CPU = A->getValue(); 508 509 #ifdef __wasm__ 510 // Handle "native" by examining the host. "native" isn't meaningful when 511 // cross compiling, so only support this when the host is also WebAssembly. 512 if (CPU == "native") 513 return llvm::sys::getHostCPUName(); 514 #endif 515 516 return CPU; 517 } 518 519 return "generic"; 520 } 521 522 std::string tools::getCPUName(const Driver &D, const ArgList &Args, 523 const llvm::Triple &T, bool FromAs) { 524 Arg *A; 525 526 switch (T.getArch()) { 527 default: 528 return ""; 529 530 case llvm::Triple::aarch64: 531 case llvm::Triple::aarch64_32: 532 case llvm::Triple::aarch64_be: 533 return aarch64::getAArch64TargetCPU(Args, T, A); 534 535 case llvm::Triple::arm: 536 case llvm::Triple::armeb: 537 case llvm::Triple::thumb: 538 case llvm::Triple::thumbeb: { 539 StringRef MArch, MCPU; 540 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 541 return arm::getARMTargetCPU(MCPU, MArch, T); 542 } 543 544 case llvm::Triple::avr: 545 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 546 return A->getValue(); 547 return ""; 548 549 case llvm::Triple::m68k: 550 return m68k::getM68kTargetCPU(Args); 551 552 case llvm::Triple::mips: 553 case llvm::Triple::mipsel: 554 case llvm::Triple::mips64: 555 case llvm::Triple::mips64el: { 556 StringRef CPUName; 557 StringRef ABIName; 558 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 559 return std::string(CPUName); 560 } 561 562 case llvm::Triple::nvptx: 563 case llvm::Triple::nvptx64: 564 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 565 return A->getValue(); 566 return ""; 567 568 case llvm::Triple::ppc: 569 case llvm::Triple::ppcle: 570 case llvm::Triple::ppc64: 571 case llvm::Triple::ppc64le: 572 return ppc::getPPCTargetCPU(D, Args, T); 573 574 case llvm::Triple::csky: 575 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 576 return A->getValue(); 577 else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 578 return A->getValue(); 579 else 580 return "ck810"; 581 case llvm::Triple::riscv32: 582 case llvm::Triple::riscv64: 583 return riscv::getRISCVTargetCPU(Args, T); 584 585 case llvm::Triple::bpfel: 586 case llvm::Triple::bpfeb: 587 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 588 return A->getValue(); 589 return ""; 590 591 case llvm::Triple::sparc: 592 case llvm::Triple::sparcel: 593 case llvm::Triple::sparcv9: 594 return sparc::getSparcTargetCPU(D, Args, T); 595 596 case llvm::Triple::x86: 597 case llvm::Triple::x86_64: 598 return x86::getX86TargetCPU(D, Args, T); 599 600 case llvm::Triple::hexagon: 601 return "hexagon" + 602 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 603 604 case llvm::Triple::lanai: 605 return getLanaiTargetCPU(Args); 606 607 case llvm::Triple::systemz: 608 return systemz::getSystemZTargetCPU(Args); 609 610 case llvm::Triple::r600: 611 case llvm::Triple::amdgcn: 612 return getAMDGPUTargetGPU(T, Args); 613 614 case llvm::Triple::wasm32: 615 case llvm::Triple::wasm64: 616 return std::string(getWebAssemblyTargetCPU(Args)); 617 618 case llvm::Triple::loongarch32: 619 case llvm::Triple::loongarch64: 620 return loongarch::getLoongArchTargetCPU(Args, T); 621 } 622 } 623 624 static void getWebAssemblyTargetFeatures(const Driver &D, 625 const llvm::Triple &Triple, 626 const ArgList &Args, 627 std::vector<StringRef> &Features) { 628 handleTargetFeaturesGroup(D, Triple, Args, Features, 629 options::OPT_m_wasm_Features_Group); 630 } 631 632 void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple, 633 const ArgList &Args, ArgStringList &CmdArgs, 634 bool ForAS, bool IsAux) { 635 std::vector<StringRef> Features; 636 switch (Triple.getArch()) { 637 default: 638 break; 639 case llvm::Triple::mips: 640 case llvm::Triple::mipsel: 641 case llvm::Triple::mips64: 642 case llvm::Triple::mips64el: 643 mips::getMIPSTargetFeatures(D, Triple, Args, Features); 644 break; 645 case llvm::Triple::arm: 646 case llvm::Triple::armeb: 647 case llvm::Triple::thumb: 648 case llvm::Triple::thumbeb: 649 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS); 650 break; 651 case llvm::Triple::ppc: 652 case llvm::Triple::ppcle: 653 case llvm::Triple::ppc64: 654 case llvm::Triple::ppc64le: 655 ppc::getPPCTargetFeatures(D, Triple, Args, Features); 656 break; 657 case llvm::Triple::riscv32: 658 case llvm::Triple::riscv64: 659 riscv::getRISCVTargetFeatures(D, Triple, Args, Features); 660 break; 661 case llvm::Triple::systemz: 662 systemz::getSystemZTargetFeatures(D, Args, Features); 663 break; 664 case llvm::Triple::aarch64: 665 case llvm::Triple::aarch64_32: 666 case llvm::Triple::aarch64_be: 667 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS); 668 break; 669 case llvm::Triple::x86: 670 case llvm::Triple::x86_64: 671 x86::getX86TargetFeatures(D, Triple, Args, Features); 672 break; 673 case llvm::Triple::hexagon: 674 hexagon::getHexagonTargetFeatures(D, Triple, Args, Features); 675 break; 676 case llvm::Triple::wasm32: 677 case llvm::Triple::wasm64: 678 getWebAssemblyTargetFeatures(D, Triple, Args, Features); 679 break; 680 case llvm::Triple::sparc: 681 case llvm::Triple::sparcel: 682 case llvm::Triple::sparcv9: 683 sparc::getSparcTargetFeatures(D, Args, Features); 684 break; 685 case llvm::Triple::r600: 686 case llvm::Triple::amdgcn: 687 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features); 688 break; 689 case llvm::Triple::nvptx: 690 case llvm::Triple::nvptx64: 691 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features); 692 break; 693 case llvm::Triple::m68k: 694 m68k::getM68kTargetFeatures(D, Triple, Args, Features); 695 break; 696 case llvm::Triple::msp430: 697 msp430::getMSP430TargetFeatures(D, Args, Features); 698 break; 699 case llvm::Triple::ve: 700 ve::getVETargetFeatures(D, Args, Features); 701 break; 702 case llvm::Triple::csky: 703 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features); 704 break; 705 case llvm::Triple::loongarch32: 706 case llvm::Triple::loongarch64: 707 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features); 708 break; 709 } 710 711 for (auto Feature : unifyTargetFeatures(Features)) { 712 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature"); 713 CmdArgs.push_back(Feature.data()); 714 } 715 } 716 717 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 718 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 719 if (!LtoJobsArg) 720 return {}; 721 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue())) 722 D.Diag(diag::err_drv_invalid_int_value) 723 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); 724 return LtoJobsArg->getValue(); 725 } 726 727 // PS4/PS5 uses -ffunction-sections and -fdata-sections by default. 728 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 729 return Triple.isPS(); 730 } 731 732 bool tools::isTLSDESCEnabled(const ToolChain &TC, 733 const llvm::opt::ArgList &Args) { 734 const llvm::Triple &Triple = TC.getEffectiveTriple(); 735 Arg *A = Args.getLastArg(options::OPT_mtls_dialect_EQ); 736 if (!A) 737 return Triple.hasDefaultTLSDESC(); 738 StringRef V = A->getValue(); 739 bool SupportedArgument = false, EnableTLSDESC = false; 740 bool Unsupported = !Triple.isOSBinFormatELF(); 741 if (Triple.isRISCV()) { 742 SupportedArgument = V == "desc" || V == "trad"; 743 EnableTLSDESC = V == "desc"; 744 } else if (Triple.isX86()) { 745 SupportedArgument = V == "gnu"; 746 } else { 747 Unsupported = true; 748 } 749 if (Unsupported) { 750 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 751 << A->getSpelling() << Triple.getTriple(); 752 } else if (!SupportedArgument) { 753 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument_for_target) 754 << A->getSpelling() << V << Triple.getTriple(); 755 } 756 return EnableTLSDESC; 757 } 758 759 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, 760 ArgStringList &CmdArgs, const InputInfo &Output, 761 const InputInfo &Input, bool IsThinLTO) { 762 const bool IsOSAIX = ToolChain.getTriple().isOSAIX(); 763 const bool IsAMDGCN = ToolChain.getTriple().isAMDGCN(); 764 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 765 const Driver &D = ToolChain.getDriver(); 766 const bool IsFatLTO = Args.hasArg(options::OPT_ffat_lto_objects); 767 const bool IsUnifiedLTO = Args.hasArg(options::OPT_funified_lto); 768 if (llvm::sys::path::filename(Linker) != "ld.lld" && 769 llvm::sys::path::stem(Linker) != "ld.lld" && 770 !ToolChain.getTriple().isOSOpenBSD()) { 771 // Tell the linker to load the plugin. This has to come before 772 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to 773 // come before any -plugin-opt/-bplugin_opt that -Wl might forward. 774 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : ""; 775 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold"; 776 777 if (!IsOSAIX) 778 CmdArgs.push_back("-plugin"); 779 780 #if defined(_WIN32) 781 const char *Suffix = ".dll"; 782 #elif defined(__APPLE__) 783 const char *Suffix = ".dylib"; 784 #else 785 const char *Suffix = ".so"; 786 #endif 787 788 SmallString<1024> Plugin; 789 llvm::sys::path::native(Twine(D.Dir) + 790 "/../" CLANG_INSTALL_LIBDIR_BASENAME + 791 PluginName + Suffix, 792 Plugin); 793 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin)); 794 } else { 795 // Tell LLD to find and use .llvm.lto section in regular relocatable object 796 // files 797 if (IsFatLTO) 798 CmdArgs.push_back("--fat-lto-objects"); 799 } 800 801 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt="; 802 const char *ExtraDash = IsOSAIX ? "-" : ""; 803 const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs="; 804 805 // Note, this solution is far from perfect, better to encode it into IR 806 // metadata, but this may not be worth it, since it looks like aranges is on 807 // the way out. 808 if (Args.hasArg(options::OPT_gdwarf_aranges)) { 809 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 810 "-generate-arange-section")); 811 } 812 813 // Pass vector library arguments to LTO. 814 Arg *ArgVecLib = Args.getLastArg(options::OPT_fveclib); 815 if (ArgVecLib && ArgVecLib->getNumValues() == 1) { 816 // Map the vector library names from clang front-end to opt front-end. The 817 // values are taken from the TargetLibraryInfo class command line options. 818 std::optional<StringRef> OptVal = 819 llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue()) 820 .Case("Accelerate", "Accelerate") 821 .Case("LIBMVEC", "LIBMVEC-X86") 822 .Case("MASSV", "MASSV") 823 .Case("SVML", "SVML") 824 .Case("SLEEF", "sleefgnuabi") 825 .Case("Darwin_libsystem_m", "Darwin_libsystem_m") 826 .Case("ArmPL", "ArmPL") 827 .Case("none", "none") 828 .Default(std::nullopt); 829 830 if (OptVal) 831 CmdArgs.push_back(Args.MakeArgString( 832 Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value())); 833 } 834 835 // Try to pass driver level flags relevant to LTO code generation down to 836 // the plugin. 837 838 // Handle flags for selecting CPU variants. 839 std::string CPU = getCPUName(D, Args, ToolChain.getTriple()); 840 if (!CPU.empty()) 841 CmdArgs.push_back( 842 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU)); 843 844 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 845 // The optimization level matches 846 // CompilerInvocation.cpp:getOptimizationLevel(). 847 StringRef OOpt; 848 if (A->getOption().matches(options::OPT_O4) || 849 A->getOption().matches(options::OPT_Ofast)) 850 OOpt = "3"; 851 else if (A->getOption().matches(options::OPT_O)) { 852 OOpt = A->getValue(); 853 if (OOpt == "g") 854 OOpt = "1"; 855 else if (OOpt == "s" || OOpt == "z") 856 OOpt = "2"; 857 } else if (A->getOption().matches(options::OPT_O0)) 858 OOpt = "0"; 859 if (!OOpt.empty()) { 860 CmdArgs.push_back( 861 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt)); 862 if (IsAMDGCN) 863 CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt)); 864 } 865 } 866 867 if (Args.hasArg(options::OPT_gsplit_dwarf)) 868 CmdArgs.push_back(Args.MakeArgString( 869 Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo")); 870 871 if (IsThinLTO && !IsOSAIX) 872 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto")); 873 else if (IsThinLTO && IsOSAIX) 874 CmdArgs.push_back(Args.MakeArgString(Twine("-bdbg:thinlto"))); 875 876 // Matrix intrinsic lowering happens at link time with ThinLTO. Enable 877 // LowerMatrixIntrinsicsPass, which is transitively called by 878 // buildThinLTODefaultPipeline under EnableMatrix. 879 if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) && 880 Args.hasArg(options::OPT_fenable_matrix)) 881 CmdArgs.push_back( 882 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-matrix")); 883 884 StringRef Parallelism = getLTOParallelism(Args, D); 885 if (!Parallelism.empty()) 886 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 887 ParallelismOpt + Parallelism)); 888 889 // Pass down GlobalISel options. 890 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel, 891 options::OPT_fno_global_isel)) { 892 // Parsing -fno-global-isel explicitly gives architectures that enable GISel 893 // by default a chance to disable it. 894 CmdArgs.push_back(Args.MakeArgString( 895 Twine(PluginOptPrefix) + "-global-isel=" + 896 (A->getOption().matches(options::OPT_fglobal_isel) ? "1" : "0"))); 897 } 898 899 // If an explicit debugger tuning argument appeared, pass it along. 900 if (Arg *A = 901 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { 902 if (A->getOption().matches(options::OPT_glldb)) 903 CmdArgs.push_back( 904 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb")); 905 else if (A->getOption().matches(options::OPT_gsce)) 906 CmdArgs.push_back( 907 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce")); 908 else if (A->getOption().matches(options::OPT_gdbx)) 909 CmdArgs.push_back( 910 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx")); 911 else 912 CmdArgs.push_back( 913 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb")); 914 } 915 916 if (IsOSAIX) { 917 if (!ToolChain.useIntegratedAs()) 918 CmdArgs.push_back( 919 Args.MakeArgString(Twine(PluginOptPrefix) + "-no-integrated-as=1")); 920 921 // On AIX, clang assumes strict-dwarf is true if any debug option is 922 // specified, unless it is told explicitly not to assume so. 923 Arg *A = Args.getLastArg(options::OPT_g_Group); 924 bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) && 925 !A->getOption().matches(options::OPT_ggdb0); 926 if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf, 927 options::OPT_gno_strict_dwarf, true)) 928 CmdArgs.push_back( 929 Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true")); 930 931 for (const Arg *A : Args.filtered_reverse(options::OPT_mabi_EQ)) { 932 StringRef V = A->getValue(); 933 if (V == "vec-default") 934 break; 935 if (V == "vec-extabi") { 936 CmdArgs.push_back( 937 Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi")); 938 break; 939 } 940 } 941 } 942 943 bool UseSeparateSections = 944 isUseSeparateSections(ToolChain.getEffectiveTriple()); 945 946 if (Args.hasFlag(options::OPT_ffunction_sections, 947 options::OPT_fno_function_sections, UseSeparateSections)) 948 CmdArgs.push_back( 949 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1")); 950 else if (Args.hasArg(options::OPT_fno_function_sections)) 951 CmdArgs.push_back( 952 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0")); 953 954 bool DataSectionsTurnedOff = false; 955 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 956 UseSeparateSections)) { 957 CmdArgs.push_back( 958 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1")); 959 } else if (Args.hasArg(options::OPT_fno_data_sections)) { 960 DataSectionsTurnedOff = true; 961 CmdArgs.push_back( 962 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0")); 963 } 964 965 if (Args.hasArg(options::OPT_mxcoff_roptr) || 966 Args.hasArg(options::OPT_mno_xcoff_roptr)) { 967 bool HasRoptr = Args.hasFlag(options::OPT_mxcoff_roptr, 968 options::OPT_mno_xcoff_roptr, false); 969 StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr"; 970 971 if (!IsOSAIX) 972 D.Diag(diag::err_drv_unsupported_opt_for_target) 973 << OptStr << ToolChain.getTriple().str(); 974 975 if (HasRoptr) { 976 // The data sections option is on by default on AIX. We only need to error 977 // out when -fno-data-sections is specified explicitly to turn off data 978 // sections. 979 if (DataSectionsTurnedOff) 980 D.Diag(diag::err_roptr_requires_data_sections); 981 982 CmdArgs.push_back( 983 Args.MakeArgString(Twine(PluginOptPrefix) + "-mxcoff-roptr")); 984 } 985 } 986 987 // Pass an option to enable split machine functions. 988 if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions, 989 options::OPT_fno_split_machine_functions)) { 990 if (A->getOption().matches(options::OPT_fsplit_machine_functions)) 991 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 992 "-split-machine-functions")); 993 } 994 995 if (Arg *A = getLastProfileSampleUseArg(Args)) { 996 StringRef FName = A->getValue(); 997 if (!llvm::sys::fs::exists(FName)) 998 D.Diag(diag::err_drv_no_such_file) << FName; 999 else 1000 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 1001 "sample-profile=" + FName)); 1002 } 1003 1004 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) { 1005 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1006 "cs-profile-generate")); 1007 if (CSPGOGenerateArg->getOption().matches( 1008 options::OPT_fcs_profile_generate_EQ)) { 1009 SmallString<128> Path(CSPGOGenerateArg->getValue()); 1010 llvm::sys::path::append(Path, "default_%m.profraw"); 1011 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1012 "cs-profile-path=" + Path)); 1013 } else 1014 CmdArgs.push_back( 1015 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1016 "cs-profile-path=default_%m.profraw")); 1017 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) { 1018 SmallString<128> Path( 1019 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 1020 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 1021 llvm::sys::path::append(Path, "default.profdata"); 1022 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1023 "cs-profile-path=" + Path)); 1024 } 1025 1026 // This controls whether or not we perform JustMyCode instrumentation. 1027 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) { 1028 if (ToolChain.getEffectiveTriple().isOSBinFormatELF()) 1029 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 1030 "-enable-jmc-instrument")); 1031 else 1032 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only); 1033 } 1034 1035 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls, 1036 ToolChain.getTriple().hasDefaultEmulatedTLS())) { 1037 CmdArgs.push_back( 1038 Args.MakeArgString(Twine(PluginOptPrefix) + "-emulated-tls")); 1039 } 1040 if (isTLSDESCEnabled(ToolChain, Args)) 1041 CmdArgs.push_back( 1042 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-tlsdesc")); 1043 1044 if (Args.hasFlag(options::OPT_fstack_size_section, 1045 options::OPT_fno_stack_size_section, false)) 1046 CmdArgs.push_back( 1047 Args.MakeArgString(Twine(PluginOptPrefix) + "-stack-size-section")); 1048 1049 // Setup statistics file output. 1050 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 1051 if (!StatsFile.empty()) 1052 CmdArgs.push_back( 1053 Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile)); 1054 1055 // Setup crash diagnostics dir. 1056 if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir)) 1057 CmdArgs.push_back(Args.MakeArgString( 1058 Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue())); 1059 1060 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix); 1061 1062 // Handle remark diagnostics on screen options: '-Rpass-*'. 1063 renderRpassOptions(Args, CmdArgs, PluginOptPrefix); 1064 1065 // Handle serialized remarks options: '-fsave-optimization-record' 1066 // and '-foptimization-record-*'. 1067 if (willEmitRemarks(Args)) 1068 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input, 1069 Output, PluginOptPrefix); 1070 1071 // Handle remarks hotness/threshold related options. 1072 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix); 1073 1074 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(), 1075 /*IsLTO=*/true, PluginOptPrefix); 1076 } 1077 1078 /// Adds the '-lcgpu' and '-lmgpu' libraries to the compilation to include the 1079 /// LLVM C library for GPUs. 1080 static void addOpenMPDeviceLibC(const ToolChain &TC, const ArgList &Args, 1081 ArgStringList &CmdArgs) { 1082 if (Args.hasArg(options::OPT_nogpulib) || Args.hasArg(options::OPT_nolibc)) 1083 return; 1084 1085 // Check the resource directory for the LLVM libc GPU declarations. If it's 1086 // found we can assume that LLVM was built with support for the GPU libc. 1087 SmallString<256> LibCDecls(TC.getDriver().ResourceDir); 1088 llvm::sys::path::append(LibCDecls, "include", "llvm_libc_wrappers", 1089 "llvm-libc-decls"); 1090 bool HasLibC = llvm::sys::fs::exists(LibCDecls) && 1091 llvm::sys::fs::is_directory(LibCDecls); 1092 if (Args.hasFlag(options::OPT_gpulibc, options::OPT_nogpulibc, HasLibC)) { 1093 CmdArgs.push_back("-lcgpu"); 1094 CmdArgs.push_back("-lmgpu"); 1095 } 1096 } 1097 1098 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC, 1099 const ArgList &Args, 1100 ArgStringList &CmdArgs) { 1101 // Default to clang lib / lib64 folder, i.e. the same location as device 1102 // runtime. 1103 SmallString<256> DefaultLibPath = 1104 llvm::sys::path::parent_path(TC.getDriver().Dir); 1105 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 1106 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath)); 1107 } 1108 1109 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 1110 ArgStringList &CmdArgs) { 1111 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 1112 options::OPT_fno_rtlib_add_rpath, false)) 1113 return; 1114 1115 for (const auto &CandidateRPath : TC.getArchSpecificLibPaths()) { 1116 if (TC.getVFS().exists(CandidateRPath)) { 1117 CmdArgs.push_back("-rpath"); 1118 CmdArgs.push_back(Args.MakeArgString(CandidateRPath)); 1119 } 1120 } 1121 } 1122 1123 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 1124 const ArgList &Args, bool ForceStaticHostRuntime, 1125 bool IsOffloadingHost, bool GompNeedsRT) { 1126 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 1127 options::OPT_fno_openmp, false)) 1128 return false; 1129 1130 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 1131 1132 if (RTKind == Driver::OMPRT_Unknown) 1133 // Already diagnosed. 1134 return false; 1135 1136 if (ForceStaticHostRuntime) 1137 CmdArgs.push_back("-Bstatic"); 1138 1139 switch (RTKind) { 1140 case Driver::OMPRT_OMP: 1141 CmdArgs.push_back("-lomp"); 1142 break; 1143 case Driver::OMPRT_GOMP: 1144 CmdArgs.push_back("-lgomp"); 1145 break; 1146 case Driver::OMPRT_IOMP5: 1147 CmdArgs.push_back("-liomp5"); 1148 break; 1149 case Driver::OMPRT_Unknown: 1150 break; 1151 } 1152 1153 if (ForceStaticHostRuntime) 1154 CmdArgs.push_back("-Bdynamic"); 1155 1156 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 1157 CmdArgs.push_back("-lrt"); 1158 1159 if (IsOffloadingHost) 1160 CmdArgs.push_back("-lomptarget"); 1161 1162 if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib)) 1163 CmdArgs.push_back("-lomptarget.devicertl"); 1164 1165 if (IsOffloadingHost) 1166 addOpenMPDeviceLibC(TC, Args, CmdArgs); 1167 1168 addArchSpecificRPath(TC, Args, CmdArgs); 1169 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs); 1170 1171 return true; 1172 } 1173 1174 /// Determines if --whole-archive is active in the list of arguments. 1175 static bool isWholeArchivePresent(const ArgList &Args) { 1176 bool WholeArchiveActive = false; 1177 for (auto *Arg : Args.filtered(options::OPT_Wl_COMMA)) { 1178 if (Arg) { 1179 for (StringRef ArgValue : Arg->getValues()) { 1180 if (ArgValue == "--whole-archive") 1181 WholeArchiveActive = true; 1182 if (ArgValue == "--no-whole-archive") 1183 WholeArchiveActive = false; 1184 } 1185 } 1186 } 1187 1188 return WholeArchiveActive; 1189 } 1190 1191 /// Determine if driver is invoked to create a shared object library (-static) 1192 static bool isSharedLinkage(const ArgList &Args) { 1193 return Args.hasArg(options::OPT_shared); 1194 } 1195 1196 /// Determine if driver is invoked to create a static object library (-shared) 1197 static bool isStaticLinkage(const ArgList &Args) { 1198 return Args.hasArg(options::OPT_static); 1199 } 1200 1201 /// Add Fortran runtime libs for MSVC 1202 static void addFortranRuntimeLibsMSVC(const ArgList &Args, 1203 llvm::opt::ArgStringList &CmdArgs) { 1204 unsigned RTOptionID = options::OPT__SLASH_MT; 1205 if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) { 1206 RTOptionID = llvm::StringSwitch<unsigned>(rtl->getValue()) 1207 .Case("static", options::OPT__SLASH_MT) 1208 .Case("static_dbg", options::OPT__SLASH_MTd) 1209 .Case("dll", options::OPT__SLASH_MD) 1210 .Case("dll_dbg", options::OPT__SLASH_MDd) 1211 .Default(options::OPT__SLASH_MT); 1212 } 1213 switch (RTOptionID) { 1214 case options::OPT__SLASH_MT: 1215 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static.lib"); 1216 break; 1217 case options::OPT__SLASH_MTd: 1218 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.static_dbg.lib"); 1219 break; 1220 case options::OPT__SLASH_MD: 1221 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic.lib"); 1222 break; 1223 case options::OPT__SLASH_MDd: 1224 CmdArgs.push_back("/WHOLEARCHIVE:Fortran_main.dynamic_dbg.lib"); 1225 break; 1226 } 1227 } 1228 1229 // Add FortranMain runtime lib 1230 static void addFortranMain(const ToolChain &TC, const ArgList &Args, 1231 llvm::opt::ArgStringList &CmdArgs) { 1232 // 0. Shared-library linkage 1233 // If we are attempting to link a library, we should not add 1234 // -lFortran_main.a to the link line, as the `main` symbol is not 1235 // required for a library and should also be provided by one of 1236 // the translation units of the code that this shared library 1237 // will be linked against eventually. 1238 if (isSharedLinkage(Args) || isStaticLinkage(Args)) { 1239 return; 1240 } 1241 1242 // 1. MSVC 1243 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1244 addFortranRuntimeLibsMSVC(Args, CmdArgs); 1245 return; 1246 } 1247 1248 // 2. GNU and similar 1249 const Driver &D = TC.getDriver(); 1250 const char *FortranMainLinkFlag = "-lFortran_main"; 1251 1252 // Warn if the user added `-lFortran_main` - this library is an implementation 1253 // detail of Flang and should be handled automaticaly by the driver. 1254 for (const char *arg : CmdArgs) { 1255 if (strncmp(arg, FortranMainLinkFlag, strlen(FortranMainLinkFlag)) == 0) 1256 D.Diag(diag::warn_drv_deprecated_custom) 1257 << FortranMainLinkFlag 1258 << "see the Flang driver documentation for correct usage"; 1259 } 1260 1261 // The --whole-archive option needs to be part of the link line to make 1262 // sure that the main() function from Fortran_main.a is pulled in by the 1263 // linker. However, it shouldn't be used if it's already active. 1264 // TODO: Find an equivalent of `--whole-archive` for Darwin and AIX. 1265 if (!isWholeArchivePresent(Args) && !TC.getTriple().isMacOSX() && 1266 !TC.getTriple().isOSAIX()) { 1267 CmdArgs.push_back("--whole-archive"); 1268 CmdArgs.push_back(FortranMainLinkFlag); 1269 CmdArgs.push_back("--no-whole-archive"); 1270 return; 1271 } 1272 1273 CmdArgs.push_back(FortranMainLinkFlag); 1274 } 1275 1276 /// Add Fortran runtime libs 1277 void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args, 1278 llvm::opt::ArgStringList &CmdArgs) { 1279 // 1. Link FortranMain 1280 // FortranMain depends on FortranRuntime, so needs to be listed first. If 1281 // -fno-fortran-main has been passed, skip linking Fortran_main.a 1282 if (!Args.hasArg(options::OPT_no_fortran_main)) 1283 addFortranMain(TC, Args, CmdArgs); 1284 1285 // 2. Link FortranRuntime and FortranDecimal 1286 // These are handled earlier on Windows by telling the frontend driver to 1287 // add the correct libraries to link against as dependents in the object 1288 // file. 1289 if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1290 CmdArgs.push_back("-lFortranRuntime"); 1291 CmdArgs.push_back("-lFortranDecimal"); 1292 } 1293 } 1294 1295 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC, 1296 const llvm::opt::ArgList &Args, 1297 ArgStringList &CmdArgs) { 1298 // Default to the <driver-path>/../lib directory. This works fine on the 1299 // platforms that we have tested so far. We will probably have to re-fine 1300 // this in the future. In particular, on some platforms, we may need to use 1301 // lib64 instead of lib. 1302 SmallString<256> DefaultLibPath = 1303 llvm::sys::path::parent_path(TC.getDriver().Dir); 1304 llvm::sys::path::append(DefaultLibPath, "lib"); 1305 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) 1306 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath)); 1307 else 1308 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath)); 1309 } 1310 1311 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 1312 ArgStringList &CmdArgs, StringRef Sanitizer, 1313 bool IsShared, bool IsWhole) { 1314 // Wrap any static runtimes that must be forced into executable in 1315 // whole-archive. 1316 if (IsWhole) CmdArgs.push_back("--whole-archive"); 1317 CmdArgs.push_back(TC.getCompilerRTArgString( 1318 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 1319 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 1320 1321 if (IsShared) { 1322 addArchSpecificRPath(TC, Args, CmdArgs); 1323 } 1324 } 1325 1326 // Tries to use a file with the list of dynamic symbols that need to be exported 1327 // from the runtime library. Returns true if the file was found. 1328 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 1329 ArgStringList &CmdArgs, 1330 StringRef Sanitizer) { 1331 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args); 1332 1333 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 1334 // the option, so don't try to pass it. 1335 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) 1336 return true; 1337 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 1338 if (llvm::sys::fs::exists(SanRT + ".syms")) { 1339 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 1340 return true; 1341 } 1342 return false; 1343 } 1344 1345 void tools::addAsNeededOption(const ToolChain &TC, 1346 const llvm::opt::ArgList &Args, 1347 llvm::opt::ArgStringList &CmdArgs, 1348 bool as_needed) { 1349 assert(!TC.getTriple().isOSAIX() && 1350 "AIX linker does not support any form of --as-needed option yet."); 1351 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args); 1352 1353 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases 1354 // for the native forms -z ignore/-z record, they are missing in Illumos, 1355 // so always use the native form. 1356 // GNU ld doesn't support -z ignore/-z record, so don't use them even on 1357 // Solaris. 1358 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) { 1359 CmdArgs.push_back("-z"); 1360 CmdArgs.push_back(as_needed ? "ignore" : "record"); 1361 } else { 1362 CmdArgs.push_back(as_needed ? "--as-needed" : "--no-as-needed"); 1363 } 1364 } 1365 1366 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 1367 const llvm::opt::ArgList &Args, 1368 ArgStringList &CmdArgs) { 1369 // Force linking against the system libraries sanitizers depends on 1370 // (see PR15823 why this is necessary). 1371 addAsNeededOption(TC, Args, CmdArgs, false); 1372 // There's no libpthread or librt on RTEMS & Android. 1373 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 1374 !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) { 1375 CmdArgs.push_back("-lpthread"); 1376 if (!TC.getTriple().isOSOpenBSD()) 1377 CmdArgs.push_back("-lrt"); 1378 } 1379 CmdArgs.push_back("-lm"); 1380 // There's no libdl on all OSes. 1381 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() && 1382 !TC.getTriple().isOSOpenBSD() && 1383 TC.getTriple().getOS() != llvm::Triple::RTEMS) 1384 CmdArgs.push_back("-ldl"); 1385 // Required for backtrace on some OSes 1386 if (TC.getTriple().isOSFreeBSD() || 1387 TC.getTriple().isOSNetBSD() || 1388 TC.getTriple().isOSOpenBSD()) 1389 CmdArgs.push_back("-lexecinfo"); 1390 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl 1391 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv 1392 // requirement. 1393 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() && 1394 !TC.getTriple().isMusl()) 1395 CmdArgs.push_back("-lresolv"); 1396 } 1397 1398 static void 1399 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 1400 SmallVectorImpl<StringRef> &SharedRuntimes, 1401 SmallVectorImpl<StringRef> &StaticRuntimes, 1402 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 1403 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 1404 SmallVectorImpl<StringRef> &RequiredSymbols) { 1405 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args); 1406 // Collect shared runtimes. 1407 if (SanArgs.needsSharedRt()) { 1408 if (SanArgs.needsAsanRt()) { 1409 SharedRuntimes.push_back("asan"); 1410 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 1411 HelperStaticRuntimes.push_back("asan-preinit"); 1412 } 1413 if (SanArgs.needsMemProfRt()) { 1414 SharedRuntimes.push_back("memprof"); 1415 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 1416 HelperStaticRuntimes.push_back("memprof-preinit"); 1417 } 1418 if (SanArgs.needsUbsanRt()) { 1419 if (SanArgs.requiresMinimalRuntime()) 1420 SharedRuntimes.push_back("ubsan_minimal"); 1421 else 1422 SharedRuntimes.push_back("ubsan_standalone"); 1423 } 1424 if (SanArgs.needsScudoRt()) { 1425 SharedRuntimes.push_back("scudo_standalone"); 1426 } 1427 if (SanArgs.needsTsanRt()) 1428 SharedRuntimes.push_back("tsan"); 1429 if (SanArgs.needsHwasanRt()) { 1430 if (SanArgs.needsHwasanAliasesRt()) 1431 SharedRuntimes.push_back("hwasan_aliases"); 1432 else 1433 SharedRuntimes.push_back("hwasan"); 1434 if (!Args.hasArg(options::OPT_shared)) 1435 HelperStaticRuntimes.push_back("hwasan-preinit"); 1436 } 1437 } 1438 1439 // The stats_client library is also statically linked into DSOs. 1440 if (SanArgs.needsStatsRt()) 1441 StaticRuntimes.push_back("stats_client"); 1442 1443 // Always link the static runtime regardless of DSO or executable. 1444 if (SanArgs.needsAsanRt()) 1445 HelperStaticRuntimes.push_back("asan_static"); 1446 1447 // Collect static runtimes. 1448 if (Args.hasArg(options::OPT_shared)) { 1449 // Don't link static runtimes into DSOs. 1450 return; 1451 } 1452 1453 // Each static runtime that has a DSO counterpart above is excluded below, 1454 // but runtimes that exist only as static are not affected by needsSharedRt. 1455 1456 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) { 1457 StaticRuntimes.push_back("asan"); 1458 if (SanArgs.linkCXXRuntimes()) 1459 StaticRuntimes.push_back("asan_cxx"); 1460 } 1461 1462 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) { 1463 StaticRuntimes.push_back("memprof"); 1464 if (SanArgs.linkCXXRuntimes()) 1465 StaticRuntimes.push_back("memprof_cxx"); 1466 } 1467 1468 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) { 1469 if (SanArgs.needsHwasanAliasesRt()) { 1470 StaticRuntimes.push_back("hwasan_aliases"); 1471 if (SanArgs.linkCXXRuntimes()) 1472 StaticRuntimes.push_back("hwasan_aliases_cxx"); 1473 } else { 1474 StaticRuntimes.push_back("hwasan"); 1475 if (SanArgs.linkCXXRuntimes()) 1476 StaticRuntimes.push_back("hwasan_cxx"); 1477 } 1478 } 1479 if (SanArgs.needsDfsanRt()) 1480 StaticRuntimes.push_back("dfsan"); 1481 if (SanArgs.needsLsanRt()) 1482 StaticRuntimes.push_back("lsan"); 1483 if (SanArgs.needsMsanRt()) { 1484 StaticRuntimes.push_back("msan"); 1485 if (SanArgs.linkCXXRuntimes()) 1486 StaticRuntimes.push_back("msan_cxx"); 1487 } 1488 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) { 1489 StaticRuntimes.push_back("tsan"); 1490 if (SanArgs.linkCXXRuntimes()) 1491 StaticRuntimes.push_back("tsan_cxx"); 1492 } 1493 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) { 1494 if (SanArgs.requiresMinimalRuntime()) { 1495 StaticRuntimes.push_back("ubsan_minimal"); 1496 } else { 1497 StaticRuntimes.push_back("ubsan_standalone"); 1498 if (SanArgs.linkCXXRuntimes()) 1499 StaticRuntimes.push_back("ubsan_standalone_cxx"); 1500 } 1501 } 1502 if (SanArgs.needsSafeStackRt()) { 1503 NonWholeStaticRuntimes.push_back("safestack"); 1504 RequiredSymbols.push_back("__safestack_init"); 1505 } 1506 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) { 1507 if (SanArgs.needsCfiRt()) 1508 StaticRuntimes.push_back("cfi"); 1509 if (SanArgs.needsCfiDiagRt()) { 1510 StaticRuntimes.push_back("cfi_diag"); 1511 if (SanArgs.linkCXXRuntimes()) 1512 StaticRuntimes.push_back("ubsan_standalone_cxx"); 1513 } 1514 } 1515 if (SanArgs.needsStatsRt()) { 1516 NonWholeStaticRuntimes.push_back("stats"); 1517 RequiredSymbols.push_back("__sanitizer_stats_register"); 1518 } 1519 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) { 1520 StaticRuntimes.push_back("scudo_standalone"); 1521 if (SanArgs.linkCXXRuntimes()) 1522 StaticRuntimes.push_back("scudo_standalone_cxx"); 1523 } 1524 } 1525 1526 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 1527 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 1528 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 1529 ArgStringList &CmdArgs) { 1530 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args); 1531 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 1532 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 1533 if (SanArgs.linkRuntimes()) { 1534 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 1535 NonWholeStaticRuntimes, HelperStaticRuntimes, 1536 RequiredSymbols); 1537 } 1538 1539 // Inject libfuzzer dependencies. 1540 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 1541 !Args.hasArg(options::OPT_shared)) { 1542 1543 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 1544 if (SanArgs.needsFuzzerInterceptors()) 1545 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false, 1546 true); 1547 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) { 1548 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && 1549 !Args.hasArg(options::OPT_static); 1550 if (OnlyLibstdcxxStatic) 1551 CmdArgs.push_back("-Bstatic"); 1552 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 1553 if (OnlyLibstdcxxStatic) 1554 CmdArgs.push_back("-Bdynamic"); 1555 } 1556 } 1557 1558 for (auto RT : SharedRuntimes) 1559 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 1560 for (auto RT : HelperStaticRuntimes) 1561 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 1562 bool AddExportDynamic = false; 1563 for (auto RT : StaticRuntimes) { 1564 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 1565 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 1566 } 1567 for (auto RT : NonWholeStaticRuntimes) { 1568 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 1569 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 1570 } 1571 for (auto S : RequiredSymbols) { 1572 CmdArgs.push_back("-u"); 1573 CmdArgs.push_back(Args.MakeArgString(S)); 1574 } 1575 // If there is a static runtime with no dynamic list, force all the symbols 1576 // to be dynamic to be sure we export sanitizer interface functions. 1577 if (AddExportDynamic) 1578 CmdArgs.push_back("--export-dynamic"); 1579 1580 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 1581 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check"); 1582 1583 if (SanArgs.hasMemTag()) { 1584 if (!TC.getTriple().isAndroid()) { 1585 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1586 << "-fsanitize=memtag*" << TC.getTriple().str(); 1587 } 1588 CmdArgs.push_back( 1589 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode())); 1590 if (SanArgs.hasMemtagHeap()) 1591 CmdArgs.push_back("--android-memtag-heap"); 1592 if (SanArgs.hasMemtagStack()) 1593 CmdArgs.push_back("--android-memtag-stack"); 1594 } 1595 1596 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 1597 } 1598 1599 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 1600 if (Args.hasArg(options::OPT_shared)) 1601 return false; 1602 1603 if (TC.getXRayArgs().needsXRayRt()) { 1604 CmdArgs.push_back("--whole-archive"); 1605 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 1606 for (const auto &Mode : TC.getXRayArgs().modeList()) 1607 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 1608 CmdArgs.push_back("--no-whole-archive"); 1609 return true; 1610 } 1611 1612 return false; 1613 } 1614 1615 void tools::linkXRayRuntimeDeps(const ToolChain &TC, 1616 const llvm::opt::ArgList &Args, 1617 ArgStringList &CmdArgs) { 1618 addAsNeededOption(TC, Args, CmdArgs, false); 1619 CmdArgs.push_back("-lpthread"); 1620 if (!TC.getTriple().isOSOpenBSD()) 1621 CmdArgs.push_back("-lrt"); 1622 CmdArgs.push_back("-lm"); 1623 1624 if (!TC.getTriple().isOSFreeBSD() && 1625 !TC.getTriple().isOSNetBSD() && 1626 !TC.getTriple().isOSOpenBSD()) 1627 CmdArgs.push_back("-ldl"); 1628 } 1629 1630 bool tools::areOptimizationsEnabled(const ArgList &Args) { 1631 // Find the last -O arg and see if it is non-zero. 1632 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 1633 return !A->getOption().matches(options::OPT_O0); 1634 // Defaults to -O0. 1635 return false; 1636 } 1637 1638 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args, 1639 const InputInfo &Input, 1640 const InputInfo &Output) { 1641 auto AddPostfix = [JA](auto &F) { 1642 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP) 1643 F += (Twine("_") + JA.getOffloadingArch()).str(); 1644 F += ".dwo"; 1645 }; 1646 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 1647 if (StringRef(A->getValue()) == "single" && Output.isFilename()) 1648 return Args.MakeArgString(Output.getFilename()); 1649 1650 SmallString<128> T; 1651 if (const Arg *A = Args.getLastArg(options::OPT_dumpdir)) { 1652 T = A->getValue(); 1653 } else { 1654 Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o); 1655 if (FinalOutput && Args.hasArg(options::OPT_c)) { 1656 T = FinalOutput->getValue(); 1657 llvm::sys::path::remove_filename(T); 1658 llvm::sys::path::append(T, 1659 llvm::sys::path::stem(FinalOutput->getValue())); 1660 AddPostfix(T); 1661 return Args.MakeArgString(T); 1662 } 1663 } 1664 1665 T += llvm::sys::path::stem(Input.getBaseInput()); 1666 AddPostfix(T); 1667 return Args.MakeArgString(T); 1668 } 1669 1670 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 1671 const JobAction &JA, const ArgList &Args, 1672 const InputInfo &Output, const char *OutFile) { 1673 ArgStringList ExtractArgs; 1674 ExtractArgs.push_back("--extract-dwo"); 1675 1676 ArgStringList StripArgs; 1677 StripArgs.push_back("--strip-dwo"); 1678 1679 // Grabbing the output of the earlier compile step. 1680 StripArgs.push_back(Output.getFilename()); 1681 ExtractArgs.push_back(Output.getFilename()); 1682 ExtractArgs.push_back(OutFile); 1683 1684 const char *Exec = 1685 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 1686 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 1687 1688 // First extract the dwo sections. 1689 C.addCommand(std::make_unique<Command>(JA, T, 1690 ResponseFileSupport::AtFileCurCP(), 1691 Exec, ExtractArgs, II, Output)); 1692 1693 // Then remove them from the original .o file. 1694 C.addCommand(std::make_unique<Command>( 1695 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output)); 1696 } 1697 1698 // Claim options we don't want to warn if they are unused. We do this for 1699 // options that build systems might add but are unused when assembling or only 1700 // running the preprocessor for example. 1701 void tools::claimNoWarnArgs(const ArgList &Args) { 1702 // Don't warn about unused -f(no-)?lto. This can happen when we're 1703 // preprocessing, precompiling or assembling. 1704 Args.ClaimAllArgs(options::OPT_flto_EQ); 1705 Args.ClaimAllArgs(options::OPT_flto); 1706 Args.ClaimAllArgs(options::OPT_fno_lto); 1707 } 1708 1709 Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) { 1710 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 1711 options::OPT_fcs_profile_generate_EQ, 1712 options::OPT_fno_profile_generate); 1713 if (CSPGOGenerateArg && 1714 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 1715 CSPGOGenerateArg = nullptr; 1716 1717 return CSPGOGenerateArg; 1718 } 1719 1720 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 1721 auto *ProfileUseArg = Args.getLastArg( 1722 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 1723 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 1724 options::OPT_fno_profile_instr_use); 1725 1726 if (ProfileUseArg && 1727 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 1728 ProfileUseArg = nullptr; 1729 1730 return ProfileUseArg; 1731 } 1732 1733 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 1734 auto *ProfileSampleUseArg = Args.getLastArg( 1735 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 1736 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 1737 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 1738 1739 if (ProfileSampleUseArg && 1740 (ProfileSampleUseArg->getOption().matches( 1741 options::OPT_fno_profile_sample_use) || 1742 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 1743 return nullptr; 1744 1745 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 1746 options::OPT_fauto_profile_EQ); 1747 } 1748 1749 const char *tools::RelocationModelName(llvm::Reloc::Model Model) { 1750 switch (Model) { 1751 case llvm::Reloc::Static: 1752 return "static"; 1753 case llvm::Reloc::PIC_: 1754 return "pic"; 1755 case llvm::Reloc::DynamicNoPIC: 1756 return "dynamic-no-pic"; 1757 case llvm::Reloc::ROPI: 1758 return "ropi"; 1759 case llvm::Reloc::RWPI: 1760 return "rwpi"; 1761 case llvm::Reloc::ROPI_RWPI: 1762 return "ropi-rwpi"; 1763 } 1764 llvm_unreachable("Unknown Reloc::Model kind"); 1765 } 1766 1767 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 1768 /// smooshes them together with platform defaults, to decide whether 1769 /// this compile should be using PIC mode or not. Returns a tuple of 1770 /// (RelocationModel, PICLevel, IsPIE). 1771 std::tuple<llvm::Reloc::Model, unsigned, bool> 1772 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 1773 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 1774 const llvm::Triple &Triple = ToolChain.getTriple(); 1775 1776 bool PIE = ToolChain.isPIEDefault(Args); 1777 bool PIC = PIE || ToolChain.isPICDefault(); 1778 // The Darwin/MachO default to use PIC does not apply when using -static. 1779 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 1780 PIE = PIC = false; 1781 bool IsPICLevelTwo = PIC; 1782 1783 bool KernelOrKext = 1784 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 1785 1786 // Android-specific defaults for PIC/PIE 1787 if (Triple.isAndroid()) { 1788 switch (Triple.getArch()) { 1789 case llvm::Triple::arm: 1790 case llvm::Triple::armeb: 1791 case llvm::Triple::thumb: 1792 case llvm::Triple::thumbeb: 1793 case llvm::Triple::aarch64: 1794 case llvm::Triple::mips: 1795 case llvm::Triple::mipsel: 1796 case llvm::Triple::mips64: 1797 case llvm::Triple::mips64el: 1798 PIC = true; // "-fpic" 1799 break; 1800 1801 case llvm::Triple::x86: 1802 case llvm::Triple::x86_64: 1803 PIC = true; // "-fPIC" 1804 IsPICLevelTwo = true; 1805 break; 1806 1807 default: 1808 break; 1809 } 1810 } 1811 1812 // OHOS-specific defaults for PIC/PIE 1813 if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64) 1814 PIC = true; 1815 1816 // OpenBSD-specific defaults for PIE 1817 if (Triple.isOSOpenBSD()) { 1818 switch (ToolChain.getArch()) { 1819 case llvm::Triple::arm: 1820 case llvm::Triple::aarch64: 1821 case llvm::Triple::mips64: 1822 case llvm::Triple::mips64el: 1823 case llvm::Triple::x86: 1824 case llvm::Triple::x86_64: 1825 IsPICLevelTwo = false; // "-fpie" 1826 break; 1827 1828 case llvm::Triple::ppc: 1829 case llvm::Triple::sparcv9: 1830 IsPICLevelTwo = true; // "-fPIE" 1831 break; 1832 1833 default: 1834 break; 1835 } 1836 } 1837 1838 // The last argument relating to either PIC or PIE wins, and no 1839 // other argument is used. If the last argument is any flavor of the 1840 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 1841 // option implicitly enables PIC at the same level. 1842 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 1843 options::OPT_fpic, options::OPT_fno_pic, 1844 options::OPT_fPIE, options::OPT_fno_PIE, 1845 options::OPT_fpie, options::OPT_fno_pie); 1846 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg && 1847 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 1848 options::OPT_fPIE, options::OPT_fpie)) { 1849 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1850 << LastPICArg->getSpelling() << Triple.str(); 1851 if (Triple.getArch() == llvm::Triple::x86_64) 1852 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 1853 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1854 } 1855 1856 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 1857 // is forced, then neither PIC nor PIE flags will have no effect. 1858 if (!ToolChain.isPICDefaultForced()) { 1859 if (LastPICArg) { 1860 Option O = LastPICArg->getOption(); 1861 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 1862 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 1863 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1864 PIC = 1865 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1866 IsPICLevelTwo = 1867 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1868 } else { 1869 PIE = PIC = false; 1870 if (EffectiveTriple.isPS()) { 1871 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1872 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1873 if (Model != "kernel") { 1874 PIC = true; 1875 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic) 1876 << LastPICArg->getSpelling() 1877 << (EffectiveTriple.isPS4() ? "PS4" : "PS5"); 1878 } 1879 } 1880 } 1881 } 1882 } 1883 1884 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but 1885 // the PIC level would've been set to level 1, force it back to level 2 PIC 1886 // instead. 1887 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS())) 1888 IsPICLevelTwo |= ToolChain.isPICDefault(); 1889 1890 // This kernel flags are a trump-card: they will disable PIC/PIE 1891 // generation, independent of the argument order. 1892 if (KernelOrKext && 1893 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1894 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit())) 1895 PIC = PIE = false; 1896 1897 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1898 // This is a very special mode. It trumps the other modes, almost no one 1899 // uses it, and it isn't even valid on any OS but Darwin. 1900 if (!Triple.isOSDarwin()) 1901 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1902 << A->getSpelling() << Triple.str(); 1903 1904 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1905 1906 // Only a forced PIC mode can cause the actual compile to have PIC defines 1907 // etc., no flags are sufficient. This behavior was selected to closely 1908 // match that of llvm-gcc and Apple GCC before that. 1909 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1910 1911 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1912 } 1913 1914 bool EmbeddedPISupported; 1915 switch (Triple.getArch()) { 1916 case llvm::Triple::arm: 1917 case llvm::Triple::armeb: 1918 case llvm::Triple::thumb: 1919 case llvm::Triple::thumbeb: 1920 EmbeddedPISupported = true; 1921 break; 1922 default: 1923 EmbeddedPISupported = false; 1924 break; 1925 } 1926 1927 bool ROPI = false, RWPI = false; 1928 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1929 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1930 if (!EmbeddedPISupported) 1931 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1932 << LastROPIArg->getSpelling() << Triple.str(); 1933 ROPI = true; 1934 } 1935 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1936 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1937 if (!EmbeddedPISupported) 1938 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1939 << LastRWPIArg->getSpelling() << Triple.str(); 1940 RWPI = true; 1941 } 1942 1943 // ROPI and RWPI are not compatible with PIC or PIE. 1944 if ((ROPI || RWPI) && (PIC || PIE)) 1945 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1946 1947 if (Triple.isMIPS()) { 1948 StringRef CPUName; 1949 StringRef ABIName; 1950 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1951 // When targeting the N64 ABI, PIC is the default, except in the case 1952 // when the -mno-abicalls option is used. In that case we exit 1953 // at next check regardless of PIC being set below. 1954 if (ABIName == "n64") 1955 PIC = true; 1956 // When targettng MIPS with -mno-abicalls, it's always static. 1957 if(Args.hasArg(options::OPT_mno_abicalls)) 1958 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1959 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1960 // does not use PIC level 2 for historical reasons. 1961 IsPICLevelTwo = false; 1962 } 1963 1964 if (PIC) 1965 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1966 1967 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1968 if (ROPI && RWPI) 1969 RelocM = llvm::Reloc::ROPI_RWPI; 1970 else if (ROPI) 1971 RelocM = llvm::Reloc::ROPI; 1972 else if (RWPI) 1973 RelocM = llvm::Reloc::RWPI; 1974 1975 return std::make_tuple(RelocM, 0U, false); 1976 } 1977 1978 // `-falign-functions` indicates that the functions should be aligned to a 1979 // 16-byte boundary. 1980 // 1981 // `-falign-functions=1` is the same as `-fno-align-functions`. 1982 // 1983 // The scalar `n` in `-falign-functions=n` must be an integral value between 1984 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1985 // the nearest power-of-two. 1986 // 1987 // If we return `0`, the frontend will default to the backend's preferred 1988 // alignment. 1989 // 1990 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1991 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1992 // alignment. For unaligned functions, we default to the backend's preferred 1993 // alignment. 1994 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1995 const ArgList &Args) { 1996 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1997 options::OPT_falign_functions_EQ, 1998 options::OPT_fno_align_functions); 1999 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 2000 return 0; 2001 2002 if (A->getOption().matches(options::OPT_falign_functions)) 2003 return 0; 2004 2005 unsigned Value = 0; 2006 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 2007 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 2008 << A->getAsString(Args) << A->getValue(); 2009 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 2010 } 2011 2012 void tools::addDebugInfoKind( 2013 ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) { 2014 switch (DebugInfoKind) { 2015 case llvm::codegenoptions::DebugDirectivesOnly: 2016 CmdArgs.push_back("-debug-info-kind=line-directives-only"); 2017 break; 2018 case llvm::codegenoptions::DebugLineTablesOnly: 2019 CmdArgs.push_back("-debug-info-kind=line-tables-only"); 2020 break; 2021 case llvm::codegenoptions::DebugInfoConstructor: 2022 CmdArgs.push_back("-debug-info-kind=constructor"); 2023 break; 2024 case llvm::codegenoptions::LimitedDebugInfo: 2025 CmdArgs.push_back("-debug-info-kind=limited"); 2026 break; 2027 case llvm::codegenoptions::FullDebugInfo: 2028 CmdArgs.push_back("-debug-info-kind=standalone"); 2029 break; 2030 case llvm::codegenoptions::UnusedTypeInfo: 2031 CmdArgs.push_back("-debug-info-kind=unused-types"); 2032 break; 2033 default: 2034 break; 2035 } 2036 } 2037 2038 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases 2039 // to the corresponding DebugInfoKind. 2040 llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) { 2041 assert(A.getOption().matches(options::OPT_gN_Group) && 2042 "Not a -g option that specifies a debug-info level"); 2043 if (A.getOption().matches(options::OPT_g0) || 2044 A.getOption().matches(options::OPT_ggdb0)) 2045 return llvm::codegenoptions::NoDebugInfo; 2046 if (A.getOption().matches(options::OPT_gline_tables_only) || 2047 A.getOption().matches(options::OPT_ggdb1)) 2048 return llvm::codegenoptions::DebugLineTablesOnly; 2049 if (A.getOption().matches(options::OPT_gline_directives_only)) 2050 return llvm::codegenoptions::DebugDirectivesOnly; 2051 return llvm::codegenoptions::DebugInfoConstructor; 2052 } 2053 2054 static unsigned ParseDebugDefaultVersion(const ToolChain &TC, 2055 const ArgList &Args) { 2056 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 2057 2058 if (!A) 2059 return 0; 2060 2061 unsigned Value = 0; 2062 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 2063 Value < 2) 2064 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 2065 << A->getAsString(Args) << A->getValue(); 2066 return Value; 2067 } 2068 2069 unsigned tools::DwarfVersionNum(StringRef ArgValue) { 2070 return llvm::StringSwitch<unsigned>(ArgValue) 2071 .Case("-gdwarf-2", 2) 2072 .Case("-gdwarf-3", 3) 2073 .Case("-gdwarf-4", 4) 2074 .Case("-gdwarf-5", 5) 2075 .Default(0); 2076 } 2077 2078 const Arg *tools::getDwarfNArg(const ArgList &Args) { 2079 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3, 2080 options::OPT_gdwarf_4, options::OPT_gdwarf_5, 2081 options::OPT_gdwarf); 2082 } 2083 2084 unsigned tools::getDwarfVersion(const ToolChain &TC, 2085 const llvm::opt::ArgList &Args) { 2086 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args); 2087 if (const Arg *GDwarfN = getDwarfNArg(Args)) 2088 if (int N = DwarfVersionNum(GDwarfN->getSpelling())) 2089 DwarfVersion = N; 2090 if (DwarfVersion == 0) { 2091 DwarfVersion = TC.GetDefaultDwarfVersion(); 2092 assert(DwarfVersion && "toolchain default DWARF version must be nonzero"); 2093 } 2094 return DwarfVersion; 2095 } 2096 2097 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 2098 ArgStringList &CmdArgs) { 2099 llvm::Reloc::Model RelocationModel; 2100 unsigned PICLevel; 2101 bool IsPIE; 2102 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 2103 2104 if (RelocationModel != llvm::Reloc::Static) 2105 CmdArgs.push_back("-KPIC"); 2106 } 2107 2108 /// Determine whether Objective-C automated reference counting is 2109 /// enabled. 2110 bool tools::isObjCAutoRefCount(const ArgList &Args) { 2111 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 2112 } 2113 2114 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 2115 2116 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, 2117 const ArgList &Args) { 2118 if (Args.hasArg(options::OPT_static_libgcc) || 2119 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) || 2120 // The Android NDK only provides libunwind.a, not libunwind.so. 2121 TC.getTriple().isAndroid()) 2122 return LibGccType::StaticLibGcc; 2123 if (Args.hasArg(options::OPT_shared_libgcc)) 2124 return LibGccType::SharedLibGcc; 2125 return LibGccType::UnspecifiedLibGcc; 2126 } 2127 2128 // Gcc adds libgcc arguments in various ways: 2129 // 2130 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 2131 // g++ <none>: -lgcc_s -lgcc 2132 // gcc shared: -lgcc_s -lgcc 2133 // g++ shared: -lgcc_s -lgcc 2134 // gcc static: -lgcc -lgcc_eh 2135 // g++ static: -lgcc -lgcc_eh 2136 // gcc static-pie: -lgcc -lgcc_eh 2137 // g++ static-pie: -lgcc -lgcc_eh 2138 // 2139 // Also, certain targets need additional adjustments. 2140 2141 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 2142 ArgStringList &CmdArgs, const ArgList &Args) { 2143 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 2144 // By default OHOS binaries are linked statically to libunwind. 2145 if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) { 2146 CmdArgs.push_back("-l:libunwind.a"); 2147 return; 2148 } 2149 2150 // Targets that don't use unwind libraries. 2151 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || 2152 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || 2153 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None) 2154 return; 2155 2156 LibGccType LGT = getLibGccType(TC, D, Args); 2157 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 2158 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) && 2159 !TC.getTriple().isAndroid() && 2160 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX(); 2161 if (AsNeeded) 2162 addAsNeededOption(TC, Args, CmdArgs, true); 2163 2164 switch (UNW) { 2165 case ToolChain::UNW_None: 2166 return; 2167 case ToolChain::UNW_Libgcc: { 2168 if (LGT == LibGccType::StaticLibGcc) 2169 CmdArgs.push_back("-lgcc_eh"); 2170 else 2171 CmdArgs.push_back("-lgcc_s"); 2172 break; 2173 } 2174 case ToolChain::UNW_CompilerRT: 2175 if (TC.getTriple().isOSAIX()) { 2176 // AIX only has libunwind as a shared library. So do not pass 2177 // anything in if -static is specified. 2178 if (LGT != LibGccType::StaticLibGcc) 2179 CmdArgs.push_back("-lunwind"); 2180 } else if (LGT == LibGccType::StaticLibGcc) { 2181 CmdArgs.push_back("-l:libunwind.a"); 2182 } else if (LGT == LibGccType::SharedLibGcc) { 2183 if (TC.getTriple().isOSCygMing()) 2184 CmdArgs.push_back("-l:libunwind.dll.a"); 2185 else 2186 CmdArgs.push_back("-l:libunwind.so"); 2187 } else { 2188 // Let the linker choose between libunwind.so and libunwind.a 2189 // depending on what's available, and depending on the -static flag 2190 CmdArgs.push_back("-lunwind"); 2191 } 2192 break; 2193 } 2194 2195 if (AsNeeded) 2196 addAsNeededOption(TC, Args, CmdArgs, false); 2197 } 2198 2199 static void AddLibgcc(const ToolChain &TC, const Driver &D, 2200 ArgStringList &CmdArgs, const ArgList &Args) { 2201 LibGccType LGT = getLibGccType(TC, D, Args); 2202 if (LGT == LibGccType::StaticLibGcc || 2203 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX())) 2204 CmdArgs.push_back("-lgcc"); 2205 AddUnwindLibrary(TC, D, CmdArgs, Args); 2206 if (LGT == LibGccType::SharedLibGcc || 2207 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX())) 2208 CmdArgs.push_back("-lgcc"); 2209 } 2210 2211 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 2212 ArgStringList &CmdArgs, const ArgList &Args) { 2213 // Make use of compiler-rt if --rtlib option is used 2214 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 2215 2216 switch (RLT) { 2217 case ToolChain::RLT_CompilerRT: 2218 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 2219 AddUnwindLibrary(TC, D, CmdArgs, Args); 2220 break; 2221 case ToolChain::RLT_Libgcc: 2222 // Make sure libgcc is not used under MSVC environment by default 2223 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 2224 // Issue error diagnostic if libgcc is explicitly specified 2225 // through command line as --rtlib option argument. 2226 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ); 2227 if (A && A->getValue() != StringRef("platform")) { 2228 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 2229 << A->getValue() << "MSVC"; 2230 } 2231 } else 2232 AddLibgcc(TC, D, CmdArgs, Args); 2233 break; 2234 } 2235 2236 // On Android, the unwinder uses dl_iterate_phdr (or one of 2237 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For 2238 // statically-linked executables, these functions come from libc.a instead. 2239 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) && 2240 !Args.hasArg(options::OPT_static_pie)) 2241 CmdArgs.push_back("-ldl"); 2242 } 2243 2244 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 2245 const InputInfo &Output, 2246 const InputInfo &Input, 2247 const Driver &D) { 2248 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 2249 if (!A && !D.CCPrintInternalStats) 2250 return {}; 2251 2252 SmallString<128> StatsFile; 2253 if (A) { 2254 StringRef SaveStats = A->getValue(); 2255 if (SaveStats == "obj" && Output.isFilename()) { 2256 StatsFile.assign(Output.getFilename()); 2257 llvm::sys::path::remove_filename(StatsFile); 2258 } else if (SaveStats != "cwd") { 2259 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 2260 return {}; 2261 } 2262 2263 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 2264 llvm::sys::path::append(StatsFile, BaseName); 2265 llvm::sys::path::replace_extension(StatsFile, "stats"); 2266 } else { 2267 assert(D.CCPrintInternalStats); 2268 StatsFile.assign(D.CCPrintInternalStatReportFilename.empty() 2269 ? "-" 2270 : D.CCPrintInternalStatReportFilename); 2271 } 2272 return StatsFile; 2273 } 2274 2275 void tools::addMultilibFlag(bool Enabled, const StringRef Flag, 2276 Multilib::flags_list &Flags) { 2277 assert(Flag.front() == '-'); 2278 if (Enabled) { 2279 Flags.push_back(Flag.str()); 2280 } else { 2281 Flags.push_back(("!" + Flag.substr(1)).str()); 2282 } 2283 } 2284 2285 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, 2286 ArgStringList &CmdArgs, bool IsLTO, 2287 const StringRef PluginOptPrefix) { 2288 auto addArg = [&, IsLTO](const Twine &Arg) { 2289 if (IsLTO) { 2290 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!"); 2291 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg)); 2292 } else { 2293 CmdArgs.push_back("-mllvm"); 2294 CmdArgs.push_back(Args.MakeArgString(Arg)); 2295 } 2296 }; 2297 2298 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) { 2299 addArg(Twine("-x86-branches-within-32B-boundaries")); 2300 } 2301 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) { 2302 StringRef Value = A->getValue(); 2303 unsigned Boundary; 2304 if (Value.getAsInteger(10, Boundary) || Boundary < 16 || 2305 !llvm::isPowerOf2_64(Boundary)) { 2306 D.Diag(diag::err_drv_invalid_argument_to_option) 2307 << Value << A->getOption().getName(); 2308 } else { 2309 addArg("-x86-align-branch-boundary=" + Twine(Boundary)); 2310 } 2311 } 2312 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) { 2313 std::string AlignBranch; 2314 for (StringRef T : A->getValues()) { 2315 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && 2316 T != "ret" && T != "indirect") 2317 D.Diag(diag::err_drv_invalid_malign_branch_EQ) 2318 << T << "fused, jcc, jmp, call, ret, indirect"; 2319 if (!AlignBranch.empty()) 2320 AlignBranch += '+'; 2321 AlignBranch += T; 2322 } 2323 addArg("-x86-align-branch=" + Twine(AlignBranch)); 2324 } 2325 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) { 2326 StringRef Value = A->getValue(); 2327 unsigned PrefixSize; 2328 if (Value.getAsInteger(10, PrefixSize)) { 2329 D.Diag(diag::err_drv_invalid_argument_to_option) 2330 << Value << A->getOption().getName(); 2331 } else { 2332 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); 2333 } 2334 } 2335 } 2336 2337 /// SDLSearch: Search for Static Device Library 2338 /// The search for SDL bitcode files is consistent with how static host 2339 /// libraries are discovered. That is, the -l option triggers a search for 2340 /// files in a set of directories called the LINKPATH. The host library search 2341 /// procedure looks for a specific filename in the LINKPATH. The filename for 2342 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an 2343 /// ordered-set of filenames that are searched. We call this ordered-set of 2344 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific, 2345 /// architecture specific, or generic across all architectures, a naming 2346 /// convention and search order is used where the file name embeds the 2347 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type 2348 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of 2349 /// device-independent SDLs. To reduce congestion in host library directories, 2350 /// the search first looks for files in the “libdevice” subdirectory. SDLs that 2351 /// are bc files begin with the prefix “lib”. 2352 /// 2353 /// Machine-code SDLs can also be managed as an archive (*.a file). The 2354 /// convention has been to use the prefix “lib”. To avoid confusion with host 2355 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives. 2356 /// 2357 static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs, 2358 llvm::opt::ArgStringList &CC1Args, 2359 const SmallVectorImpl<std::string> &LibraryPaths, 2360 StringRef Lib, StringRef Arch, StringRef Target, 2361 bool isBitCodeSDL) { 2362 SmallVector<std::string, 12> SDLs; 2363 2364 std::string LibDeviceLoc = "/libdevice"; 2365 std::string LibBcPrefix = "/libbc-"; 2366 std::string LibPrefix = "/lib"; 2367 2368 if (isBitCodeSDL) { 2369 // SEARCH-ORDER for Bitcode SDLs: 2370 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a 2371 // libbc-<libname>-<arch-name>-<device-type>.a 2372 // libdevice/libbc-<libname>-<arch-name>.a 2373 // libbc-<libname>-<arch-name>.a 2374 // libdevice/libbc-<libname>.a 2375 // libbc-<libname>.a 2376 // libdevice/lib<libname>-<arch-name>-<device-type>.bc 2377 // lib<libname>-<arch-name>-<device-type>.bc 2378 // libdevice/lib<libname>-<arch-name>.bc 2379 // lib<libname>-<arch-name>.bc 2380 // libdevice/lib<libname>.bc 2381 // lib<libname>.bc 2382 2383 for (StringRef Base : {LibBcPrefix, LibPrefix}) { 2384 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc"; 2385 2386 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), 2387 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) { 2388 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str()); 2389 SDLs.push_back(Twine(Base + Suffix + Ext).str()); 2390 } 2391 } 2392 } else { 2393 // SEARCH-ORDER for Machine-code SDLs: 2394 // libdevice/lib<libname>-<arch-name>-<device-type>.a 2395 // lib<libname>-<arch-name>-<device-type>.a 2396 // libdevice/lib<libname>-<arch-name>.a 2397 // lib<libname>-<arch-name>.a 2398 2399 const auto *Ext = ".a"; 2400 2401 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), 2402 Twine(Lib + "-" + Arch).str()}) { 2403 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str()); 2404 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str()); 2405 } 2406 } 2407 2408 // The CUDA toolchain does not use a global device llvm-link before the LLVM 2409 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is 2410 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that 2411 // will link libraries after clang compilation while the LLVM IR is still in 2412 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”. 2413 // This is a clang -cc1 option that is generated by the clang driver. The 2414 // option value must a full path to an existing file. 2415 bool FoundSDL = false; 2416 for (auto LPath : LibraryPaths) { 2417 for (auto SDL : SDLs) { 2418 auto FullName = Twine(LPath + SDL).str(); 2419 if (llvm::sys::fs::exists(FullName)) { 2420 CC1Args.push_back(DriverArgs.MakeArgString(FullName)); 2421 FoundSDL = true; 2422 break; 2423 } 2424 } 2425 if (FoundSDL) 2426 break; 2427 } 2428 return FoundSDL; 2429 } 2430 2431 /// Search if a user provided archive file lib<libname>.a exists in any of 2432 /// the library paths. If so, add a new command to clang-offload-bundler to 2433 /// unbundle this archive and create a temporary device specific archive. Name 2434 /// of this SDL is passed to the llvm-link tool. 2435 static void GetSDLFromOffloadArchive( 2436 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA, 2437 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, 2438 llvm::opt::ArgStringList &CC1Args, 2439 const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib, 2440 StringRef Arch, StringRef Target, bool isBitCodeSDL) { 2441 2442 // We don't support bitcode archive bundles for nvptx 2443 if (isBitCodeSDL && Arch.contains("nvptx")) 2444 return; 2445 2446 bool FoundAOB = false; 2447 std::string ArchiveOfBundles; 2448 2449 llvm::Triple Triple(D.getTargetTriple()); 2450 bool IsMSVC = Triple.isWindowsMSVCEnvironment(); 2451 auto Ext = IsMSVC ? ".lib" : ".a"; 2452 if (!Lib.starts_with(":") && !Lib.starts_with("-l")) { 2453 if (llvm::sys::fs::exists(Lib)) { 2454 ArchiveOfBundles = Lib; 2455 FoundAOB = true; 2456 } 2457 } else { 2458 Lib.consume_front("-l"); 2459 for (auto LPath : LibraryPaths) { 2460 ArchiveOfBundles.clear(); 2461 auto LibFile = (Lib.starts_with(":") ? Lib.drop_front() 2462 : IsMSVC ? Lib + Ext 2463 : "lib" + Lib + Ext) 2464 .str(); 2465 for (auto Prefix : {"/libdevice/", "/"}) { 2466 auto AOB = Twine(LPath + Prefix + LibFile).str(); 2467 if (llvm::sys::fs::exists(AOB)) { 2468 ArchiveOfBundles = AOB; 2469 FoundAOB = true; 2470 break; 2471 } 2472 } 2473 if (FoundAOB) 2474 break; 2475 } 2476 } 2477 2478 if (!FoundAOB) 2479 return; 2480 2481 llvm::file_magic Magic; 2482 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic); 2483 if (EC || Magic != llvm::file_magic::archive) 2484 return; 2485 2486 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib"; 2487 std::string OutputLib = 2488 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" + 2489 Arch + "-" + Target) 2490 .str(), 2491 "a"); 2492 2493 C.addTempFile(C.getArgs().MakeArgString(OutputLib)); 2494 2495 ArgStringList CmdArgs; 2496 SmallString<128> DeviceTriple; 2497 DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind()); 2498 DeviceTriple += '-'; 2499 std::string NormalizedTriple = T.getToolChain().getTriple().normalize(); 2500 DeviceTriple += NormalizedTriple; 2501 if (!Target.empty()) { 2502 DeviceTriple += '-'; 2503 DeviceTriple += Target; 2504 } 2505 2506 std::string UnbundleArg("-unbundle"); 2507 std::string TypeArg("-type=a"); 2508 std::string InputArg("-input=" + ArchiveOfBundles); 2509 std::string OffloadArg("-targets=" + std::string(DeviceTriple)); 2510 std::string OutputArg("-output=" + OutputLib); 2511 2512 const char *UBProgram = DriverArgs.MakeArgString( 2513 T.getToolChain().GetProgramPath("clang-offload-bundler")); 2514 2515 ArgStringList UBArgs; 2516 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg)); 2517 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg)); 2518 UBArgs.push_back(C.getArgs().MakeArgString(InputArg)); 2519 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg)); 2520 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg)); 2521 2522 // Add this flag to not exit from clang-offload-bundler if no compatible 2523 // code object is found in heterogenous archive library. 2524 std::string AdditionalArgs("-allow-missing-bundles"); 2525 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs)); 2526 2527 // Add this flag to treat hip and hipv4 offload kinds as compatible with 2528 // openmp offload kind while extracting code objects from a heterogenous 2529 // archive library. Vice versa is also considered compatible. 2530 std::string HipCompatibleArgs("-hip-openmp-compatible"); 2531 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs)); 2532 2533 C.addCommand(std::make_unique<Command>( 2534 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs, 2535 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib)))); 2536 2537 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib)); 2538 2539 return; 2540 } 2541 2542 // Wrapper function used by driver for adding SDLs during link phase. 2543 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, 2544 const JobAction &JA, 2545 const InputInfoList &Inputs, 2546 const llvm::opt::ArgList &DriverArgs, 2547 llvm::opt::ArgStringList &CC1Args, 2548 StringRef Arch, StringRef Target, 2549 bool isBitCodeSDL) { 2550 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args, 2551 Arch, Target, isBitCodeSDL); 2552 } 2553 2554 // User defined Static Device Libraries(SDLs) can be passed to clang for 2555 // offloading GPU compilers. Like static host libraries, the use of a SDL is 2556 // specified with the -l command line option. The primary difference between 2557 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs 2558 // and SEARCH-ORDER for Machine-code SDLs for the naming convention). 2559 // SDLs are of following types: 2560 // 2561 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files. 2562 // For NVPTX, these libraries are post-clang linked following each 2563 // compilation. For AMDGPU, these libraries are linked one time 2564 // during the application link phase. 2565 // 2566 // * Machine-code SDLs: They are archive files. For AMDGPU, the process for 2567 // machine code SDLs is still in development. But they will be linked 2568 // by the LLVM tool lld. 2569 // 2570 // * Bundled objects that contain both host and device codes: Bundled objects 2571 // may also contain library code compiled from source. For NVPTX, the 2572 // bundle contains cubin. For AMDGPU, the bundle contains bitcode. 2573 // 2574 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the 2575 // inclusion of specific SDLs such as math libraries and the OpenMP device 2576 // library libomptarget. 2577 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T, 2578 const JobAction *JA, 2579 const InputInfoList *Inputs, const Driver &D, 2580 const llvm::opt::ArgList &DriverArgs, 2581 llvm::opt::ArgStringList &CC1Args, 2582 StringRef Arch, StringRef Target, 2583 bool isBitCodeSDL) { 2584 2585 SmallVector<std::string, 8> LibraryPaths; 2586 // Add search directories from LIBRARY_PATH env variable 2587 std::optional<std::string> LibPath = 2588 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 2589 if (LibPath) { 2590 SmallVector<StringRef, 8> Frags; 2591 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 2592 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 2593 for (StringRef Path : Frags) 2594 LibraryPaths.emplace_back(Path.trim()); 2595 } 2596 2597 // Add directories from user-specified -L options 2598 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L)) 2599 LibraryPaths.emplace_back(Search_Dir); 2600 2601 // Add path to lib-debug folders 2602 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 2603 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 2604 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 2605 2606 // Build list of Static Device Libraries SDLs specified by -l option 2607 llvm::SmallSet<std::string, 16> SDLNames; 2608 static const StringRef HostOnlyArchives[] = { 2609 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"}; 2610 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) { 2611 if (!llvm::is_contained(HostOnlyArchives, SDLName)) { 2612 SDLNames.insert(std::string("-l") + SDLName); 2613 } 2614 } 2615 2616 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) { 2617 auto FileName = StringRef(Input); 2618 // Clang treats any unknown file types as archives and passes them to the 2619 // linker. Files with extension 'lib' are classified as TY_Object by clang 2620 // but they are usually archives. It is OK if the file is not really an 2621 // archive since GetSDLFromOffloadArchive will check the magic of the file 2622 // and only unbundle it if it is really an archive. 2623 const StringRef LibFileExt = ".lib"; 2624 if (!llvm::sys::path::has_extension(FileName) || 2625 types::lookupTypeForExtension( 2626 llvm::sys::path::extension(FileName).drop_front()) == 2627 types::TY_INVALID || 2628 llvm::sys::path::extension(FileName) == LibFileExt) 2629 SDLNames.insert(Input); 2630 } 2631 2632 // The search stops as soon as an SDL file is found. The driver then provides 2633 // the full filename of the SDL to the llvm-link command. If no SDL is found 2634 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an 2635 // archive file lib<libname>.a exists and may contain bundled object files. 2636 for (auto SDLName : SDLNames) { 2637 // This is the only call to SDLSearch 2638 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target, 2639 isBitCodeSDL)) { 2640 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args, 2641 LibraryPaths, SDLName, Arch, Target, 2642 isBitCodeSDL); 2643 } 2644 } 2645 } 2646 2647 static llvm::opt::Arg * 2648 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) { 2649 return Args.getLastArg(options::OPT_mcode_object_version_EQ); 2650 } 2651 2652 void tools::checkAMDGPUCodeObjectVersion(const Driver &D, 2653 const llvm::opt::ArgList &Args) { 2654 const unsigned MinCodeObjVer = 4; 2655 const unsigned MaxCodeObjVer = 5; 2656 2657 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 2658 if (CodeObjArg->getOption().getID() == 2659 options::OPT_mcode_object_version_EQ) { 2660 unsigned CodeObjVer = MaxCodeObjVer; 2661 auto Remnant = 2662 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 2663 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer) 2664 D.Diag(diag::err_drv_invalid_int_value) 2665 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); 2666 } 2667 } 2668 } 2669 2670 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D, 2671 const llvm::opt::ArgList &Args) { 2672 unsigned CodeObjVer = 4; // default 2673 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) 2674 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 2675 return CodeObjVer; 2676 } 2677 2678 bool tools::haveAMDGPUCodeObjectVersionArgument( 2679 const Driver &D, const llvm::opt::ArgList &Args) { 2680 return getAMDGPUCodeObjectArgument(D, Args) != nullptr; 2681 } 2682 2683 void tools::addMachineOutlinerArgs(const Driver &D, 2684 const llvm::opt::ArgList &Args, 2685 llvm::opt::ArgStringList &CmdArgs, 2686 const llvm::Triple &Triple, bool IsLTO, 2687 const StringRef PluginOptPrefix) { 2688 auto addArg = [&, IsLTO](const Twine &Arg) { 2689 if (IsLTO) { 2690 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!"); 2691 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg)); 2692 } else { 2693 CmdArgs.push_back("-mllvm"); 2694 CmdArgs.push_back(Args.MakeArgString(Arg)); 2695 } 2696 }; 2697 2698 if (Arg *A = Args.getLastArg(options::OPT_moutline, 2699 options::OPT_mno_outline)) { 2700 if (A->getOption().matches(options::OPT_moutline)) { 2701 // We only support -moutline in AArch64 and ARM targets right now. If 2702 // we're not compiling for these, emit a warning and ignore the flag. 2703 // Otherwise, add the proper mllvm flags. 2704 if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) { 2705 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 2706 } else { 2707 addArg(Twine("-enable-machine-outliner")); 2708 } 2709 } else { 2710 // Disable all outlining behaviour. 2711 addArg(Twine("-enable-machine-outliner=never")); 2712 } 2713 } 2714 } 2715 2716 void tools::addOpenMPDeviceRTL(const Driver &D, 2717 const llvm::opt::ArgList &DriverArgs, 2718 llvm::opt::ArgStringList &CC1Args, 2719 StringRef BitcodeSuffix, 2720 const llvm::Triple &Triple) { 2721 SmallVector<StringRef, 8> LibraryPaths; 2722 2723 // Add path to clang lib / lib64 folder. 2724 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 2725 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 2726 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 2727 2728 // Add user defined library paths from LIBRARY_PATH. 2729 std::optional<std::string> LibPath = 2730 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 2731 if (LibPath) { 2732 SmallVector<StringRef, 8> Frags; 2733 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 2734 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 2735 for (StringRef Path : Frags) 2736 LibraryPaths.emplace_back(Path.trim()); 2737 } 2738 2739 OptSpecifier LibomptargetBCPathOpt = 2740 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ 2741 : options::OPT_libomptarget_nvptx_bc_path_EQ; 2742 2743 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx"; 2744 std::string LibOmpTargetName = 2745 ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str(); 2746 2747 // First check whether user specifies bc library 2748 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) { 2749 SmallString<128> LibOmpTargetFile(A->getValue()); 2750 if (llvm::sys::fs::exists(LibOmpTargetFile) && 2751 llvm::sys::fs::is_directory(LibOmpTargetFile)) { 2752 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 2753 } 2754 2755 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 2756 CC1Args.push_back("-mlink-builtin-bitcode"); 2757 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 2758 } else { 2759 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found) 2760 << LibOmpTargetFile; 2761 } 2762 } else { 2763 bool FoundBCLibrary = false; 2764 2765 for (StringRef LibraryPath : LibraryPaths) { 2766 SmallString<128> LibOmpTargetFile(LibraryPath); 2767 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 2768 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 2769 CC1Args.push_back("-mlink-builtin-bitcode"); 2770 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 2771 FoundBCLibrary = true; 2772 break; 2773 } 2774 } 2775 2776 if (!FoundBCLibrary) 2777 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime) 2778 << LibOmpTargetName << ArchPrefix; 2779 } 2780 } 2781 void tools::addHIPRuntimeLibArgs(const ToolChain &TC, Compilation &C, 2782 const llvm::opt::ArgList &Args, 2783 llvm::opt::ArgStringList &CmdArgs) { 2784 if ((C.getActiveOffloadKinds() & Action::OFK_HIP) && 2785 !Args.hasArg(options::OPT_nostdlib) && 2786 !Args.hasArg(options::OPT_no_hip_rt)) { 2787 TC.AddHIPRuntimeLibArgs(Args, CmdArgs); 2788 } else { 2789 // Claim "no HIP libraries" arguments if any 2790 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) { 2791 Arg->claim(); 2792 } 2793 } 2794 } 2795