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