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