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