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 60 using namespace clang::driver; 61 using namespace clang::driver::tools; 62 using namespace clang; 63 using namespace llvm::opt; 64 65 static 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 79 static 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 109 static 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 121 void 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 127 void 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 145 std::vector<StringRef> 146 tools::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 170 void 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 224 void 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 275 void 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 293 void 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. 306 static 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 323 static 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. 331 static 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 349 std::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 463 llvm::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. 474 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 475 return Triple.getOS() == llvm::Triple::CloudABI; 476 } 477 478 void 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 554 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb"); 555 } 556 557 bool UseSeparateSections = 558 isUseSeparateSections(ToolChain.getEffectiveTriple()); 559 560 if (Args.hasFlag(options::OPT_ffunction_sections, 561 options::OPT_fno_function_sections, UseSeparateSections)) { 562 CmdArgs.push_back("-plugin-opt=-function-sections"); 563 } 564 565 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 566 UseSeparateSections)) { 567 CmdArgs.push_back("-plugin-opt=-data-sections"); 568 } 569 570 if (Arg *A = getLastProfileSampleUseArg(Args)) { 571 StringRef FName = A->getValue(); 572 if (!llvm::sys::fs::exists(FName)) 573 D.Diag(diag::err_drv_no_such_file) << FName; 574 else 575 CmdArgs.push_back( 576 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName)); 577 } 578 579 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 580 options::OPT_fcs_profile_generate_EQ, 581 options::OPT_fno_profile_generate); 582 if (CSPGOGenerateArg && 583 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 584 CSPGOGenerateArg = nullptr; 585 586 auto *ProfileUseArg = getLastProfileUseArg(Args); 587 588 if (CSPGOGenerateArg) { 589 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate")); 590 if (CSPGOGenerateArg->getOption().matches( 591 options::OPT_fcs_profile_generate_EQ)) { 592 SmallString<128> Path(CSPGOGenerateArg->getValue()); 593 llvm::sys::path::append(Path, "default_%m.profraw"); 594 CmdArgs.push_back( 595 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path)); 596 } else 597 CmdArgs.push_back( 598 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw")); 599 } else if (ProfileUseArg) { 600 SmallString<128> Path( 601 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 602 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 603 llvm::sys::path::append(Path, "default.profdata"); 604 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + 605 Path)); 606 } 607 608 // Pass an option to enable/disable the new pass manager. 609 if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager, 610 options::OPT_fno_legacy_pass_manager)) { 611 if (A->getOption().matches(options::OPT_flegacy_pass_manager)) 612 CmdArgs.push_back("-plugin-opt=legacy-pass-manager"); 613 else 614 CmdArgs.push_back("-plugin-opt=new-pass-manager"); 615 } 616 617 // Pass an option to enable pseudo probe emission. 618 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling, 619 options::OPT_fno_pseudo_probe_for_profiling, false)) 620 CmdArgs.push_back("-plugin-opt=pseudo-probe-for-profiling"); 621 622 // Setup statistics file output. 623 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 624 if (!StatsFile.empty()) 625 CmdArgs.push_back( 626 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile)); 627 628 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true); 629 630 // Handle remark diagnostics on screen options: '-Rpass-*'. 631 renderRpassOptions(Args, CmdArgs); 632 633 // Handle serialized remarks options: '-fsave-optimization-record' 634 // and '-foptimization-record-*'. 635 if (willEmitRemarks(Args)) 636 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input, 637 Output); 638 639 // Handle remarks hotness/threshold related options. 640 renderRemarksHotnessOptions(Args, CmdArgs); 641 642 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(), 643 /*IsLTO=*/true); 644 } 645 646 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 647 ArgStringList &CmdArgs) { 648 // Enable -frtlib-add-rpath by default for the case of VE. 649 const bool IsVE = TC.getTriple().isVE(); 650 bool DefaultValue = IsVE; 651 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 652 options::OPT_fno_rtlib_add_rpath, DefaultValue)) 653 return; 654 655 std::string CandidateRPath = TC.getArchSpecificLibPath(); 656 if (TC.getVFS().exists(CandidateRPath)) { 657 CmdArgs.push_back("-rpath"); 658 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str())); 659 } 660 } 661 662 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 663 const ArgList &Args, bool ForceStaticHostRuntime, 664 bool IsOffloadingHost, bool GompNeedsRT) { 665 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 666 options::OPT_fno_openmp, false)) 667 return false; 668 669 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 670 671 if (RTKind == Driver::OMPRT_Unknown) 672 // Already diagnosed. 673 return false; 674 675 if (ForceStaticHostRuntime) 676 CmdArgs.push_back("-Bstatic"); 677 678 switch (RTKind) { 679 case Driver::OMPRT_OMP: 680 CmdArgs.push_back("-lomp"); 681 break; 682 case Driver::OMPRT_GOMP: 683 CmdArgs.push_back("-lgomp"); 684 break; 685 case Driver::OMPRT_IOMP5: 686 CmdArgs.push_back("-liomp5"); 687 break; 688 case Driver::OMPRT_Unknown: 689 break; 690 } 691 692 if (ForceStaticHostRuntime) 693 CmdArgs.push_back("-Bdynamic"); 694 695 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 696 CmdArgs.push_back("-lrt"); 697 698 if (IsOffloadingHost) 699 CmdArgs.push_back("-lomptarget"); 700 701 addArchSpecificRPath(TC, Args, CmdArgs); 702 703 return true; 704 } 705 706 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 707 ArgStringList &CmdArgs, StringRef Sanitizer, 708 bool IsShared, bool IsWhole) { 709 // Wrap any static runtimes that must be forced into executable in 710 // whole-archive. 711 if (IsWhole) CmdArgs.push_back("--whole-archive"); 712 CmdArgs.push_back(TC.getCompilerRTArgString( 713 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 714 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 715 716 if (IsShared) { 717 addArchSpecificRPath(TC, Args, CmdArgs); 718 } 719 } 720 721 // Tries to use a file with the list of dynamic symbols that need to be exported 722 // from the runtime library. Returns true if the file was found. 723 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 724 ArgStringList &CmdArgs, 725 StringRef Sanitizer) { 726 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 727 // the option, so don't try to pass it. 728 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 729 return true; 730 // Myriad is static linking only. Furthermore, some versions of its 731 // linker have the bug where --export-dynamic overrides -static, so 732 // don't use --export-dynamic on that platform. 733 if (TC.getTriple().getVendor() == llvm::Triple::Myriad) 734 return true; 735 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 736 if (llvm::sys::fs::exists(SanRT + ".syms")) { 737 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 738 return true; 739 } 740 return false; 741 } 742 743 static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) { 744 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases 745 // for the native forms -z ignore/-z record, they are missing in Illumos, 746 // so always use the native form. 747 if (TC.getTriple().isOSSolaris()) 748 return as_needed ? "-zignore" : "-zrecord"; 749 else 750 return as_needed ? "--as-needed" : "--no-as-needed"; 751 } 752 753 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 754 ArgStringList &CmdArgs) { 755 // Fuchsia never needs these. Any sanitizer runtimes with system 756 // dependencies use the `.deplibs` feature instead. 757 if (TC.getTriple().isOSFuchsia()) 758 return; 759 760 // Force linking against the system libraries sanitizers depends on 761 // (see PR15823 why this is necessary). 762 CmdArgs.push_back(getAsNeededOption(TC, false)); 763 // There's no libpthread or librt on RTEMS & Android. 764 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 765 !TC.getTriple().isAndroid()) { 766 CmdArgs.push_back("-lpthread"); 767 if (!TC.getTriple().isOSOpenBSD()) 768 CmdArgs.push_back("-lrt"); 769 } 770 CmdArgs.push_back("-lm"); 771 // There's no libdl on all OSes. 772 if (!TC.getTriple().isOSFreeBSD() && 773 !TC.getTriple().isOSNetBSD() && 774 !TC.getTriple().isOSOpenBSD() && 775 TC.getTriple().getOS() != llvm::Triple::RTEMS) 776 CmdArgs.push_back("-ldl"); 777 // Required for backtrace on some OSes 778 if (TC.getTriple().isOSFreeBSD() || 779 TC.getTriple().isOSNetBSD()) 780 CmdArgs.push_back("-lexecinfo"); 781 } 782 783 static void 784 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 785 SmallVectorImpl<StringRef> &SharedRuntimes, 786 SmallVectorImpl<StringRef> &StaticRuntimes, 787 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 788 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 789 SmallVectorImpl<StringRef> &RequiredSymbols) { 790 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 791 // Collect shared runtimes. 792 if (SanArgs.needsSharedRt()) { 793 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 794 SharedRuntimes.push_back("asan"); 795 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 796 HelperStaticRuntimes.push_back("asan-preinit"); 797 } 798 if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) { 799 SharedRuntimes.push_back("memprof"); 800 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 801 HelperStaticRuntimes.push_back("memprof-preinit"); 802 } 803 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 804 if (SanArgs.requiresMinimalRuntime()) 805 SharedRuntimes.push_back("ubsan_minimal"); 806 else 807 SharedRuntimes.push_back("ubsan_standalone"); 808 } 809 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 810 if (SanArgs.requiresMinimalRuntime()) 811 SharedRuntimes.push_back("scudo_minimal"); 812 else 813 SharedRuntimes.push_back("scudo"); 814 } 815 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) 816 SharedRuntimes.push_back("tsan"); 817 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) 818 SharedRuntimes.push_back("hwasan"); 819 } 820 821 // The stats_client library is also statically linked into DSOs. 822 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 823 StaticRuntimes.push_back("stats_client"); 824 825 // Collect static runtimes. 826 if (Args.hasArg(options::OPT_shared)) { 827 // Don't link static runtimes into DSOs. 828 return; 829 } 830 831 // Each static runtime that has a DSO counterpart above is excluded below, 832 // but runtimes that exist only as static are not affected by needsSharedRt. 833 834 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 835 StaticRuntimes.push_back("asan"); 836 if (SanArgs.linkCXXRuntimes()) 837 StaticRuntimes.push_back("asan_cxx"); 838 } 839 840 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() && 841 SanArgs.linkRuntimes()) { 842 StaticRuntimes.push_back("memprof"); 843 if (SanArgs.linkCXXRuntimes()) 844 StaticRuntimes.push_back("memprof_cxx"); 845 } 846 847 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 848 StaticRuntimes.push_back("hwasan"); 849 if (SanArgs.linkCXXRuntimes()) 850 StaticRuntimes.push_back("hwasan_cxx"); 851 } 852 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes()) 853 StaticRuntimes.push_back("dfsan"); 854 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes()) 855 StaticRuntimes.push_back("lsan"); 856 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) { 857 StaticRuntimes.push_back("msan"); 858 if (SanArgs.linkCXXRuntimes()) 859 StaticRuntimes.push_back("msan_cxx"); 860 } 861 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() && 862 SanArgs.linkRuntimes()) { 863 StaticRuntimes.push_back("tsan"); 864 if (SanArgs.linkCXXRuntimes()) 865 StaticRuntimes.push_back("tsan_cxx"); 866 } 867 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 868 if (SanArgs.requiresMinimalRuntime()) { 869 StaticRuntimes.push_back("ubsan_minimal"); 870 } else { 871 StaticRuntimes.push_back("ubsan_standalone"); 872 if (SanArgs.linkCXXRuntimes()) 873 StaticRuntimes.push_back("ubsan_standalone_cxx"); 874 } 875 } 876 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) { 877 NonWholeStaticRuntimes.push_back("safestack"); 878 RequiredSymbols.push_back("__safestack_init"); 879 } 880 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) { 881 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes()) 882 StaticRuntimes.push_back("cfi"); 883 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) { 884 StaticRuntimes.push_back("cfi_diag"); 885 if (SanArgs.linkCXXRuntimes()) 886 StaticRuntimes.push_back("ubsan_standalone_cxx"); 887 } 888 } 889 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) { 890 NonWholeStaticRuntimes.push_back("stats"); 891 RequiredSymbols.push_back("__sanitizer_stats_register"); 892 } 893 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 894 if (SanArgs.requiresMinimalRuntime()) { 895 StaticRuntimes.push_back("scudo_minimal"); 896 if (SanArgs.linkCXXRuntimes()) 897 StaticRuntimes.push_back("scudo_cxx_minimal"); 898 } else { 899 StaticRuntimes.push_back("scudo"); 900 if (SanArgs.linkCXXRuntimes()) 901 StaticRuntimes.push_back("scudo_cxx"); 902 } 903 } 904 } 905 906 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 907 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 908 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 909 ArgStringList &CmdArgs) { 910 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 911 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 912 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 913 NonWholeStaticRuntimes, HelperStaticRuntimes, 914 RequiredSymbols); 915 916 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 917 // Inject libfuzzer dependencies. 918 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 919 !Args.hasArg(options::OPT_shared)) { 920 921 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 922 if (SanArgs.needsFuzzerInterceptors()) 923 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false, 924 true); 925 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) { 926 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && 927 !Args.hasArg(options::OPT_static); 928 if (OnlyLibstdcxxStatic) 929 CmdArgs.push_back("-Bstatic"); 930 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 931 if (OnlyLibstdcxxStatic) 932 CmdArgs.push_back("-Bdynamic"); 933 } 934 } 935 936 for (auto RT : SharedRuntimes) 937 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 938 for (auto RT : HelperStaticRuntimes) 939 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 940 bool AddExportDynamic = false; 941 for (auto RT : StaticRuntimes) { 942 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 943 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 944 } 945 for (auto RT : NonWholeStaticRuntimes) { 946 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 947 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 948 } 949 for (auto S : RequiredSymbols) { 950 CmdArgs.push_back("-u"); 951 CmdArgs.push_back(Args.MakeArgString(S)); 952 } 953 // If there is a static runtime with no dynamic list, force all the symbols 954 // to be dynamic to be sure we export sanitizer interface functions. 955 if (AddExportDynamic) 956 CmdArgs.push_back("--export-dynamic"); 957 958 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 959 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check"); 960 961 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 962 } 963 964 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 965 if (Args.hasArg(options::OPT_shared)) 966 return false; 967 968 if (TC.getXRayArgs().needsXRayRt()) { 969 CmdArgs.push_back("-whole-archive"); 970 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 971 for (const auto &Mode : TC.getXRayArgs().modeList()) 972 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 973 CmdArgs.push_back("-no-whole-archive"); 974 return true; 975 } 976 977 return false; 978 } 979 980 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) { 981 CmdArgs.push_back(getAsNeededOption(TC, false)); 982 CmdArgs.push_back("-lpthread"); 983 if (!TC.getTriple().isOSOpenBSD()) 984 CmdArgs.push_back("-lrt"); 985 CmdArgs.push_back("-lm"); 986 987 if (!TC.getTriple().isOSFreeBSD() && 988 !TC.getTriple().isOSNetBSD() && 989 !TC.getTriple().isOSOpenBSD()) 990 CmdArgs.push_back("-ldl"); 991 } 992 993 bool tools::areOptimizationsEnabled(const ArgList &Args) { 994 // Find the last -O arg and see if it is non-zero. 995 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 996 return !A->getOption().matches(options::OPT_O0); 997 // Defaults to -O0. 998 return false; 999 } 1000 1001 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args, 1002 const InputInfo &Input, 1003 const InputInfo &Output) { 1004 auto AddPostfix = [JA](auto &F) { 1005 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP) 1006 F += (Twine("_") + JA.getOffloadingArch()).str(); 1007 F += ".dwo"; 1008 }; 1009 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 1010 if (StringRef(A->getValue()) == "single") 1011 return Args.MakeArgString(Output.getFilename()); 1012 1013 Arg *FinalOutput = Args.getLastArg(options::OPT_o); 1014 if (FinalOutput && Args.hasArg(options::OPT_c)) { 1015 SmallString<128> T(FinalOutput->getValue()); 1016 llvm::sys::path::remove_filename(T); 1017 llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue())); 1018 AddPostfix(T); 1019 return Args.MakeArgString(T); 1020 } else { 1021 // Use the compilation dir. 1022 Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ, 1023 options::OPT_fdebug_compilation_dir_EQ); 1024 SmallString<128> T(A ? A->getValue() : ""); 1025 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput())); 1026 AddPostfix(F); 1027 T += F; 1028 return Args.MakeArgString(T); 1029 } 1030 } 1031 1032 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 1033 const JobAction &JA, const ArgList &Args, 1034 const InputInfo &Output, const char *OutFile) { 1035 ArgStringList ExtractArgs; 1036 ExtractArgs.push_back("--extract-dwo"); 1037 1038 ArgStringList StripArgs; 1039 StripArgs.push_back("--strip-dwo"); 1040 1041 // Grabbing the output of the earlier compile step. 1042 StripArgs.push_back(Output.getFilename()); 1043 ExtractArgs.push_back(Output.getFilename()); 1044 ExtractArgs.push_back(OutFile); 1045 1046 const char *Exec = 1047 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 1048 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 1049 1050 // First extract the dwo sections. 1051 C.addCommand(std::make_unique<Command>(JA, T, 1052 ResponseFileSupport::AtFileCurCP(), 1053 Exec, ExtractArgs, II, Output)); 1054 1055 // Then remove them from the original .o file. 1056 C.addCommand(std::make_unique<Command>( 1057 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output)); 1058 } 1059 1060 // Claim options we don't want to warn if they are unused. We do this for 1061 // options that build systems might add but are unused when assembling or only 1062 // running the preprocessor for example. 1063 void tools::claimNoWarnArgs(const ArgList &Args) { 1064 // Don't warn about unused -f(no-)?lto. This can happen when we're 1065 // preprocessing, precompiling or assembling. 1066 Args.ClaimAllArgs(options::OPT_flto_EQ); 1067 Args.ClaimAllArgs(options::OPT_flto); 1068 Args.ClaimAllArgs(options::OPT_fno_lto); 1069 } 1070 1071 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 1072 auto *ProfileUseArg = Args.getLastArg( 1073 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 1074 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 1075 options::OPT_fno_profile_instr_use); 1076 1077 if (ProfileUseArg && 1078 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 1079 ProfileUseArg = nullptr; 1080 1081 return ProfileUseArg; 1082 } 1083 1084 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 1085 auto *ProfileSampleUseArg = Args.getLastArg( 1086 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 1087 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 1088 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 1089 1090 if (ProfileSampleUseArg && 1091 (ProfileSampleUseArg->getOption().matches( 1092 options::OPT_fno_profile_sample_use) || 1093 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 1094 return nullptr; 1095 1096 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 1097 options::OPT_fauto_profile_EQ); 1098 } 1099 1100 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 1101 /// smooshes them together with platform defaults, to decide whether 1102 /// this compile should be using PIC mode or not. Returns a tuple of 1103 /// (RelocationModel, PICLevel, IsPIE). 1104 std::tuple<llvm::Reloc::Model, unsigned, bool> 1105 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 1106 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 1107 const llvm::Triple &Triple = ToolChain.getTriple(); 1108 1109 bool PIE = ToolChain.isPIEDefault(); 1110 bool PIC = PIE || ToolChain.isPICDefault(); 1111 // The Darwin/MachO default to use PIC does not apply when using -static. 1112 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 1113 PIE = PIC = false; 1114 bool IsPICLevelTwo = PIC; 1115 1116 bool KernelOrKext = 1117 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 1118 1119 // Android-specific defaults for PIC/PIE 1120 if (Triple.isAndroid()) { 1121 switch (Triple.getArch()) { 1122 case llvm::Triple::arm: 1123 case llvm::Triple::armeb: 1124 case llvm::Triple::thumb: 1125 case llvm::Triple::thumbeb: 1126 case llvm::Triple::aarch64: 1127 case llvm::Triple::mips: 1128 case llvm::Triple::mipsel: 1129 case llvm::Triple::mips64: 1130 case llvm::Triple::mips64el: 1131 PIC = true; // "-fpic" 1132 break; 1133 1134 case llvm::Triple::x86: 1135 case llvm::Triple::x86_64: 1136 PIC = true; // "-fPIC" 1137 IsPICLevelTwo = true; 1138 break; 1139 1140 default: 1141 break; 1142 } 1143 } 1144 1145 // OpenBSD-specific defaults for PIE 1146 if (Triple.isOSOpenBSD()) { 1147 switch (ToolChain.getArch()) { 1148 case llvm::Triple::arm: 1149 case llvm::Triple::aarch64: 1150 case llvm::Triple::mips64: 1151 case llvm::Triple::mips64el: 1152 case llvm::Triple::x86: 1153 case llvm::Triple::x86_64: 1154 IsPICLevelTwo = false; // "-fpie" 1155 break; 1156 1157 case llvm::Triple::ppc: 1158 case llvm::Triple::sparcv9: 1159 IsPICLevelTwo = true; // "-fPIE" 1160 break; 1161 1162 default: 1163 break; 1164 } 1165 } 1166 1167 // AMDGPU-specific defaults for PIC. 1168 if (Triple.getArch() == llvm::Triple::amdgcn) 1169 PIC = true; 1170 1171 // The last argument relating to either PIC or PIE wins, and no 1172 // other argument is used. If the last argument is any flavor of the 1173 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 1174 // option implicitly enables PIC at the same level. 1175 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 1176 options::OPT_fpic, options::OPT_fno_pic, 1177 options::OPT_fPIE, options::OPT_fno_PIE, 1178 options::OPT_fpie, options::OPT_fno_pie); 1179 if (Triple.isOSWindows() && LastPICArg && 1180 LastPICArg == 1181 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 1182 options::OPT_fPIE, options::OPT_fpie)) { 1183 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1184 << LastPICArg->getSpelling() << Triple.str(); 1185 if (Triple.getArch() == llvm::Triple::x86_64) 1186 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 1187 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1188 } 1189 1190 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 1191 // is forced, then neither PIC nor PIE flags will have no effect. 1192 if (!ToolChain.isPICDefaultForced()) { 1193 if (LastPICArg) { 1194 Option O = LastPICArg->getOption(); 1195 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 1196 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 1197 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1198 PIC = 1199 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1200 IsPICLevelTwo = 1201 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1202 } else { 1203 PIE = PIC = false; 1204 if (EffectiveTriple.isPS4CPU()) { 1205 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1206 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1207 if (Model != "kernel") { 1208 PIC = true; 1209 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic) 1210 << LastPICArg->getSpelling(); 1211 } 1212 } 1213 } 1214 } 1215 } 1216 1217 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the 1218 // PIC level would've been set to level 1, force it back to level 2 PIC 1219 // instead. 1220 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU())) 1221 IsPICLevelTwo |= ToolChain.isPICDefault(); 1222 1223 // This kernel flags are a trump-card: they will disable PIC/PIE 1224 // generation, independent of the argument order. 1225 if (KernelOrKext && 1226 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1227 !EffectiveTriple.isWatchOS())) 1228 PIC = PIE = false; 1229 1230 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1231 // This is a very special mode. It trumps the other modes, almost no one 1232 // uses it, and it isn't even valid on any OS but Darwin. 1233 if (!Triple.isOSDarwin()) 1234 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1235 << A->getSpelling() << Triple.str(); 1236 1237 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1238 1239 // Only a forced PIC mode can cause the actual compile to have PIC defines 1240 // etc., no flags are sufficient. This behavior was selected to closely 1241 // match that of llvm-gcc and Apple GCC before that. 1242 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1243 1244 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1245 } 1246 1247 bool EmbeddedPISupported; 1248 switch (Triple.getArch()) { 1249 case llvm::Triple::arm: 1250 case llvm::Triple::armeb: 1251 case llvm::Triple::thumb: 1252 case llvm::Triple::thumbeb: 1253 EmbeddedPISupported = true; 1254 break; 1255 default: 1256 EmbeddedPISupported = false; 1257 break; 1258 } 1259 1260 bool ROPI = false, RWPI = false; 1261 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1262 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1263 if (!EmbeddedPISupported) 1264 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1265 << LastROPIArg->getSpelling() << Triple.str(); 1266 ROPI = true; 1267 } 1268 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1269 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1270 if (!EmbeddedPISupported) 1271 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1272 << LastRWPIArg->getSpelling() << Triple.str(); 1273 RWPI = true; 1274 } 1275 1276 // ROPI and RWPI are not compatible with PIC or PIE. 1277 if ((ROPI || RWPI) && (PIC || PIE)) 1278 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1279 1280 if (Triple.isMIPS()) { 1281 StringRef CPUName; 1282 StringRef ABIName; 1283 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1284 // When targeting the N64 ABI, PIC is the default, except in the case 1285 // when the -mno-abicalls option is used. In that case we exit 1286 // at next check regardless of PIC being set below. 1287 if (ABIName == "n64") 1288 PIC = true; 1289 // When targettng MIPS with -mno-abicalls, it's always static. 1290 if(Args.hasArg(options::OPT_mno_abicalls)) 1291 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1292 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1293 // does not use PIC level 2 for historical reasons. 1294 IsPICLevelTwo = false; 1295 } 1296 1297 if (PIC) 1298 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1299 1300 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1301 if (ROPI && RWPI) 1302 RelocM = llvm::Reloc::ROPI_RWPI; 1303 else if (ROPI) 1304 RelocM = llvm::Reloc::ROPI; 1305 else if (RWPI) 1306 RelocM = llvm::Reloc::RWPI; 1307 1308 return std::make_tuple(RelocM, 0U, false); 1309 } 1310 1311 // `-falign-functions` indicates that the functions should be aligned to a 1312 // 16-byte boundary. 1313 // 1314 // `-falign-functions=1` is the same as `-fno-align-functions`. 1315 // 1316 // The scalar `n` in `-falign-functions=n` must be an integral value between 1317 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1318 // the nearest power-of-two. 1319 // 1320 // If we return `0`, the frontend will default to the backend's preferred 1321 // alignment. 1322 // 1323 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1324 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1325 // alignment. For unaligned functions, we default to the backend's preferred 1326 // alignment. 1327 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1328 const ArgList &Args) { 1329 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1330 options::OPT_falign_functions_EQ, 1331 options::OPT_fno_align_functions); 1332 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1333 return 0; 1334 1335 if (A->getOption().matches(options::OPT_falign_functions)) 1336 return 0; 1337 1338 unsigned Value = 0; 1339 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1340 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1341 << A->getAsString(Args) << A->getValue(); 1342 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1343 } 1344 1345 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC, 1346 const ArgList &Args) { 1347 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 1348 1349 if (!A) 1350 return 0; 1351 1352 unsigned Value = 0; 1353 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 1354 Value < 2) 1355 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1356 << A->getAsString(Args) << A->getValue(); 1357 return Value; 1358 } 1359 1360 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1361 ArgStringList &CmdArgs) { 1362 llvm::Reloc::Model RelocationModel; 1363 unsigned PICLevel; 1364 bool IsPIE; 1365 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1366 1367 if (RelocationModel != llvm::Reloc::Static) 1368 CmdArgs.push_back("-KPIC"); 1369 } 1370 1371 /// Determine whether Objective-C automated reference counting is 1372 /// enabled. 1373 bool tools::isObjCAutoRefCount(const ArgList &Args) { 1374 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1375 } 1376 1377 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1378 1379 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, 1380 const ArgList &Args) { 1381 if (Args.hasArg(options::OPT_static_libgcc) || 1382 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie)) 1383 return LibGccType::StaticLibGcc; 1384 if (Args.hasArg(options::OPT_shared_libgcc)) 1385 return LibGccType::SharedLibGcc; 1386 // The Android NDK only provides libunwind.a, not libunwind.so. 1387 if (TC.getTriple().isAndroid()) 1388 return LibGccType::StaticLibGcc; 1389 // For MinGW, don't imply a shared libgcc here, we only want to return 1390 // SharedLibGcc if that was explicitly requested. 1391 if (D.CCCIsCXX() && !TC.getTriple().isOSCygMing()) 1392 return LibGccType::SharedLibGcc; 1393 return LibGccType::UnspecifiedLibGcc; 1394 } 1395 1396 // Gcc adds libgcc arguments in various ways: 1397 // 1398 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1399 // g++ <none>: -lgcc_s -lgcc 1400 // gcc shared: -lgcc_s -lgcc 1401 // g++ shared: -lgcc_s -lgcc 1402 // gcc static: -lgcc -lgcc_eh 1403 // g++ static: -lgcc -lgcc_eh 1404 // gcc static-pie: -lgcc -lgcc_eh 1405 // g++ static-pie: -lgcc -lgcc_eh 1406 // 1407 // Also, certain targets need additional adjustments. 1408 1409 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1410 ArgStringList &CmdArgs, const ArgList &Args) { 1411 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1412 // Targets that don't use unwind libraries. 1413 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || 1414 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || 1415 UNW == ToolChain::UNW_None) 1416 return; 1417 1418 LibGccType LGT = getLibGccType(TC, D, Args); 1419 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1420 !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing(); 1421 if (AsNeeded) 1422 CmdArgs.push_back(getAsNeededOption(TC, true)); 1423 1424 switch (UNW) { 1425 case ToolChain::UNW_None: 1426 return; 1427 case ToolChain::UNW_Libgcc: { 1428 if (LGT == LibGccType::StaticLibGcc) 1429 CmdArgs.push_back("-lgcc_eh"); 1430 else 1431 CmdArgs.push_back("-lgcc_s"); 1432 break; 1433 } 1434 case ToolChain::UNW_CompilerRT: 1435 if (LGT == LibGccType::StaticLibGcc) 1436 CmdArgs.push_back("-l:libunwind.a"); 1437 else if (TC.getTriple().isOSCygMing()) { 1438 if (LGT == LibGccType::SharedLibGcc) 1439 CmdArgs.push_back("-l:libunwind.dll.a"); 1440 else 1441 // Let the linker choose between libunwind.dll.a and libunwind.a 1442 // depending on what's available, and depending on the -static flag 1443 CmdArgs.push_back("-lunwind"); 1444 } else 1445 CmdArgs.push_back("-l:libunwind.so"); 1446 break; 1447 } 1448 1449 if (AsNeeded) 1450 CmdArgs.push_back(getAsNeededOption(TC, false)); 1451 } 1452 1453 static void AddLibgcc(const ToolChain &TC, const Driver &D, 1454 ArgStringList &CmdArgs, const ArgList &Args) { 1455 LibGccType LGT = getLibGccType(TC, D, Args); 1456 if (LGT != LibGccType::SharedLibGcc) 1457 CmdArgs.push_back("-lgcc"); 1458 AddUnwindLibrary(TC, D, CmdArgs, Args); 1459 if (LGT == LibGccType::SharedLibGcc) 1460 CmdArgs.push_back("-lgcc"); 1461 } 1462 1463 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1464 ArgStringList &CmdArgs, const ArgList &Args) { 1465 // Make use of compiler-rt if --rtlib option is used 1466 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1467 1468 switch (RLT) { 1469 case ToolChain::RLT_CompilerRT: 1470 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1471 AddUnwindLibrary(TC, D, CmdArgs, Args); 1472 break; 1473 case ToolChain::RLT_Libgcc: 1474 // Make sure libgcc is not used under MSVC environment by default 1475 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1476 // Issue error diagnostic if libgcc is explicitly specified 1477 // through command line as --rtlib option argument. 1478 if (Args.hasArg(options::OPT_rtlib_EQ)) { 1479 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1480 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC"; 1481 } 1482 } else 1483 AddLibgcc(TC, D, CmdArgs, Args); 1484 break; 1485 } 1486 1487 // On Android, the unwinder uses dl_iterate_phdr (or one of 1488 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For 1489 // statically-linked executables, these functions come from libc.a instead. 1490 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) && 1491 !Args.hasArg(options::OPT_static_pie)) 1492 CmdArgs.push_back("-ldl"); 1493 } 1494 1495 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1496 const InputInfo &Output, 1497 const InputInfo &Input, 1498 const Driver &D) { 1499 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1500 if (!A) 1501 return {}; 1502 1503 StringRef SaveStats = A->getValue(); 1504 SmallString<128> StatsFile; 1505 if (SaveStats == "obj" && Output.isFilename()) { 1506 StatsFile.assign(Output.getFilename()); 1507 llvm::sys::path::remove_filename(StatsFile); 1508 } else if (SaveStats != "cwd") { 1509 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1510 return {}; 1511 } 1512 1513 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1514 llvm::sys::path::append(StatsFile, BaseName); 1515 llvm::sys::path::replace_extension(StatsFile, "stats"); 1516 return StatsFile; 1517 } 1518 1519 void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1520 Multilib::flags_list &Flags) { 1521 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1522 } 1523 1524 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, 1525 ArgStringList &CmdArgs, bool IsLTO) { 1526 auto addArg = [&, IsLTO](const Twine &Arg) { 1527 if (IsLTO) { 1528 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg)); 1529 } else { 1530 CmdArgs.push_back("-mllvm"); 1531 CmdArgs.push_back(Args.MakeArgString(Arg)); 1532 } 1533 }; 1534 1535 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) { 1536 addArg(Twine("-x86-branches-within-32B-boundaries")); 1537 } 1538 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) { 1539 StringRef Value = A->getValue(); 1540 unsigned Boundary; 1541 if (Value.getAsInteger(10, Boundary) || Boundary < 16 || 1542 !llvm::isPowerOf2_64(Boundary)) { 1543 D.Diag(diag::err_drv_invalid_argument_to_option) 1544 << Value << A->getOption().getName(); 1545 } else { 1546 addArg("-x86-align-branch-boundary=" + Twine(Boundary)); 1547 } 1548 } 1549 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) { 1550 std::string AlignBranch; 1551 for (StringRef T : A->getValues()) { 1552 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && 1553 T != "ret" && T != "indirect") 1554 D.Diag(diag::err_drv_invalid_malign_branch_EQ) 1555 << T << "fused, jcc, jmp, call, ret, indirect"; 1556 if (!AlignBranch.empty()) 1557 AlignBranch += '+'; 1558 AlignBranch += T; 1559 } 1560 addArg("-x86-align-branch=" + Twine(AlignBranch)); 1561 } 1562 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) { 1563 StringRef Value = A->getValue(); 1564 unsigned PrefixSize; 1565 if (Value.getAsInteger(10, PrefixSize)) { 1566 D.Diag(diag::err_drv_invalid_argument_to_option) 1567 << Value << A->getOption().getName(); 1568 } else { 1569 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); 1570 } 1571 } 1572 } 1573 1574 unsigned tools::getOrCheckAMDGPUCodeObjectVersion( 1575 const Driver &D, const llvm::opt::ArgList &Args, bool Diagnose) { 1576 const unsigned MinCodeObjVer = 2; 1577 const unsigned MaxCodeObjVer = 4; 1578 unsigned CodeObjVer = 3; 1579 1580 // Emit warnings for legacy options even if they are overridden. 1581 if (Diagnose) { 1582 if (Args.hasArg(options::OPT_mno_code_object_v3_legacy)) 1583 D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3" 1584 << "-mcode-object-version=2"; 1585 1586 if (Args.hasArg(options::OPT_mcode_object_v3_legacy)) 1587 D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3" 1588 << "-mcode-object-version=3"; 1589 } 1590 1591 // The last of -mcode-object-v3, -mno-code-object-v3 and 1592 // -mcode-object-version=<version> wins. 1593 if (auto *CodeObjArg = 1594 Args.getLastArg(options::OPT_mcode_object_v3_legacy, 1595 options::OPT_mno_code_object_v3_legacy, 1596 options::OPT_mcode_object_version_EQ)) { 1597 if (CodeObjArg->getOption().getID() == 1598 options::OPT_mno_code_object_v3_legacy) { 1599 CodeObjVer = 2; 1600 } else if (CodeObjArg->getOption().getID() == 1601 options::OPT_mcode_object_v3_legacy) { 1602 CodeObjVer = 3; 1603 } else { 1604 auto Remnant = 1605 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 1606 if (Diagnose && 1607 (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)) 1608 D.Diag(diag::err_drv_invalid_int_value) 1609 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); 1610 } 1611 } 1612 return CodeObjVer; 1613 } 1614 1615 void tools::addMachineOutlinerArgs(const Driver &D, 1616 const llvm::opt::ArgList &Args, 1617 llvm::opt::ArgStringList &CmdArgs, 1618 const llvm::Triple &Triple, bool IsLTO) { 1619 auto addArg = [&, IsLTO](const Twine &Arg) { 1620 if (IsLTO) { 1621 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg)); 1622 } else { 1623 CmdArgs.push_back("-mllvm"); 1624 CmdArgs.push_back(Args.MakeArgString(Arg)); 1625 } 1626 }; 1627 1628 if (Arg *A = Args.getLastArg(options::OPT_moutline, 1629 options::OPT_mno_outline)) { 1630 if (A->getOption().matches(options::OPT_moutline)) { 1631 // We only support -moutline in AArch64 and ARM targets right now. If 1632 // we're not compiling for these, emit a warning and ignore the flag. 1633 // Otherwise, add the proper mllvm flags. 1634 if (!(Triple.isARM() || Triple.isThumb() || 1635 Triple.getArch() == llvm::Triple::aarch64 || 1636 Triple.getArch() == llvm::Triple::aarch64_32)) { 1637 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 1638 } else { 1639 addArg(Twine("-enable-machine-outliner")); 1640 } 1641 } else { 1642 // Disable all outlining behaviour. 1643 addArg(Twine("-enable-machine-outliner=never")); 1644 } 1645 } 1646 } 1647 1648 void tools::addOpenMPDeviceRTL(const Driver &D, 1649 const llvm::opt::ArgList &DriverArgs, 1650 llvm::opt::ArgStringList &CC1Args, 1651 StringRef BitcodeSuffix, 1652 const llvm::Triple &Triple) { 1653 SmallVector<StringRef, 8> LibraryPaths; 1654 // Add user defined library paths from LIBRARY_PATH. 1655 llvm::Optional<std::string> LibPath = 1656 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 1657 if (LibPath) { 1658 SmallVector<StringRef, 8> Frags; 1659 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 1660 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 1661 for (StringRef Path : Frags) 1662 LibraryPaths.emplace_back(Path.trim()); 1663 } 1664 1665 // Add path to lib / lib64 folder. 1666 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 1667 llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX); 1668 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 1669 1670 OptSpecifier LibomptargetBCPathOpt = 1671 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgcn_bc_path_EQ 1672 : options::OPT_libomptarget_nvptx_bc_path_EQ; 1673 1674 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgcn" : "nvptx"; 1675 // First check whether user specifies bc library 1676 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) { 1677 std::string LibOmpTargetName(A->getValue()); 1678 if (llvm::sys::fs::exists(LibOmpTargetName)) { 1679 CC1Args.push_back("-mlink-builtin-bitcode"); 1680 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName)); 1681 } else { 1682 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found) 1683 << LibOmpTargetName; 1684 } 1685 } else { 1686 bool FoundBCLibrary = false; 1687 1688 std::string LibOmpTargetName = 1689 "libomptarget-" + BitcodeSuffix.str() + ".bc"; 1690 1691 for (StringRef LibraryPath : LibraryPaths) { 1692 SmallString<128> LibOmpTargetFile(LibraryPath); 1693 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 1694 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 1695 CC1Args.push_back("-mlink-builtin-bitcode"); 1696 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 1697 FoundBCLibrary = true; 1698 break; 1699 } 1700 } 1701 1702 if (!FoundBCLibrary) 1703 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime) 1704 << LibOmpTargetName << ArchPrefix; 1705 } 1706 } 1707