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 "HIP.h" 19#include "Hexagon.h" 20#include "InputInfo.h" 21#include "clang/Basic/CharInfo.h" 22#include "clang/Basic/LangOptions.h" 23#include "clang/Basic/ObjCRuntime.h" 24#include "clang/Basic/Version.h" 25#include "clang/Config/config.h" 26#include "clang/Driver/Action.h" 27#include "clang/Driver/Compilation.h" 28#include "clang/Driver/Driver.h" 29#include "clang/Driver/DriverDiagnostic.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/SmallString.h" 38#include "llvm/ADT/StringExtras.h" 39#include "llvm/ADT/StringSwitch.h" 40#include "llvm/ADT/Twine.h" 41#include "llvm/Config/llvm-config.h" 42#include "llvm/Option/Arg.h" 43#include "llvm/Option/ArgList.h" 44#include "llvm/Option/Option.h" 45#include "llvm/Support/CodeGen.h" 46#include "llvm/Support/Compression.h" 47#include "llvm/Support/Debug.h" 48#include "llvm/Support/ErrorHandling.h" 49#include "llvm/Support/FileSystem.h" 50#include "llvm/Support/Host.h" 51#include "llvm/Support/Path.h" 52#include "llvm/Support/Process.h" 53#include "llvm/Support/Program.h" 54#include "llvm/Support/ScopedPrinter.h" 55#include "llvm/Support/TargetParser.h" 56#include "llvm/Support/Threading.h" 57#include "llvm/Support/VirtualFileSystem.h" 58#include "llvm/Support/YAMLParser.h" 59 60using namespace clang::driver; 61using namespace clang::driver::tools; 62using namespace clang; 63using namespace llvm::opt; 64 65static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) { 66 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) 67 CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") + 68 A->getValue())); 69 70 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) 71 CmdArgs.push_back(Args.MakeArgString( 72 Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue())); 73 74 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) 75 CmdArgs.push_back(Args.MakeArgString( 76 Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue())); 77} 78 79static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, 80 const llvm::Triple &Triple, 81 const InputInfo &Input, 82 const InputInfo &Output) { 83 StringRef Format = "yaml"; 84 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) 85 Format = A->getValue(); 86 87 SmallString<128> F; 88 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ); 89 if (A) 90 F = A->getValue(); 91 else if (Output.isFilename()) 92 F = Output.getFilename(); 93 94 assert(!F.empty() && "Cannot determine remarks output name."); 95 // Append "opt.ld.<format>" to the end of the file name. 96 CmdArgs.push_back( 97 Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F + 98 Twine(".opt.ld.") + Format)); 99 100 if (const Arg *A = 101 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) 102 CmdArgs.push_back(Args.MakeArgString( 103 Twine("--plugin-opt=opt-remarks-passes=") + A->getValue())); 104 105 CmdArgs.push_back(Args.MakeArgString( 106 Twine("--plugin-opt=opt-remarks-format=") + Format.data())); 107} 108 109static void renderRemarksHotnessOptions(const ArgList &Args, 110 ArgStringList &CmdArgs) { 111 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 112 options::OPT_fno_diagnostics_show_hotness, false)) 113 CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness"); 114 115 if (const Arg *A = 116 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) 117 CmdArgs.push_back(Args.MakeArgString( 118 Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue())); 119} 120 121void tools::addPathIfExists(const Driver &D, const Twine &Path, 122 ToolChain::path_list &Paths) { 123 if (D.getVFS().exists(Path)) 124 Paths.push_back(Path.str()); 125} 126 127void tools::handleTargetFeaturesGroup(const ArgList &Args, 128 std::vector<StringRef> &Features, 129 OptSpecifier Group) { 130 for (const Arg *A : Args.filtered(Group)) { 131 StringRef Name = A->getOption().getName(); 132 A->claim(); 133 134 // Skip over "-m". 135 assert(Name.startswith("m") && "Invalid feature name."); 136 Name = Name.substr(1); 137 138 bool IsNegative = Name.startswith("no-"); 139 if (IsNegative) 140 Name = Name.substr(3); 141 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 142 } 143} 144 145std::vector<StringRef> 146tools::unifyTargetFeatures(const std::vector<StringRef> &Features) { 147 std::vector<StringRef> UnifiedFeatures; 148 // Find the last of each feature. 149 llvm::StringMap<unsigned> LastOpt; 150 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 151 StringRef Name = Features[I]; 152 assert(Name[0] == '-' || Name[0] == '+'); 153 LastOpt[Name.drop_front(1)] = I; 154 } 155 156 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 157 // If this feature was overridden, ignore it. 158 StringRef Name = Features[I]; 159 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1)); 160 assert(LastI != LastOpt.end()); 161 unsigned Last = LastI->second; 162 if (Last != I) 163 continue; 164 165 UnifiedFeatures.push_back(Name); 166 } 167 return UnifiedFeatures; 168} 169 170void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 171 const char *ArgName, const char *EnvVar) { 172 const char *DirList = ::getenv(EnvVar); 173 bool CombinedArg = false; 174 175 if (!DirList) 176 return; // Nothing to do. 177 178 StringRef Name(ArgName); 179 if (Name.equals("-I") || Name.equals("-L") || Name.empty()) 180 CombinedArg = true; 181 182 StringRef Dirs(DirList); 183 if (Dirs.empty()) // Empty string should not add '.'. 184 return; 185 186 StringRef::size_type Delim; 187 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 188 if (Delim == 0) { // Leading colon. 189 if (CombinedArg) { 190 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 191 } else { 192 CmdArgs.push_back(ArgName); 193 CmdArgs.push_back("."); 194 } 195 } else { 196 if (CombinedArg) { 197 CmdArgs.push_back( 198 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 199 } else { 200 CmdArgs.push_back(ArgName); 201 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 202 } 203 } 204 Dirs = Dirs.substr(Delim + 1); 205 } 206 207 if (Dirs.empty()) { // Trailing colon. 208 if (CombinedArg) { 209 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 210 } else { 211 CmdArgs.push_back(ArgName); 212 CmdArgs.push_back("."); 213 } 214 } else { // Add the last path. 215 if (CombinedArg) { 216 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 217 } else { 218 CmdArgs.push_back(ArgName); 219 CmdArgs.push_back(Args.MakeArgString(Dirs)); 220 } 221 } 222} 223 224void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 225 const ArgList &Args, ArgStringList &CmdArgs, 226 const JobAction &JA) { 227 const Driver &D = TC.getDriver(); 228 229 // Add extra linker input arguments which are not treated as inputs 230 // (constructed via -Xarch_). 231 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 232 233 // LIBRARY_PATH are included before user inputs and only supported on native 234 // toolchains. 235 if (!TC.isCrossCompiling()) 236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 237 238 for (const auto &II : Inputs) { 239 // If the current tool chain refers to an OpenMP offloading host, we 240 // should ignore inputs that refer to OpenMP offloading devices - 241 // they will be embedded according to a proper linker script. 242 if (auto *IA = II.getAction()) 243 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 244 IA->isDeviceOffloading(Action::OFK_OpenMP))) 245 continue; 246 247 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 248 // Don't try to pass LLVM inputs unless we have native support. 249 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 250 251 // Add filenames immediately. 252 if (II.isFilename()) { 253 CmdArgs.push_back(II.getFilename()); 254 continue; 255 } 256 257 // Otherwise, this is a linker input argument. 258 const Arg &A = II.getInputArg(); 259 260 // Handle reserved library options. 261 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 262 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 263 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 264 TC.AddCCKextLibArgs(Args, CmdArgs); 265 else if (A.getOption().matches(options::OPT_z)) { 266 // Pass -z prefix for gcc linker compatibility. 267 A.claim(); 268 A.render(Args, CmdArgs); 269 } else { 270 A.renderAsInput(Args, CmdArgs); 271 } 272 } 273} 274 275void tools::addLinkerCompressDebugSectionsOption( 276 const ToolChain &TC, const llvm::opt::ArgList &Args, 277 llvm::opt::ArgStringList &CmdArgs) { 278 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi 279 // whereas zlib is an alias to zlib-gabi. Therefore -gz=none|zlib|zlib-gnu 280 // are translated to --compress-debug-sections=none|zlib|zlib-gnu. 281 // -gz is not translated since ld --compress-debug-sections option requires an 282 // argument. 283 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) { 284 StringRef V = A->getValue(); 285 if (V == "none" || V == "zlib" || V == "zlib-gnu") 286 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V)); 287 else 288 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument) 289 << A->getOption().getName() << V; 290 } 291} 292 293void tools::AddTargetFeature(const ArgList &Args, 294 std::vector<StringRef> &Features, 295 OptSpecifier OnOpt, OptSpecifier OffOpt, 296 StringRef FeatureName) { 297 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 298 if (A->getOption().matches(OnOpt)) 299 Features.push_back(Args.MakeArgString("+" + FeatureName)); 300 else 301 Features.push_back(Args.MakeArgString("-" + FeatureName)); 302 } 303} 304 305/// Get the (LLVM) name of the AMDGPU gpu we are targeting. 306static std::string getAMDGPUTargetGPU(const llvm::Triple &T, 307 const ArgList &Args) { 308 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 309 auto GPUName = getProcessorFromTargetID(T, A->getValue()); 310 return llvm::StringSwitch<std::string>(GPUName) 311 .Cases("rv630", "rv635", "r600") 312 .Cases("rv610", "rv620", "rs780", "rs880") 313 .Case("rv740", "rv770") 314 .Case("palm", "cedar") 315 .Cases("sumo", "sumo2", "sumo") 316 .Case("hemlock", "cypress") 317 .Case("aruba", "cayman") 318 .Default(GPUName.str()); 319 } 320 return ""; 321} 322 323static std::string getLanaiTargetCPU(const ArgList &Args) { 324 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 325 return A->getValue(); 326 } 327 return ""; 328} 329 330/// Get the (LLVM) name of the WebAssembly cpu we are targeting. 331static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 332 // If we have -mcpu=, use that. 333 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 334 StringRef CPU = A->getValue(); 335 336#ifdef __wasm__ 337 // Handle "native" by examining the host. "native" isn't meaningful when 338 // cross compiling, so only support this when the host is also WebAssembly. 339 if (CPU == "native") 340 return llvm::sys::getHostCPUName(); 341#endif 342 343 return CPU; 344 } 345 346 return "generic"; 347} 348 349std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T, 350 bool FromAs) { 351 Arg *A; 352 353 switch (T.getArch()) { 354 default: 355 return ""; 356 357 case llvm::Triple::aarch64: 358 case llvm::Triple::aarch64_32: 359 case llvm::Triple::aarch64_be: 360 return aarch64::getAArch64TargetCPU(Args, T, A); 361 362 case llvm::Triple::arm: 363 case llvm::Triple::armeb: 364 case llvm::Triple::thumb: 365 case llvm::Triple::thumbeb: { 366 StringRef MArch, MCPU; 367 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 368 return arm::getARMTargetCPU(MCPU, MArch, T); 369 } 370 371 case llvm::Triple::avr: 372 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 373 return A->getValue(); 374 return ""; 375 376 case llvm::Triple::m68k: 377 return m68k::getM68kTargetCPU(Args); 378 379 case llvm::Triple::mips: 380 case llvm::Triple::mipsel: 381 case llvm::Triple::mips64: 382 case llvm::Triple::mips64el: { 383 StringRef CPUName; 384 StringRef ABIName; 385 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 386 return std::string(CPUName); 387 } 388 389 case llvm::Triple::nvptx: 390 case llvm::Triple::nvptx64: 391 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 392 return A->getValue(); 393 return ""; 394 395 case llvm::Triple::ppc: 396 case llvm::Triple::ppcle: 397 case llvm::Triple::ppc64: 398 case llvm::Triple::ppc64le: { 399 std::string TargetCPUName = ppc::getPPCTargetCPU(Args); 400 // LLVM may default to generating code for the native CPU, 401 // but, like gcc, we default to a more generic option for 402 // each architecture. (except on AIX) 403 if (!TargetCPUName.empty()) 404 return TargetCPUName; 405 406 if (T.isOSAIX()) { 407 unsigned major, minor, unused_micro; 408 T.getOSVersion(major, minor, unused_micro); 409 // The minimal arch level moved from pwr4 for AIX7.1 to 410 // pwr7 for AIX7.2. 411 TargetCPUName = 412 (major < 7 || (major == 7 && minor < 2)) ? "pwr4" : "pwr7"; 413 } else if (T.getArch() == llvm::Triple::ppc64le) 414 TargetCPUName = "ppc64le"; 415 else if (T.getArch() == llvm::Triple::ppc64) 416 TargetCPUName = "ppc64"; 417 else 418 TargetCPUName = "ppc"; 419 420 return TargetCPUName; 421 } 422 case llvm::Triple::riscv32: 423 case llvm::Triple::riscv64: 424 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 425 return A->getValue(); 426 return ""; 427 428 case llvm::Triple::bpfel: 429 case llvm::Triple::bpfeb: 430 case llvm::Triple::sparc: 431 case llvm::Triple::sparcel: 432 case llvm::Triple::sparcv9: 433 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 434 return A->getValue(); 435 if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris()) 436 return "v9"; 437 return ""; 438 439 case llvm::Triple::x86: 440 case llvm::Triple::x86_64: 441 return x86::getX86TargetCPU(Args, T); 442 443 case llvm::Triple::hexagon: 444 return "hexagon" + 445 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 446 447 case llvm::Triple::lanai: 448 return getLanaiTargetCPU(Args); 449 450 case llvm::Triple::systemz: 451 return systemz::getSystemZTargetCPU(Args); 452 453 case llvm::Triple::r600: 454 case llvm::Triple::amdgcn: 455 return getAMDGPUTargetGPU(T, Args); 456 457 case llvm::Triple::wasm32: 458 case llvm::Triple::wasm64: 459 return std::string(getWebAssemblyTargetCPU(Args)); 460 } 461} 462 463llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 464 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 465 if (!LtoJobsArg) 466 return {}; 467 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue())) 468 D.Diag(diag::err_drv_invalid_int_value) 469 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); 470 return LtoJobsArg->getValue(); 471} 472 473// CloudABI uses -ffunction-sections and -fdata-sections by default. 474bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 475 return Triple.getOS() == llvm::Triple::CloudABI; 476} 477 478void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, 479 ArgStringList &CmdArgs, const InputInfo &Output, 480 const InputInfo &Input, bool IsThinLTO) { 481 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 482 const Driver &D = ToolChain.getDriver(); 483 if (llvm::sys::path::filename(Linker) != "ld.lld" && 484 llvm::sys::path::stem(Linker) != "ld.lld") { 485 // Tell the linker to load the plugin. This has to come before 486 // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt 487 // that -Wl might forward. 488 CmdArgs.push_back("-plugin"); 489 490#if defined(_WIN32) 491 const char *Suffix = ".dll"; 492#elif defined(__APPLE__) 493 const char *Suffix = ".dylib"; 494#else 495 const char *Suffix = ".so"; 496#endif 497 498 SmallString<1024> Plugin; 499 llvm::sys::path::native( 500 Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix, 501 Plugin); 502 CmdArgs.push_back(Args.MakeArgString(Plugin)); 503 } 504 505 // Try to pass driver level flags relevant to LTO code generation down to 506 // the plugin. 507 508 // Handle flags for selecting CPU variants. 509 std::string CPU = getCPUName(Args, ToolChain.getTriple()); 510 if (!CPU.empty()) 511 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU)); 512 513 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 514 // The optimization level matches 515 // CompilerInvocation.cpp:getOptimizationLevel(). 516 StringRef OOpt; 517 if (A->getOption().matches(options::OPT_O4) || 518 A->getOption().matches(options::OPT_Ofast)) 519 OOpt = "3"; 520 else if (A->getOption().matches(options::OPT_O)) { 521 OOpt = A->getValue(); 522 if (OOpt == "g") 523 OOpt = "1"; 524 else if (OOpt == "s" || OOpt == "z") 525 OOpt = "2"; 526 } else if (A->getOption().matches(options::OPT_O0)) 527 OOpt = "0"; 528 if (!OOpt.empty()) 529 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt)); 530 } 531 532 if (Args.hasArg(options::OPT_gsplit_dwarf)) { 533 CmdArgs.push_back( 534 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") + 535 Output.getFilename() + "_dwo")); 536 } 537 538 if (IsThinLTO) 539 CmdArgs.push_back("-plugin-opt=thinlto"); 540 541 StringRef Parallelism = getLTOParallelism(Args, D); 542 if (!Parallelism.empty()) 543 CmdArgs.push_back( 544 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism))); 545 546 // If an explicit debugger tuning argument appeared, pass it along. 547 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group, 548 options::OPT_ggdbN_Group)) { 549 if (A->getOption().matches(options::OPT_glldb)) 550 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb"); 551 else if (A->getOption().matches(options::OPT_gsce)) 552 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce"); 553 else if (A->getOption().matches(options::OPT_gdbx)) 554 CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx"); 555 else 556 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb"); 557 } 558 559 bool UseSeparateSections = 560 isUseSeparateSections(ToolChain.getEffectiveTriple()); 561 562 if (Args.hasFlag(options::OPT_ffunction_sections, 563 options::OPT_fno_function_sections, UseSeparateSections)) { 564 CmdArgs.push_back("-plugin-opt=-function-sections"); 565 } 566 567 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 568 UseSeparateSections)) { 569 CmdArgs.push_back("-plugin-opt=-data-sections"); 570 } 571 572 if (Arg *A = getLastProfileSampleUseArg(Args)) { 573 StringRef FName = A->getValue(); 574 if (!llvm::sys::fs::exists(FName)) 575 D.Diag(diag::err_drv_no_such_file) << FName; 576 else 577 CmdArgs.push_back( 578 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName)); 579 } 580 581 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 582 options::OPT_fcs_profile_generate_EQ, 583 options::OPT_fno_profile_generate); 584 if (CSPGOGenerateArg && 585 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 586 CSPGOGenerateArg = nullptr; 587 588 auto *ProfileUseArg = getLastProfileUseArg(Args); 589 590 if (CSPGOGenerateArg) { 591 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate")); 592 if (CSPGOGenerateArg->getOption().matches( 593 options::OPT_fcs_profile_generate_EQ)) { 594 SmallString<128> Path(CSPGOGenerateArg->getValue()); 595 llvm::sys::path::append(Path, "default_%m.profraw"); 596 CmdArgs.push_back( 597 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path)); 598 } else 599 CmdArgs.push_back( 600 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw")); 601 } else if (ProfileUseArg) { 602 SmallString<128> Path( 603 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 604 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 605 llvm::sys::path::append(Path, "default.profdata"); 606 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + 607 Path)); 608 } 609 610 // Pass an option to enable/disable the new pass manager. 611 if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager, 612 options::OPT_fno_legacy_pass_manager)) { 613 if (A->getOption().matches(options::OPT_flegacy_pass_manager)) 614 CmdArgs.push_back("-plugin-opt=legacy-pass-manager"); 615 else 616 CmdArgs.push_back("-plugin-opt=new-pass-manager"); 617 } 618 619 // Pass an option to enable pseudo probe emission. 620 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling, 621 options::OPT_fno_pseudo_probe_for_profiling, false)) 622 CmdArgs.push_back("-plugin-opt=pseudo-probe-for-profiling"); 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 648void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 649 ArgStringList &CmdArgs) { 650 // Enable -frtlib-add-rpath by default for the case of VE. 651 const bool IsVE = TC.getTriple().isVE(); 652 bool DefaultValue = IsVE; 653 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 654 options::OPT_fno_rtlib_add_rpath, DefaultValue)) 655 return; 656 657 std::string CandidateRPath = TC.getArchSpecificLibPath(); 658 if (TC.getVFS().exists(CandidateRPath)) { 659 CmdArgs.push_back("-rpath"); 660 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str())); 661 } 662} 663 664bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 665 const ArgList &Args, bool ForceStaticHostRuntime, 666 bool IsOffloadingHost, bool GompNeedsRT) { 667 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 668 options::OPT_fno_openmp, false)) 669 return false; 670 671 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 672 673 if (RTKind == Driver::OMPRT_Unknown) 674 // Already diagnosed. 675 return false; 676 677 if (ForceStaticHostRuntime) 678 CmdArgs.push_back("-Bstatic"); 679 680 switch (RTKind) { 681 case Driver::OMPRT_OMP: 682 CmdArgs.push_back("-lomp"); 683 break; 684 case Driver::OMPRT_GOMP: 685 CmdArgs.push_back("-lgomp"); 686 break; 687 case Driver::OMPRT_IOMP5: 688 CmdArgs.push_back("-liomp5"); 689 break; 690 case Driver::OMPRT_Unknown: 691 break; 692 } 693 694 if (ForceStaticHostRuntime) 695 CmdArgs.push_back("-Bdynamic"); 696 697 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 698 CmdArgs.push_back("-lrt"); 699 700 if (IsOffloadingHost) 701 CmdArgs.push_back("-lomptarget"); 702 703 addArchSpecificRPath(TC, Args, CmdArgs); 704 705 return true; 706} 707 708static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 709 ArgStringList &CmdArgs, StringRef Sanitizer, 710 bool IsShared, bool IsWhole) { 711 // Wrap any static runtimes that must be forced into executable in 712 // whole-archive. 713 if (IsWhole) CmdArgs.push_back("--whole-archive"); 714 CmdArgs.push_back(TC.getCompilerRTArgString( 715 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 716 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 717 718 if (IsShared) { 719 addArchSpecificRPath(TC, Args, CmdArgs); 720 } 721} 722 723// Tries to use a file with the list of dynamic symbols that need to be exported 724// from the runtime library. Returns true if the file was found. 725static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 726 ArgStringList &CmdArgs, 727 StringRef Sanitizer) { 728 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 729 // the option, so don't try to pass it. 730 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 731 return true; 732 // Myriad is static linking only. Furthermore, some versions of its 733 // linker have the bug where --export-dynamic overrides -static, so 734 // don't use --export-dynamic on that platform. 735 if (TC.getTriple().getVendor() == llvm::Triple::Myriad) 736 return true; 737 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 738 if (llvm::sys::fs::exists(SanRT + ".syms")) { 739 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 740 return true; 741 } 742 return false; 743} 744 745static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) { 746 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases 747 // for the native forms -z ignore/-z record, they are missing in Illumos, 748 // so always use the native form. 749 if (TC.getTriple().isOSSolaris()) 750 return as_needed ? "-zignore" : "-zrecord"; 751 else 752 return as_needed ? "--as-needed" : "--no-as-needed"; 753} 754 755void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 756 ArgStringList &CmdArgs) { 757 // Fuchsia never needs these. Any sanitizer runtimes with system 758 // dependencies use the `.deplibs` feature instead. 759 if (TC.getTriple().isOSFuchsia()) 760 return; 761 762 // Force linking against the system libraries sanitizers depends on 763 // (see PR15823 why this is necessary). 764 CmdArgs.push_back(getAsNeededOption(TC, false)); 765 // There's no libpthread or librt on RTEMS & Android. 766 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 767 !TC.getTriple().isAndroid()) { 768 CmdArgs.push_back("-lpthread"); 769 if (!TC.getTriple().isOSOpenBSD()) 770 CmdArgs.push_back("-lrt"); 771 } 772 CmdArgs.push_back("-lm"); 773 // There's no libdl on all OSes. 774 if (!TC.getTriple().isOSFreeBSD() && 775 !TC.getTriple().isOSNetBSD() && 776 !TC.getTriple().isOSOpenBSD() && 777 TC.getTriple().getOS() != llvm::Triple::RTEMS) 778 CmdArgs.push_back("-ldl"); 779 // Required for backtrace on some OSes 780 if (TC.getTriple().isOSFreeBSD() || 781 TC.getTriple().isOSNetBSD()) 782 CmdArgs.push_back("-lexecinfo"); 783} 784 785static void 786collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 787 SmallVectorImpl<StringRef> &SharedRuntimes, 788 SmallVectorImpl<StringRef> &StaticRuntimes, 789 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 790 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 791 SmallVectorImpl<StringRef> &RequiredSymbols) { 792 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 793 // Collect shared runtimes. 794 if (SanArgs.needsSharedRt()) { 795 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 796 SharedRuntimes.push_back("asan"); 797 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 798 HelperStaticRuntimes.push_back("asan-preinit"); 799 } 800 if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) { 801 SharedRuntimes.push_back("memprof"); 802 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 803 HelperStaticRuntimes.push_back("memprof-preinit"); 804 } 805 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 806 if (SanArgs.requiresMinimalRuntime()) 807 SharedRuntimes.push_back("ubsan_minimal"); 808 else 809 SharedRuntimes.push_back("ubsan_standalone"); 810 } 811 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 812 if (SanArgs.requiresMinimalRuntime()) 813 SharedRuntimes.push_back("scudo_minimal"); 814 else 815 SharedRuntimes.push_back("scudo"); 816 } 817 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) 818 SharedRuntimes.push_back("tsan"); 819 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 820 if (SanArgs.needsHwasanAliasesRt()) 821 SharedRuntimes.push_back("hwasan_aliases"); 822 else 823 SharedRuntimes.push_back("hwasan"); 824 } 825 } 826 827 // The stats_client library is also statically linked into DSOs. 828 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 829 StaticRuntimes.push_back("stats_client"); 830 831 // Collect static runtimes. 832 if (Args.hasArg(options::OPT_shared)) { 833 // Don't link static runtimes into DSOs. 834 return; 835 } 836 837 // Each static runtime that has a DSO counterpart above is excluded below, 838 // but runtimes that exist only as static are not affected by needsSharedRt. 839 840 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 841 StaticRuntimes.push_back("asan"); 842 if (SanArgs.linkCXXRuntimes()) 843 StaticRuntimes.push_back("asan_cxx"); 844 } 845 846 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() && 847 SanArgs.linkRuntimes()) { 848 StaticRuntimes.push_back("memprof"); 849 if (SanArgs.linkCXXRuntimes()) 850 StaticRuntimes.push_back("memprof_cxx"); 851 } 852 853 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 854 if (SanArgs.needsHwasanAliasesRt()) { 855 StaticRuntimes.push_back("hwasan_aliases"); 856 if (SanArgs.linkCXXRuntimes()) 857 StaticRuntimes.push_back("hwasan_aliases_cxx"); 858 } else { 859 StaticRuntimes.push_back("hwasan"); 860 if (SanArgs.linkCXXRuntimes()) 861 StaticRuntimes.push_back("hwasan_cxx"); 862 } 863 } 864 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes()) 865 StaticRuntimes.push_back("dfsan"); 866 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes()) 867 StaticRuntimes.push_back("lsan"); 868 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) { 869 StaticRuntimes.push_back("msan"); 870 if (SanArgs.linkCXXRuntimes()) 871 StaticRuntimes.push_back("msan_cxx"); 872 } 873 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() && 874 SanArgs.linkRuntimes()) { 875 StaticRuntimes.push_back("tsan"); 876 if (SanArgs.linkCXXRuntimes()) 877 StaticRuntimes.push_back("tsan_cxx"); 878 } 879 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 880 if (SanArgs.requiresMinimalRuntime()) { 881 StaticRuntimes.push_back("ubsan_minimal"); 882 } else { 883 StaticRuntimes.push_back("ubsan_standalone"); 884 if (SanArgs.linkCXXRuntimes()) 885 StaticRuntimes.push_back("ubsan_standalone_cxx"); 886 } 887 } 888 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) { 889 NonWholeStaticRuntimes.push_back("safestack"); 890 RequiredSymbols.push_back("__safestack_init"); 891 } 892 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) { 893 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes()) 894 StaticRuntimes.push_back("cfi"); 895 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) { 896 StaticRuntimes.push_back("cfi_diag"); 897 if (SanArgs.linkCXXRuntimes()) 898 StaticRuntimes.push_back("ubsan_standalone_cxx"); 899 } 900 } 901 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) { 902 NonWholeStaticRuntimes.push_back("stats"); 903 RequiredSymbols.push_back("__sanitizer_stats_register"); 904 } 905 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 906 if (SanArgs.requiresMinimalRuntime()) { 907 StaticRuntimes.push_back("scudo_minimal"); 908 if (SanArgs.linkCXXRuntimes()) 909 StaticRuntimes.push_back("scudo_cxx_minimal"); 910 } else { 911 StaticRuntimes.push_back("scudo"); 912 if (SanArgs.linkCXXRuntimes()) 913 StaticRuntimes.push_back("scudo_cxx"); 914 } 915 } 916} 917 918// Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 919// C runtime, etc). Returns true if sanitizer system deps need to be linked in. 920bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 921 ArgStringList &CmdArgs) { 922 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 923 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 924 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 925 NonWholeStaticRuntimes, HelperStaticRuntimes, 926 RequiredSymbols); 927 928 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 929 // Inject libfuzzer dependencies. 930 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 931 !Args.hasArg(options::OPT_shared)) { 932 933 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 934 if (SanArgs.needsFuzzerInterceptors()) 935 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false, 936 true); 937 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) { 938 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && 939 !Args.hasArg(options::OPT_static); 940 if (OnlyLibstdcxxStatic) 941 CmdArgs.push_back("-Bstatic"); 942 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 943 if (OnlyLibstdcxxStatic) 944 CmdArgs.push_back("-Bdynamic"); 945 } 946 } 947 948 for (auto RT : SharedRuntimes) 949 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 950 for (auto RT : HelperStaticRuntimes) 951 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 952 bool AddExportDynamic = false; 953 for (auto RT : StaticRuntimes) { 954 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 955 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 956 } 957 for (auto RT : NonWholeStaticRuntimes) { 958 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 959 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 960 } 961 for (auto S : RequiredSymbols) { 962 CmdArgs.push_back("-u"); 963 CmdArgs.push_back(Args.MakeArgString(S)); 964 } 965 // If there is a static runtime with no dynamic list, force all the symbols 966 // to be dynamic to be sure we export sanitizer interface functions. 967 if (AddExportDynamic) 968 CmdArgs.push_back("--export-dynamic"); 969 970 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 971 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check"); 972 973 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 974} 975 976bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 977 if (Args.hasArg(options::OPT_shared)) 978 return false; 979 980 if (TC.getXRayArgs().needsXRayRt()) { 981 CmdArgs.push_back("-whole-archive"); 982 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 983 for (const auto &Mode : TC.getXRayArgs().modeList()) 984 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 985 CmdArgs.push_back("-no-whole-archive"); 986 return true; 987 } 988 989 return false; 990} 991 992void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) { 993 CmdArgs.push_back(getAsNeededOption(TC, false)); 994 CmdArgs.push_back("-lpthread"); 995 if (!TC.getTriple().isOSOpenBSD()) 996 CmdArgs.push_back("-lrt"); 997 CmdArgs.push_back("-lm"); 998 999 if (!TC.getTriple().isOSFreeBSD() && 1000 !TC.getTriple().isOSNetBSD() && 1001 !TC.getTriple().isOSOpenBSD()) 1002 CmdArgs.push_back("-ldl"); 1003} 1004 1005bool tools::areOptimizationsEnabled(const ArgList &Args) { 1006 // Find the last -O arg and see if it is non-zero. 1007 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 1008 return !A->getOption().matches(options::OPT_O0); 1009 // Defaults to -O0. 1010 return false; 1011} 1012 1013const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args, 1014 const InputInfo &Input, 1015 const InputInfo &Output) { 1016 auto AddPostfix = [JA](auto &F) { 1017 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP) 1018 F += (Twine("_") + JA.getOffloadingArch()).str(); 1019 F += ".dwo"; 1020 }; 1021 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 1022 if (StringRef(A->getValue()) == "single") 1023 return Args.MakeArgString(Output.getFilename()); 1024 1025 Arg *FinalOutput = Args.getLastArg(options::OPT_o); 1026 if (FinalOutput && Args.hasArg(options::OPT_c)) { 1027 SmallString<128> T(FinalOutput->getValue()); 1028 llvm::sys::path::remove_filename(T); 1029 llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue())); 1030 AddPostfix(T); 1031 return Args.MakeArgString(T); 1032 } else { 1033 // Use the compilation dir. 1034 Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ, 1035 options::OPT_fdebug_compilation_dir_EQ); 1036 SmallString<128> T(A ? A->getValue() : ""); 1037 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput())); 1038 AddPostfix(F); 1039 T += F; 1040 return Args.MakeArgString(T); 1041 } 1042} 1043 1044void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 1045 const JobAction &JA, const ArgList &Args, 1046 const InputInfo &Output, const char *OutFile) { 1047 ArgStringList ExtractArgs; 1048 ExtractArgs.push_back("--extract-dwo"); 1049 1050 ArgStringList StripArgs; 1051 StripArgs.push_back("--strip-dwo"); 1052 1053 // Grabbing the output of the earlier compile step. 1054 StripArgs.push_back(Output.getFilename()); 1055 ExtractArgs.push_back(Output.getFilename()); 1056 ExtractArgs.push_back(OutFile); 1057 1058 const char *Exec = 1059 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 1060 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 1061 1062 // First extract the dwo sections. 1063 C.addCommand(std::make_unique<Command>(JA, T, 1064 ResponseFileSupport::AtFileCurCP(), 1065 Exec, ExtractArgs, II, Output)); 1066 1067 // Then remove them from the original .o file. 1068 C.addCommand(std::make_unique<Command>( 1069 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output)); 1070} 1071 1072// Claim options we don't want to warn if they are unused. We do this for 1073// options that build systems might add but are unused when assembling or only 1074// running the preprocessor for example. 1075void tools::claimNoWarnArgs(const ArgList &Args) { 1076 // Don't warn about unused -f(no-)?lto. This can happen when we're 1077 // preprocessing, precompiling or assembling. 1078 Args.ClaimAllArgs(options::OPT_flto_EQ); 1079 Args.ClaimAllArgs(options::OPT_flto); 1080 Args.ClaimAllArgs(options::OPT_fno_lto); 1081} 1082 1083Arg *tools::getLastProfileUseArg(const ArgList &Args) { 1084 auto *ProfileUseArg = Args.getLastArg( 1085 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 1086 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 1087 options::OPT_fno_profile_instr_use); 1088 1089 if (ProfileUseArg && 1090 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 1091 ProfileUseArg = nullptr; 1092 1093 return ProfileUseArg; 1094} 1095 1096Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 1097 auto *ProfileSampleUseArg = Args.getLastArg( 1098 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 1099 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 1100 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 1101 1102 if (ProfileSampleUseArg && 1103 (ProfileSampleUseArg->getOption().matches( 1104 options::OPT_fno_profile_sample_use) || 1105 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 1106 return nullptr; 1107 1108 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 1109 options::OPT_fauto_profile_EQ); 1110} 1111 1112/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 1113/// smooshes them together with platform defaults, to decide whether 1114/// this compile should be using PIC mode or not. Returns a tuple of 1115/// (RelocationModel, PICLevel, IsPIE). 1116std::tuple<llvm::Reloc::Model, unsigned, bool> 1117tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 1118 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 1119 const llvm::Triple &Triple = ToolChain.getTriple(); 1120 1121 bool PIE = ToolChain.isPIEDefault(); 1122 bool PIC = PIE || ToolChain.isPICDefault(); 1123 // The Darwin/MachO default to use PIC does not apply when using -static. 1124 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 1125 PIE = PIC = false; 1126 bool IsPICLevelTwo = PIC; 1127 1128 bool KernelOrKext = 1129 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 1130 1131 // Android-specific defaults for PIC/PIE 1132 if (Triple.isAndroid()) { 1133 switch (Triple.getArch()) { 1134 case llvm::Triple::arm: 1135 case llvm::Triple::armeb: 1136 case llvm::Triple::thumb: 1137 case llvm::Triple::thumbeb: 1138 case llvm::Triple::aarch64: 1139 case llvm::Triple::mips: 1140 case llvm::Triple::mipsel: 1141 case llvm::Triple::mips64: 1142 case llvm::Triple::mips64el: 1143 PIC = true; // "-fpic" 1144 break; 1145 1146 case llvm::Triple::x86: 1147 case llvm::Triple::x86_64: 1148 PIC = true; // "-fPIC" 1149 IsPICLevelTwo = true; 1150 break; 1151 1152 default: 1153 break; 1154 } 1155 } 1156 1157 // OpenBSD-specific defaults for PIE 1158 if (Triple.isOSOpenBSD()) { 1159 switch (ToolChain.getArch()) { 1160 case llvm::Triple::arm: 1161 case llvm::Triple::aarch64: 1162 case llvm::Triple::mips64: 1163 case llvm::Triple::mips64el: 1164 case llvm::Triple::x86: 1165 case llvm::Triple::x86_64: 1166 IsPICLevelTwo = false; // "-fpie" 1167 break; 1168 1169 case llvm::Triple::ppc: 1170 case llvm::Triple::sparcv9: 1171 IsPICLevelTwo = true; // "-fPIE" 1172 break; 1173 1174 default: 1175 break; 1176 } 1177 } 1178 1179 // AMDGPU-specific defaults for PIC. 1180 if (Triple.getArch() == llvm::Triple::amdgcn) 1181 PIC = true; 1182 1183 // The last argument relating to either PIC or PIE wins, and no 1184 // other argument is used. If the last argument is any flavor of the 1185 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 1186 // option implicitly enables PIC at the same level. 1187 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 1188 options::OPT_fpic, options::OPT_fno_pic, 1189 options::OPT_fPIE, options::OPT_fno_PIE, 1190 options::OPT_fpie, options::OPT_fno_pie); 1191 if (Triple.isOSWindows() && LastPICArg && 1192 LastPICArg == 1193 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 1194 options::OPT_fPIE, options::OPT_fpie)) { 1195 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1196 << LastPICArg->getSpelling() << Triple.str(); 1197 if (Triple.getArch() == llvm::Triple::x86_64) 1198 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 1199 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1200 } 1201 1202 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 1203 // is forced, then neither PIC nor PIE flags will have no effect. 1204 if (!ToolChain.isPICDefaultForced()) { 1205 if (LastPICArg) { 1206 Option O = LastPICArg->getOption(); 1207 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 1208 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 1209 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1210 PIC = 1211 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1212 IsPICLevelTwo = 1213 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1214 } else { 1215 PIE = PIC = false; 1216 if (EffectiveTriple.isPS4CPU()) { 1217 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1218 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1219 if (Model != "kernel") { 1220 PIC = true; 1221 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic) 1222 << LastPICArg->getSpelling(); 1223 } 1224 } 1225 } 1226 } 1227 } 1228 1229 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the 1230 // PIC level would've been set to level 1, force it back to level 2 PIC 1231 // instead. 1232 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU())) 1233 IsPICLevelTwo |= ToolChain.isPICDefault(); 1234 1235 // This kernel flags are a trump-card: they will disable PIC/PIE 1236 // generation, independent of the argument order. 1237 if (KernelOrKext && 1238 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1239 !EffectiveTriple.isWatchOS())) 1240 PIC = PIE = false; 1241 1242 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1243 // This is a very special mode. It trumps the other modes, almost no one 1244 // uses it, and it isn't even valid on any OS but Darwin. 1245 if (!Triple.isOSDarwin()) 1246 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1247 << A->getSpelling() << Triple.str(); 1248 1249 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1250 1251 // Only a forced PIC mode can cause the actual compile to have PIC defines 1252 // etc., no flags are sufficient. This behavior was selected to closely 1253 // match that of llvm-gcc and Apple GCC before that. 1254 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1255 1256 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1257 } 1258 1259 bool EmbeddedPISupported; 1260 switch (Triple.getArch()) { 1261 case llvm::Triple::arm: 1262 case llvm::Triple::armeb: 1263 case llvm::Triple::thumb: 1264 case llvm::Triple::thumbeb: 1265 EmbeddedPISupported = true; 1266 break; 1267 default: 1268 EmbeddedPISupported = false; 1269 break; 1270 } 1271 1272 bool ROPI = false, RWPI = false; 1273 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1274 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1275 if (!EmbeddedPISupported) 1276 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1277 << LastROPIArg->getSpelling() << Triple.str(); 1278 ROPI = true; 1279 } 1280 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1281 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1282 if (!EmbeddedPISupported) 1283 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1284 << LastRWPIArg->getSpelling() << Triple.str(); 1285 RWPI = true; 1286 } 1287 1288 // ROPI and RWPI are not compatible with PIC or PIE. 1289 if ((ROPI || RWPI) && (PIC || PIE)) 1290 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1291 1292 if (Triple.isMIPS()) { 1293 StringRef CPUName; 1294 StringRef ABIName; 1295 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1296 // When targeting the N64 ABI, PIC is the default, except in the case 1297 // when the -mno-abicalls option is used. In that case we exit 1298 // at next check regardless of PIC being set below. 1299 if (ABIName == "n64") 1300 PIC = true; 1301 // When targettng MIPS with -mno-abicalls, it's always static. 1302 if(Args.hasArg(options::OPT_mno_abicalls)) 1303 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1304 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1305 // does not use PIC level 2 for historical reasons. 1306 IsPICLevelTwo = false; 1307 } 1308 1309 if (PIC) 1310 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1311 1312 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1313 if (ROPI && RWPI) 1314 RelocM = llvm::Reloc::ROPI_RWPI; 1315 else if (ROPI) 1316 RelocM = llvm::Reloc::ROPI; 1317 else if (RWPI) 1318 RelocM = llvm::Reloc::RWPI; 1319 1320 return std::make_tuple(RelocM, 0U, false); 1321} 1322 1323// `-falign-functions` indicates that the functions should be aligned to a 1324// 16-byte boundary. 1325// 1326// `-falign-functions=1` is the same as `-fno-align-functions`. 1327// 1328// The scalar `n` in `-falign-functions=n` must be an integral value between 1329// [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1330// the nearest power-of-two. 1331// 1332// If we return `0`, the frontend will default to the backend's preferred 1333// alignment. 1334// 1335// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1336// to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1337// alignment. For unaligned functions, we default to the backend's preferred 1338// alignment. 1339unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1340 const ArgList &Args) { 1341 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1342 options::OPT_falign_functions_EQ, 1343 options::OPT_fno_align_functions); 1344 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1345 return 0; 1346 1347 if (A->getOption().matches(options::OPT_falign_functions)) 1348 return 0; 1349 1350 unsigned Value = 0; 1351 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1352 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1353 << A->getAsString(Args) << A->getValue(); 1354 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1355} 1356 1357unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC, 1358 const ArgList &Args) { 1359 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 1360 1361 if (!A) 1362 return 0; 1363 1364 unsigned Value = 0; 1365 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 1366 Value < 2) 1367 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1368 << A->getAsString(Args) << A->getValue(); 1369 return Value; 1370} 1371 1372void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1373 ArgStringList &CmdArgs) { 1374 llvm::Reloc::Model RelocationModel; 1375 unsigned PICLevel; 1376 bool IsPIE; 1377 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1378 1379 if (RelocationModel != llvm::Reloc::Static) 1380 CmdArgs.push_back("-KPIC"); 1381} 1382 1383/// Determine whether Objective-C automated reference counting is 1384/// enabled. 1385bool tools::isObjCAutoRefCount(const ArgList &Args) { 1386 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1387} 1388 1389enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1390 1391static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, 1392 const ArgList &Args) { 1393 if (Args.hasArg(options::OPT_static_libgcc) || 1394 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie)) 1395 return LibGccType::StaticLibGcc; 1396 if (Args.hasArg(options::OPT_shared_libgcc)) 1397 return LibGccType::SharedLibGcc; 1398 // The Android NDK only provides libunwind.a, not libunwind.so. 1399 if (TC.getTriple().isAndroid()) 1400 return LibGccType::StaticLibGcc; 1401 // For MinGW, don't imply a shared libgcc here, we only want to return 1402 // SharedLibGcc if that was explicitly requested. 1403 if (D.CCCIsCXX() && !TC.getTriple().isOSCygMing()) 1404 return LibGccType::SharedLibGcc; 1405 return LibGccType::UnspecifiedLibGcc; 1406} 1407 1408// Gcc adds libgcc arguments in various ways: 1409// 1410// gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1411// g++ <none>: -lgcc_s -lgcc 1412// gcc shared: -lgcc_s -lgcc 1413// g++ shared: -lgcc_s -lgcc 1414// gcc static: -lgcc -lgcc_eh 1415// g++ static: -lgcc -lgcc_eh 1416// gcc static-pie: -lgcc -lgcc_eh 1417// g++ static-pie: -lgcc -lgcc_eh 1418// 1419// Also, certain targets need additional adjustments. 1420 1421static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1422 ArgStringList &CmdArgs, const ArgList &Args) { 1423 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1424 // Targets that don't use unwind libraries. 1425 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || 1426 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || 1427 UNW == ToolChain::UNW_None) 1428 return; 1429 1430 LibGccType LGT = getLibGccType(TC, D, Args); 1431 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1432 !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing(); 1433 if (AsNeeded) 1434 CmdArgs.push_back(getAsNeededOption(TC, true)); 1435 1436 switch (UNW) { 1437 case ToolChain::UNW_None: 1438 return; 1439 case ToolChain::UNW_Libgcc: { 1440 if (LGT == LibGccType::StaticLibGcc) 1441 CmdArgs.push_back("-lgcc_eh"); 1442 else 1443 CmdArgs.push_back("-lgcc_s"); 1444 break; 1445 } 1446 case ToolChain::UNW_CompilerRT: 1447 if (LGT == LibGccType::StaticLibGcc) 1448 CmdArgs.push_back("-l:libunwind.a"); 1449 else if (TC.getTriple().isOSCygMing()) { 1450 if (LGT == LibGccType::SharedLibGcc) 1451 CmdArgs.push_back("-l:libunwind.dll.a"); 1452 else 1453 // Let the linker choose between libunwind.dll.a and libunwind.a 1454 // depending on what's available, and depending on the -static flag 1455 CmdArgs.push_back("-lunwind"); 1456 } else 1457 CmdArgs.push_back("-l:libunwind.so"); 1458 break; 1459 } 1460 1461 if (AsNeeded) 1462 CmdArgs.push_back(getAsNeededOption(TC, false)); 1463} 1464 1465static void AddLibgcc(const ToolChain &TC, const Driver &D, 1466 ArgStringList &CmdArgs, const ArgList &Args) { 1467 LibGccType LGT = getLibGccType(TC, D, Args); 1468 if (LGT != LibGccType::SharedLibGcc) 1469 CmdArgs.push_back("-lgcc"); 1470 AddUnwindLibrary(TC, D, CmdArgs, Args); 1471 if (LGT == LibGccType::SharedLibGcc) 1472 CmdArgs.push_back("-lgcc"); 1473} 1474 1475void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1476 ArgStringList &CmdArgs, const ArgList &Args) { 1477 // Make use of compiler-rt if --rtlib option is used 1478 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1479 1480 switch (RLT) { 1481 case ToolChain::RLT_CompilerRT: 1482 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1483 AddUnwindLibrary(TC, D, CmdArgs, Args); 1484 break; 1485 case ToolChain::RLT_Libgcc: 1486 // Make sure libgcc is not used under MSVC environment by default 1487 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1488 // Issue error diagnostic if libgcc is explicitly specified 1489 // through command line as --rtlib option argument. 1490 if (Args.hasArg(options::OPT_rtlib_EQ)) { 1491 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1492 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC"; 1493 } 1494 } else 1495 AddLibgcc(TC, D, CmdArgs, Args); 1496 break; 1497 } 1498 1499 // On Android, the unwinder uses dl_iterate_phdr (or one of 1500 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For 1501 // statically-linked executables, these functions come from libc.a instead. 1502 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) && 1503 !Args.hasArg(options::OPT_static_pie)) 1504 CmdArgs.push_back("-ldl"); 1505} 1506 1507SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1508 const InputInfo &Output, 1509 const InputInfo &Input, 1510 const Driver &D) { 1511 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1512 if (!A) 1513 return {}; 1514 1515 StringRef SaveStats = A->getValue(); 1516 SmallString<128> StatsFile; 1517 if (SaveStats == "obj" && Output.isFilename()) { 1518 StatsFile.assign(Output.getFilename()); 1519 llvm::sys::path::remove_filename(StatsFile); 1520 } else if (SaveStats != "cwd") { 1521 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1522 return {}; 1523 } 1524 1525 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1526 llvm::sys::path::append(StatsFile, BaseName); 1527 llvm::sys::path::replace_extension(StatsFile, "stats"); 1528 return StatsFile; 1529} 1530 1531void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1532 Multilib::flags_list &Flags) { 1533 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1534} 1535 1536void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, 1537 ArgStringList &CmdArgs, bool IsLTO) { 1538 auto addArg = [&, IsLTO](const Twine &Arg) { 1539 if (IsLTO) { 1540 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg)); 1541 } else { 1542 CmdArgs.push_back("-mllvm"); 1543 CmdArgs.push_back(Args.MakeArgString(Arg)); 1544 } 1545 }; 1546 1547 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) { 1548 addArg(Twine("-x86-branches-within-32B-boundaries")); 1549 } 1550 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) { 1551 StringRef Value = A->getValue(); 1552 unsigned Boundary; 1553 if (Value.getAsInteger(10, Boundary) || Boundary < 16 || 1554 !llvm::isPowerOf2_64(Boundary)) { 1555 D.Diag(diag::err_drv_invalid_argument_to_option) 1556 << Value << A->getOption().getName(); 1557 } else { 1558 addArg("-x86-align-branch-boundary=" + Twine(Boundary)); 1559 } 1560 } 1561 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) { 1562 std::string AlignBranch; 1563 for (StringRef T : A->getValues()) { 1564 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && 1565 T != "ret" && T != "indirect") 1566 D.Diag(diag::err_drv_invalid_malign_branch_EQ) 1567 << T << "fused, jcc, jmp, call, ret, indirect"; 1568 if (!AlignBranch.empty()) 1569 AlignBranch += '+'; 1570 AlignBranch += T; 1571 } 1572 addArg("-x86-align-branch=" + Twine(AlignBranch)); 1573 } 1574 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) { 1575 StringRef Value = A->getValue(); 1576 unsigned PrefixSize; 1577 if (Value.getAsInteger(10, PrefixSize)) { 1578 D.Diag(diag::err_drv_invalid_argument_to_option) 1579 << Value << A->getOption().getName(); 1580 } else { 1581 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); 1582 } 1583 } 1584} 1585 1586static llvm::opt::Arg * 1587getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) { 1588 // The last of -mcode-object-v3, -mno-code-object-v3 and 1589 // -mcode-object-version=<version> wins. 1590 return Args.getLastArg(options::OPT_mcode_object_v3_legacy, 1591 options::OPT_mno_code_object_v3_legacy, 1592 options::OPT_mcode_object_version_EQ); 1593} 1594 1595void tools::checkAMDGPUCodeObjectVersion(const Driver &D, 1596 const llvm::opt::ArgList &Args) { 1597 const unsigned MinCodeObjVer = 2; 1598 const unsigned MaxCodeObjVer = 4; 1599 1600 // Emit warnings for legacy options even if they are overridden. 1601 if (Args.hasArg(options::OPT_mno_code_object_v3_legacy)) 1602 D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3" 1603 << "-mcode-object-version=2"; 1604 1605 if (Args.hasArg(options::OPT_mcode_object_v3_legacy)) 1606 D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3" 1607 << "-mcode-object-version=3"; 1608 1609 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 1610 if (CodeObjArg->getOption().getID() == 1611 options::OPT_mcode_object_version_EQ) { 1612 unsigned CodeObjVer = MaxCodeObjVer; 1613 auto Remnant = 1614 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 1615 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer) 1616 D.Diag(diag::err_drv_invalid_int_value) 1617 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); 1618 } 1619 } 1620} 1621 1622unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D, 1623 const llvm::opt::ArgList &Args) { 1624 unsigned CodeObjVer = 4; // default 1625 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 1626 if (CodeObjArg->getOption().getID() == 1627 options::OPT_mno_code_object_v3_legacy) { 1628 CodeObjVer = 2; 1629 } else if (CodeObjArg->getOption().getID() == 1630 options::OPT_mcode_object_v3_legacy) { 1631 CodeObjVer = 3; 1632 } else { 1633 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 1634 } 1635 } 1636 return CodeObjVer; 1637} 1638 1639bool tools::haveAMDGPUCodeObjectVersionArgument( 1640 const Driver &D, const llvm::opt::ArgList &Args) { 1641 return getAMDGPUCodeObjectArgument(D, Args) != nullptr; 1642} 1643 1644void tools::addMachineOutlinerArgs(const Driver &D, 1645 const llvm::opt::ArgList &Args, 1646 llvm::opt::ArgStringList &CmdArgs, 1647 const llvm::Triple &Triple, bool IsLTO) { 1648 auto addArg = [&, IsLTO](const Twine &Arg) { 1649 if (IsLTO) { 1650 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg)); 1651 } else { 1652 CmdArgs.push_back("-mllvm"); 1653 CmdArgs.push_back(Args.MakeArgString(Arg)); 1654 } 1655 }; 1656 1657 if (Arg *A = Args.getLastArg(options::OPT_moutline, 1658 options::OPT_mno_outline)) { 1659 if (A->getOption().matches(options::OPT_moutline)) { 1660 // We only support -moutline in AArch64 and ARM targets right now. If 1661 // we're not compiling for these, emit a warning and ignore the flag. 1662 // Otherwise, add the proper mllvm flags. 1663 if (!(Triple.isARM() || Triple.isThumb() || 1664 Triple.getArch() == llvm::Triple::aarch64 || 1665 Triple.getArch() == llvm::Triple::aarch64_32)) { 1666 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 1667 } else { 1668 addArg(Twine("-enable-machine-outliner")); 1669 } 1670 } else { 1671 // Disable all outlining behaviour. 1672 addArg(Twine("-enable-machine-outliner=never")); 1673 } 1674 } 1675} 1676 1677void tools::addOpenMPDeviceRTL(const Driver &D, 1678 const llvm::opt::ArgList &DriverArgs, 1679 llvm::opt::ArgStringList &CC1Args, 1680 StringRef BitcodeSuffix, 1681 const llvm::Triple &Triple) { 1682 SmallVector<StringRef, 8> LibraryPaths; 1683 // Add user defined library paths from LIBRARY_PATH. 1684 llvm::Optional<std::string> LibPath = 1685 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 1686 if (LibPath) { 1687 SmallVector<StringRef, 8> Frags; 1688 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 1689 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 1690 for (StringRef Path : Frags) 1691 LibraryPaths.emplace_back(Path.trim()); 1692 } 1693 1694 // Add path to lib / lib64 folder. 1695 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 1696 llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX); 1697 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 1698 1699 OptSpecifier LibomptargetBCPathOpt = 1700 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgcn_bc_path_EQ 1701 : options::OPT_libomptarget_nvptx_bc_path_EQ; 1702 1703 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgcn" : "nvptx"; 1704 // First check whether user specifies bc library 1705 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) { 1706 std::string LibOmpTargetName(A->getValue()); 1707 if (llvm::sys::fs::exists(LibOmpTargetName)) { 1708 CC1Args.push_back("-mlink-builtin-bitcode"); 1709 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName)); 1710 } else { 1711 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found) 1712 << LibOmpTargetName; 1713 } 1714 } else { 1715 bool FoundBCLibrary = false; 1716 1717 std::string LibOmpTargetName = 1718 "libomptarget-" + BitcodeSuffix.str() + ".bc"; 1719 1720 for (StringRef LibraryPath : LibraryPaths) { 1721 SmallString<128> LibOmpTargetFile(LibraryPath); 1722 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 1723 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 1724 CC1Args.push_back("-mlink-builtin-bitcode"); 1725 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 1726 FoundBCLibrary = true; 1727 break; 1728 } 1729 } 1730 1731 if (!FoundBCLibrary) 1732 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime) 1733 << LibOmpTargetName << ArchPrefix; 1734 } 1735} 1736