1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "CommonArgs.h" 10 #include "Arch/AArch64.h" 11 #include "Arch/ARM.h" 12 #include "Arch/CSKY.h" 13 #include "Arch/LoongArch.h" 14 #include "Arch/M68k.h" 15 #include "Arch/Mips.h" 16 #include "Arch/PPC.h" 17 #include "Arch/RISCV.h" 18 #include "Arch/Sparc.h" 19 #include "Arch/SystemZ.h" 20 #include "Arch/VE.h" 21 #include "Arch/X86.h" 22 #include "BareMetal.h" 23 #include "HIPAMD.h" 24 #include "Hexagon.h" 25 #include "MSP430.h" 26 #include "Solaris.h" 27 #include "clang/Basic/CharInfo.h" 28 #include "clang/Basic/CodeGenOptions.h" 29 #include "clang/Basic/LangOptions.h" 30 #include "clang/Basic/ObjCRuntime.h" 31 #include "clang/Basic/Version.h" 32 #include "clang/Config/config.h" 33 #include "clang/Driver/Action.h" 34 #include "clang/Driver/Compilation.h" 35 #include "clang/Driver/Driver.h" 36 #include "clang/Driver/DriverDiagnostic.h" 37 #include "clang/Driver/InputInfo.h" 38 #include "clang/Driver/Job.h" 39 #include "clang/Driver/Options.h" 40 #include "clang/Driver/SanitizerArgs.h" 41 #include "clang/Driver/ToolChain.h" 42 #include "clang/Driver/Util.h" 43 #include "clang/Driver/XRayArgs.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/SmallSet.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/StringExtras.h" 48 #include "llvm/ADT/StringSwitch.h" 49 #include "llvm/ADT/Twine.h" 50 #include "llvm/BinaryFormat/Magic.h" 51 #include "llvm/Config/llvm-config.h" 52 #include "llvm/Option/Arg.h" 53 #include "llvm/Option/ArgList.h" 54 #include "llvm/Option/Option.h" 55 #include "llvm/Support/CodeGen.h" 56 #include "llvm/Support/Compression.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/ErrorHandling.h" 59 #include "llvm/Support/FileSystem.h" 60 #include "llvm/Support/Path.h" 61 #include "llvm/Support/Process.h" 62 #include "llvm/Support/Program.h" 63 #include "llvm/Support/ScopedPrinter.h" 64 #include "llvm/Support/Threading.h" 65 #include "llvm/Support/VirtualFileSystem.h" 66 #include "llvm/Support/YAMLParser.h" 67 #include "llvm/TargetParser/Host.h" 68 #include "llvm/TargetParser/PPCTargetParser.h" 69 #include "llvm/TargetParser/TargetParser.h" 70 #include <optional> 71 72 using namespace clang::driver; 73 using namespace clang::driver::tools; 74 using namespace clang; 75 using namespace llvm::opt; 76 77 static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args, 78 const llvm::Triple &Triple) { 79 if (Args.hasArg(clang::driver::options::OPT_pg) && 80 !Args.hasArg(clang::driver::options::OPT_mfentry)) 81 return true; 82 83 if (Triple.isAndroid()) 84 return true; 85 86 switch (Triple.getArch()) { 87 case llvm::Triple::xcore: 88 case llvm::Triple::wasm32: 89 case llvm::Triple::wasm64: 90 case llvm::Triple::msp430: 91 // XCore never wants frame pointers, regardless of OS. 92 // WebAssembly never wants frame pointers. 93 return false; 94 case llvm::Triple::ppc: 95 case llvm::Triple::ppcle: 96 case llvm::Triple::ppc64: 97 case llvm::Triple::ppc64le: 98 case llvm::Triple::riscv32: 99 case llvm::Triple::riscv64: 100 case llvm::Triple::sparc: 101 case llvm::Triple::sparcel: 102 case llvm::Triple::sparcv9: 103 case llvm::Triple::amdgcn: 104 case llvm::Triple::r600: 105 case llvm::Triple::csky: 106 case llvm::Triple::loongarch32: 107 case llvm::Triple::loongarch64: 108 case llvm::Triple::m68k: 109 return !clang::driver::tools::areOptimizationsEnabled(Args); 110 default: 111 break; 112 } 113 114 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) { 115 return !clang::driver::tools::areOptimizationsEnabled(Args); 116 } 117 118 if (Triple.isOSLinux() || Triple.isOSHurd()) { 119 switch (Triple.getArch()) { 120 // Don't use a frame pointer on linux if optimizing for certain targets. 121 case llvm::Triple::arm: 122 case llvm::Triple::armeb: 123 case llvm::Triple::thumb: 124 case llvm::Triple::thumbeb: 125 case llvm::Triple::mips64: 126 case llvm::Triple::mips64el: 127 case llvm::Triple::mips: 128 case llvm::Triple::mipsel: 129 case llvm::Triple::systemz: 130 case llvm::Triple::x86: 131 case llvm::Triple::x86_64: 132 return !clang::driver::tools::areOptimizationsEnabled(Args); 133 default: 134 return true; 135 } 136 } 137 138 if (Triple.isOSWindows()) { 139 switch (Triple.getArch()) { 140 case llvm::Triple::x86: 141 return !clang::driver::tools::areOptimizationsEnabled(Args); 142 case llvm::Triple::x86_64: 143 return Triple.isOSBinFormatMachO(); 144 case llvm::Triple::arm: 145 case llvm::Triple::thumb: 146 // Windows on ARM builds with FPO disabled to aid fast stack walking 147 return true; 148 default: 149 // All other supported Windows ISAs use xdata unwind information, so frame 150 // pointers are not generally useful. 151 return false; 152 } 153 } 154 155 if (arm::isARMEABIBareMetal(Triple)) 156 return false; 157 158 return true; 159 } 160 161 static bool useLeafFramePointerForTargetByDefault(const llvm::Triple &Triple) { 162 if (Triple.isAArch64() || Triple.isPS() || Triple.isVE() || 163 (Triple.isAndroid() && !Triple.isARM())) 164 return false; 165 166 return true; 167 } 168 169 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) { 170 switch (Triple.getArch()) { 171 default: 172 return false; 173 case llvm::Triple::arm: 174 case llvm::Triple::thumb: 175 // ARM Darwin targets require a frame pointer to be always present to aid 176 // offline debugging via backtraces. 177 return Triple.isOSDarwin(); 178 } 179 } 180 181 // True if a target-specific option requires the frame chain to be preserved, 182 // even if new frame records are not created. 183 static bool mustMaintainValidFrameChain(const llvm::opt::ArgList &Args, 184 const llvm::Triple &Triple) { 185 if (Triple.isARM() || Triple.isThumb()) { 186 // For 32-bit Arm, the -mframe-chain=aapcs and -mframe-chain=aapcs+leaf 187 // options require the frame pointer register to be reserved (or point to a 188 // new AAPCS-compilant frame record), even with -fno-omit-frame-pointer. 189 if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) { 190 StringRef V = A->getValue(); 191 return V != "none"; 192 } 193 return false; 194 } 195 return false; 196 } 197 198 // True if a target-specific option causes -fno-omit-frame-pointer to also 199 // cause frame records to be created in leaf functions. 200 static bool framePointerImpliesLeafFramePointer(const llvm::opt::ArgList &Args, 201 const llvm::Triple &Triple) { 202 if (Triple.isARM() || Triple.isThumb()) { 203 // For 32-bit Arm, the -mframe-chain=aapcs+leaf option causes the 204 // -fno-omit-frame-pointer optiion to imply -mno-omit-leaf-frame-pointer, 205 // but does not by itself imply either option. 206 if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) { 207 StringRef V = A->getValue(); 208 return V == "aapcs+leaf"; 209 } 210 return false; 211 } 212 return false; 213 } 214 215 clang::CodeGenOptions::FramePointerKind 216 getFramePointerKind(const llvm::opt::ArgList &Args, 217 const llvm::Triple &Triple) { 218 // There are three things to consider here: 219 // * Should a frame record be created for non-leaf functions? 220 // * Should a frame record be created for leaf functions? 221 // * Is the frame pointer register reserved, i.e. must it always point to 222 // either a new, valid frame record or be un-modified? 223 // 224 // Not all combinations of these are valid: 225 // * It's not useful to have leaf frame records without non-leaf ones. 226 // * It's not useful to have frame records without reserving the frame 227 // pointer. 228 // 229 // | Non-leaf | Leaf | Reserved | 230 // | N | N | N | FramePointerKind::None 231 // | N | N | Y | FramePointerKind::Reserved 232 // | N | Y | N | Invalid 233 // | N | Y | Y | Invalid 234 // | Y | N | N | Invalid 235 // | Y | N | Y | FramePointerKind::NonLeaf 236 // | Y | Y | N | Invalid 237 // | Y | Y | Y | FramePointerKind::All 238 // 239 // The FramePointerKind::Reserved case is currently only reachable for Arm, 240 // which has the -mframe-chain= option which can (in combination with 241 // -fno-omit-frame-pointer) specify that the frame chain must be valid, 242 // without requiring new frame records to be created. 243 244 bool DefaultFP = useFramePointerForTargetByDefault(Args, Triple); 245 bool EnableFP = 246 mustUseNonLeafFramePointerForTarget(Triple) || 247 Args.hasFlag(clang::driver::options::OPT_fno_omit_frame_pointer, 248 clang::driver::options::OPT_fomit_frame_pointer, DefaultFP); 249 250 bool DefaultLeafFP = 251 useLeafFramePointerForTargetByDefault(Triple) || 252 (EnableFP && framePointerImpliesLeafFramePointer(Args, Triple)); 253 bool EnableLeafFP = Args.hasFlag( 254 clang::driver::options::OPT_mno_omit_leaf_frame_pointer, 255 clang::driver::options::OPT_momit_leaf_frame_pointer, DefaultLeafFP); 256 257 bool FPRegReserved = EnableFP || mustMaintainValidFrameChain(Args, Triple); 258 259 if (EnableFP) { 260 if (EnableLeafFP) 261 return clang::CodeGenOptions::FramePointerKind::All; 262 return clang::CodeGenOptions::FramePointerKind::NonLeaf; 263 } 264 if (FPRegReserved) 265 return clang::CodeGenOptions::FramePointerKind::Reserved; 266 return clang::CodeGenOptions::FramePointerKind::None; 267 } 268 269 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs, 270 const StringRef PluginOptPrefix) { 271 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ)) 272 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 273 "-pass-remarks=" + A->getValue())); 274 275 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ)) 276 CmdArgs.push_back(Args.MakeArgString( 277 Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue())); 278 279 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ)) 280 CmdArgs.push_back(Args.MakeArgString( 281 Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue())); 282 } 283 284 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, 285 const llvm::Triple &Triple, 286 const InputInfo &Input, 287 const InputInfo &Output, 288 const StringRef PluginOptPrefix) { 289 StringRef Format = "yaml"; 290 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) 291 Format = A->getValue(); 292 293 SmallString<128> F; 294 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ); 295 if (A) 296 F = A->getValue(); 297 else if (Output.isFilename()) 298 F = Output.getFilename(); 299 300 assert(!F.empty() && "Cannot determine remarks output name."); 301 // Append "opt.ld.<format>" to the end of the file name. 302 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 303 "opt-remarks-filename=" + F + 304 ".opt.ld." + Format)); 305 306 if (const Arg *A = 307 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) 308 CmdArgs.push_back(Args.MakeArgString( 309 Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue())); 310 311 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 312 "opt-remarks-format=" + Format.data())); 313 } 314 315 static void renderRemarksHotnessOptions(const ArgList &Args, 316 ArgStringList &CmdArgs, 317 const StringRef PluginOptPrefix) { 318 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 319 options::OPT_fno_diagnostics_show_hotness, false)) 320 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 321 "opt-remarks-with-hotness")); 322 323 if (const Arg *A = 324 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) 325 CmdArgs.push_back( 326 Args.MakeArgString(Twine(PluginOptPrefix) + 327 "opt-remarks-hotness-threshold=" + A->getValue())); 328 } 329 330 static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg, 331 llvm::Triple T, 332 StringRef Processor) { 333 // Warn no-cumode for AMDGCN processors not supporing WGP mode. 334 if (!T.isAMDGPU()) 335 return false; 336 auto GPUKind = T.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(Processor) 337 : llvm::AMDGPU::parseArchR600(Processor); 338 auto GPUFeatures = T.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(GPUKind) 339 : llvm::AMDGPU::getArchAttrR600(GPUKind); 340 if (GPUFeatures & llvm::AMDGPU::FEATURE_WGP) 341 return false; 342 return TargetFeatureArg.getOption().matches(options::OPT_mno_cumode); 343 } 344 345 void tools::addPathIfExists(const Driver &D, const Twine &Path, 346 ToolChain::path_list &Paths) { 347 if (D.getVFS().exists(Path)) 348 Paths.push_back(Path.str()); 349 } 350 351 void tools::handleTargetFeaturesGroup(const Driver &D, 352 const llvm::Triple &Triple, 353 const ArgList &Args, 354 std::vector<StringRef> &Features, 355 OptSpecifier Group) { 356 std::set<StringRef> Warned; 357 for (const Arg *A : Args.filtered(Group)) { 358 StringRef Name = A->getOption().getName(); 359 A->claim(); 360 361 // Skip over "-m". 362 assert(Name.starts_with("m") && "Invalid feature name."); 363 Name = Name.substr(1); 364 365 auto Proc = getCPUName(D, Args, Triple); 366 if (shouldIgnoreUnsupportedTargetFeature(*A, Triple, Proc)) { 367 if (Warned.count(Name) == 0) { 368 D.getDiags().Report( 369 clang::diag::warn_drv_unsupported_option_for_processor) 370 << A->getAsString(Args) << Proc; 371 Warned.insert(Name); 372 } 373 continue; 374 } 375 376 bool IsNegative = Name.consume_front("no-"); 377 378 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 379 } 380 } 381 382 SmallVector<StringRef> 383 tools::unifyTargetFeatures(ArrayRef<StringRef> Features) { 384 // Only add a feature if it hasn't been seen before starting from the end. 385 SmallVector<StringRef> UnifiedFeatures; 386 llvm::DenseSet<StringRef> UsedFeatures; 387 for (StringRef Feature : llvm::reverse(Features)) { 388 if (UsedFeatures.insert(Feature.drop_front()).second) 389 UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature); 390 } 391 392 return UnifiedFeatures; 393 } 394 395 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 396 const char *ArgName, const char *EnvVar) { 397 const char *DirList = ::getenv(EnvVar); 398 bool CombinedArg = false; 399 400 if (!DirList) 401 return; // Nothing to do. 402 403 StringRef Name(ArgName); 404 if (Name == "-I" || Name == "-L" || Name.empty()) 405 CombinedArg = true; 406 407 StringRef Dirs(DirList); 408 if (Dirs.empty()) // Empty string should not add '.'. 409 return; 410 411 StringRef::size_type Delim; 412 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 413 if (Delim == 0) { // Leading colon. 414 if (CombinedArg) { 415 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 416 } else { 417 CmdArgs.push_back(ArgName); 418 CmdArgs.push_back("."); 419 } 420 } else { 421 if (CombinedArg) { 422 CmdArgs.push_back( 423 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 424 } else { 425 CmdArgs.push_back(ArgName); 426 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 427 } 428 } 429 Dirs = Dirs.substr(Delim + 1); 430 } 431 432 if (Dirs.empty()) { // Trailing colon. 433 if (CombinedArg) { 434 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 435 } else { 436 CmdArgs.push_back(ArgName); 437 CmdArgs.push_back("."); 438 } 439 } else { // Add the last path. 440 if (CombinedArg) { 441 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 442 } else { 443 CmdArgs.push_back(ArgName); 444 CmdArgs.push_back(Args.MakeArgString(Dirs)); 445 } 446 } 447 } 448 449 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 450 const ArgList &Args, ArgStringList &CmdArgs, 451 const JobAction &JA) { 452 const Driver &D = TC.getDriver(); 453 454 // Add extra linker input arguments which are not treated as inputs 455 // (constructed via -Xarch_). 456 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 457 458 // LIBRARY_PATH are included before user inputs and only supported on native 459 // toolchains. 460 if (!TC.isCrossCompiling()) 461 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 462 463 for (const auto &II : Inputs) { 464 // If the current tool chain refers to an OpenMP offloading host, we 465 // should ignore inputs that refer to OpenMP offloading devices - 466 // they will be embedded according to a proper linker script. 467 if (auto *IA = II.getAction()) 468 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 469 IA->isDeviceOffloading(Action::OFK_OpenMP))) 470 continue; 471 472 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 473 // Don't try to pass LLVM inputs unless we have native support. 474 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 475 476 // Add filenames immediately. 477 if (II.isFilename()) { 478 CmdArgs.push_back(II.getFilename()); 479 continue; 480 } 481 482 // In some error cases, the input could be Nothing; skip those. 483 if (II.isNothing()) 484 continue; 485 486 // Otherwise, this is a linker input argument. 487 const Arg &A = II.getInputArg(); 488 489 // Handle reserved library options. 490 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 491 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 492 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 493 TC.AddCCKextLibArgs(Args, CmdArgs); 494 else 495 A.renderAsInput(Args, CmdArgs); 496 } 497 if (const Arg *A = Args.getLastArg(options::OPT_fveclib)) { 498 const llvm::Triple &Triple = TC.getTriple(); 499 StringRef V = A->getValue(); 500 if (V == "ArmPL" && (Triple.isOSLinux() || Triple.isOSDarwin())) { 501 // To support -fveclib=ArmPL we need to link against libamath. Some of the 502 // libamath functions depend on libm, at the same time, libamath exports 503 // its own implementation of some of the libm functions. These are faster 504 // and potentially less accurate implementations, hence we need to be 505 // careful what is being linked in. Since here we are interested only in 506 // the subset of libamath functions that is covered by the veclib 507 // mappings, we need to prioritize libm functions by putting -lm before 508 // -lamath (and then -lm again, to fulfill libamath requirements). 509 // 510 // Therefore we need to do the following: 511 // 512 // 1. On Linux, link only when actually needed. 513 // 514 // 2. Prefer libm functions over libamath. 515 // 516 // 3. Link against libm to resolve libamath dependencies. 517 // 518 if (Triple.isOSLinux()) { 519 CmdArgs.push_back(Args.MakeArgString("--push-state")); 520 CmdArgs.push_back(Args.MakeArgString("--as-needed")); 521 } 522 CmdArgs.push_back(Args.MakeArgString("-lm")); 523 CmdArgs.push_back(Args.MakeArgString("-lamath")); 524 CmdArgs.push_back(Args.MakeArgString("-lm")); 525 if (Triple.isOSLinux()) 526 CmdArgs.push_back(Args.MakeArgString("--pop-state")); 527 addArchSpecificRPath(TC, Args, CmdArgs); 528 } 529 } 530 } 531 532 void tools::addLinkerCompressDebugSectionsOption( 533 const ToolChain &TC, const llvm::opt::ArgList &Args, 534 llvm::opt::ArgStringList &CmdArgs) { 535 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi 536 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore 537 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz 538 // is not translated since ld --compress-debug-sections option requires an 539 // argument. 540 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) { 541 StringRef V = A->getValue(); 542 if (V == "none" || V == "zlib" || V == "zstd") 543 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V)); 544 else 545 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument) 546 << A->getSpelling() << V; 547 } 548 } 549 550 void tools::AddTargetFeature(const ArgList &Args, 551 std::vector<StringRef> &Features, 552 OptSpecifier OnOpt, OptSpecifier OffOpt, 553 StringRef FeatureName) { 554 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 555 if (A->getOption().matches(OnOpt)) 556 Features.push_back(Args.MakeArgString("+" + FeatureName)); 557 else 558 Features.push_back(Args.MakeArgString("-" + FeatureName)); 559 } 560 } 561 562 /// Get the (LLVM) name of the AMDGPU gpu we are targeting. 563 static std::string getAMDGPUTargetGPU(const llvm::Triple &T, 564 const ArgList &Args) { 565 Arg *MArch = Args.getLastArg(options::OPT_march_EQ); 566 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 567 auto GPUName = getProcessorFromTargetID(T, A->getValue()); 568 return llvm::StringSwitch<std::string>(GPUName) 569 .Cases("rv630", "rv635", "r600") 570 .Cases("rv610", "rv620", "rs780", "rs880") 571 .Case("rv740", "rv770") 572 .Case("palm", "cedar") 573 .Cases("sumo", "sumo2", "sumo") 574 .Case("hemlock", "cypress") 575 .Case("aruba", "cayman") 576 .Default(GPUName.str()); 577 } 578 if (MArch) 579 return getProcessorFromTargetID(T, MArch->getValue()).str(); 580 return ""; 581 } 582 583 static std::string getLanaiTargetCPU(const ArgList &Args) { 584 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 585 return A->getValue(); 586 } 587 return ""; 588 } 589 590 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 591 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 592 // If we have -mcpu=, use that. 593 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 594 StringRef CPU = A->getValue(); 595 596 #ifdef __wasm__ 597 // Handle "native" by examining the host. "native" isn't meaningful when 598 // cross compiling, so only support this when the host is also WebAssembly. 599 if (CPU == "native") 600 return llvm::sys::getHostCPUName(); 601 #endif 602 603 return CPU; 604 } 605 606 return "generic"; 607 } 608 609 std::string tools::getCPUName(const Driver &D, const ArgList &Args, 610 const llvm::Triple &T, bool FromAs) { 611 Arg *A; 612 613 switch (T.getArch()) { 614 default: 615 return ""; 616 617 case llvm::Triple::aarch64: 618 case llvm::Triple::aarch64_32: 619 case llvm::Triple::aarch64_be: 620 return aarch64::getAArch64TargetCPU(Args, T, A); 621 622 case llvm::Triple::arm: 623 case llvm::Triple::armeb: 624 case llvm::Triple::thumb: 625 case llvm::Triple::thumbeb: { 626 StringRef MArch, MCPU; 627 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 628 return arm::getARMTargetCPU(MCPU, MArch, T); 629 } 630 631 case llvm::Triple::avr: 632 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 633 return A->getValue(); 634 return ""; 635 636 case llvm::Triple::m68k: 637 return m68k::getM68kTargetCPU(Args); 638 639 case llvm::Triple::mips: 640 case llvm::Triple::mipsel: 641 case llvm::Triple::mips64: 642 case llvm::Triple::mips64el: { 643 StringRef CPUName; 644 StringRef ABIName; 645 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 646 return std::string(CPUName); 647 } 648 649 case llvm::Triple::nvptx: 650 case llvm::Triple::nvptx64: 651 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 652 return A->getValue(); 653 return ""; 654 655 case llvm::Triple::ppc: 656 case llvm::Triple::ppcle: 657 case llvm::Triple::ppc64: 658 case llvm::Triple::ppc64le: 659 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ)) 660 return std::string( 661 llvm::PPC::getNormalizedPPCTargetCPU(T, A->getValue())); 662 return std::string(llvm::PPC::getNormalizedPPCTargetCPU(T)); 663 664 case llvm::Triple::csky: 665 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 666 return A->getValue(); 667 else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 668 return A->getValue(); 669 else 670 return "ck810"; 671 case llvm::Triple::riscv32: 672 case llvm::Triple::riscv64: 673 return riscv::getRISCVTargetCPU(Args, T); 674 675 case llvm::Triple::bpfel: 676 case llvm::Triple::bpfeb: 677 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 678 return A->getValue(); 679 return ""; 680 681 case llvm::Triple::sparc: 682 case llvm::Triple::sparcel: 683 case llvm::Triple::sparcv9: 684 return sparc::getSparcTargetCPU(D, Args, T); 685 686 case llvm::Triple::x86: 687 case llvm::Triple::x86_64: 688 return x86::getX86TargetCPU(D, Args, T); 689 690 case llvm::Triple::hexagon: 691 return "hexagon" + 692 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 693 694 case llvm::Triple::lanai: 695 return getLanaiTargetCPU(Args); 696 697 case llvm::Triple::systemz: 698 return systemz::getSystemZTargetCPU(Args, T); 699 700 case llvm::Triple::r600: 701 case llvm::Triple::amdgcn: 702 return getAMDGPUTargetGPU(T, Args); 703 704 case llvm::Triple::wasm32: 705 case llvm::Triple::wasm64: 706 return std::string(getWebAssemblyTargetCPU(Args)); 707 708 case llvm::Triple::loongarch32: 709 case llvm::Triple::loongarch64: 710 return loongarch::getLoongArchTargetCPU(Args, T); 711 712 case llvm::Triple::xtensa: 713 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 714 return A->getValue(); 715 return ""; 716 } 717 } 718 719 static void getWebAssemblyTargetFeatures(const Driver &D, 720 const llvm::Triple &Triple, 721 const ArgList &Args, 722 std::vector<StringRef> &Features) { 723 handleTargetFeaturesGroup(D, Triple, Args, Features, 724 options::OPT_m_wasm_Features_Group); 725 } 726 727 void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple, 728 const ArgList &Args, ArgStringList &CmdArgs, 729 bool ForAS, bool IsAux) { 730 std::vector<StringRef> Features; 731 switch (Triple.getArch()) { 732 default: 733 break; 734 case llvm::Triple::mips: 735 case llvm::Triple::mipsel: 736 case llvm::Triple::mips64: 737 case llvm::Triple::mips64el: 738 mips::getMIPSTargetFeatures(D, Triple, Args, Features); 739 break; 740 case llvm::Triple::arm: 741 case llvm::Triple::armeb: 742 case llvm::Triple::thumb: 743 case llvm::Triple::thumbeb: 744 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS); 745 break; 746 case llvm::Triple::ppc: 747 case llvm::Triple::ppcle: 748 case llvm::Triple::ppc64: 749 case llvm::Triple::ppc64le: 750 ppc::getPPCTargetFeatures(D, Triple, Args, Features); 751 break; 752 case llvm::Triple::riscv32: 753 case llvm::Triple::riscv64: 754 riscv::getRISCVTargetFeatures(D, Triple, Args, Features); 755 break; 756 case llvm::Triple::systemz: 757 systemz::getSystemZTargetFeatures(D, Args, Features); 758 break; 759 case llvm::Triple::aarch64: 760 case llvm::Triple::aarch64_32: 761 case llvm::Triple::aarch64_be: 762 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS); 763 break; 764 case llvm::Triple::x86: 765 case llvm::Triple::x86_64: 766 x86::getX86TargetFeatures(D, Triple, Args, Features); 767 break; 768 case llvm::Triple::hexagon: 769 hexagon::getHexagonTargetFeatures(D, Triple, Args, Features); 770 break; 771 case llvm::Triple::wasm32: 772 case llvm::Triple::wasm64: 773 getWebAssemblyTargetFeatures(D, Triple, Args, Features); 774 break; 775 case llvm::Triple::sparc: 776 case llvm::Triple::sparcel: 777 case llvm::Triple::sparcv9: 778 sparc::getSparcTargetFeatures(D, Args, Features); 779 break; 780 case llvm::Triple::r600: 781 case llvm::Triple::amdgcn: 782 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features); 783 break; 784 case llvm::Triple::nvptx: 785 case llvm::Triple::nvptx64: 786 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features); 787 break; 788 case llvm::Triple::m68k: 789 m68k::getM68kTargetFeatures(D, Triple, Args, Features); 790 break; 791 case llvm::Triple::msp430: 792 msp430::getMSP430TargetFeatures(D, Args, Features); 793 break; 794 case llvm::Triple::ve: 795 ve::getVETargetFeatures(D, Args, Features); 796 break; 797 case llvm::Triple::csky: 798 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features); 799 break; 800 case llvm::Triple::loongarch32: 801 case llvm::Triple::loongarch64: 802 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features); 803 break; 804 } 805 806 for (auto Feature : unifyTargetFeatures(Features)) { 807 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature"); 808 CmdArgs.push_back(Feature.data()); 809 } 810 } 811 812 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 813 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 814 if (!LtoJobsArg) 815 return {}; 816 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue())) 817 D.Diag(diag::err_drv_invalid_int_value) 818 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); 819 return LtoJobsArg->getValue(); 820 } 821 822 // PS4/PS5 uses -ffunction-sections and -fdata-sections by default. 823 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 824 return Triple.isPS(); 825 } 826 827 bool tools::isTLSDESCEnabled(const ToolChain &TC, 828 const llvm::opt::ArgList &Args) { 829 const llvm::Triple &Triple = TC.getEffectiveTriple(); 830 Arg *A = Args.getLastArg(options::OPT_mtls_dialect_EQ); 831 if (!A) 832 return Triple.hasDefaultTLSDESC(); 833 StringRef V = A->getValue(); 834 bool SupportedArgument = false, EnableTLSDESC = false; 835 bool Unsupported = !Triple.isOSBinFormatELF(); 836 if (Triple.isLoongArch() || Triple.isRISCV()) { 837 SupportedArgument = V == "desc" || V == "trad"; 838 EnableTLSDESC = V == "desc"; 839 } else if (Triple.isX86()) { 840 SupportedArgument = V == "gnu" || V == "gnu2"; 841 EnableTLSDESC = V == "gnu2"; 842 } else { 843 Unsupported = true; 844 } 845 if (Unsupported) { 846 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 847 << A->getSpelling() << Triple.getTriple(); 848 } else if (!SupportedArgument) { 849 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument_for_target) 850 << A->getSpelling() << V << Triple.getTriple(); 851 } 852 return EnableTLSDESC; 853 } 854 855 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, 856 ArgStringList &CmdArgs, const InputInfo &Output, 857 const InputInfo &Input, bool IsThinLTO) { 858 const llvm::Triple &Triple = ToolChain.getTriple(); 859 const bool IsOSAIX = Triple.isOSAIX(); 860 const bool IsAMDGCN = Triple.isAMDGCN(); 861 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 862 const Driver &D = ToolChain.getDriver(); 863 const bool IsFatLTO = Args.hasArg(options::OPT_ffat_lto_objects); 864 const bool IsUnifiedLTO = Args.hasArg(options::OPT_funified_lto); 865 if (llvm::sys::path::filename(Linker) != "ld.lld" && 866 llvm::sys::path::stem(Linker) != "ld.lld" && !Triple.isOSOpenBSD()) { 867 // Tell the linker to load the plugin. This has to come before 868 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to 869 // come before any -plugin-opt/-bplugin_opt that -Wl might forward. 870 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : ""; 871 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold"; 872 873 if (!IsOSAIX) 874 CmdArgs.push_back("-plugin"); 875 876 #if defined(_WIN32) 877 const char *Suffix = ".dll"; 878 #elif defined(__APPLE__) 879 const char *Suffix = ".dylib"; 880 #else 881 const char *Suffix = ".so"; 882 #endif 883 884 SmallString<1024> Plugin; 885 llvm::sys::path::native(Twine(D.Dir) + 886 "/../" CLANG_INSTALL_LIBDIR_BASENAME + 887 PluginName + Suffix, 888 Plugin); 889 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin)); 890 } else { 891 // Tell LLD to find and use .llvm.lto section in regular relocatable object 892 // files 893 if (IsFatLTO) 894 CmdArgs.push_back("--fat-lto-objects"); 895 } 896 897 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt="; 898 const char *ExtraDash = IsOSAIX ? "-" : ""; 899 const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs="; 900 901 // Note, this solution is far from perfect, better to encode it into IR 902 // metadata, but this may not be worth it, since it looks like aranges is on 903 // the way out. 904 if (Args.hasArg(options::OPT_gdwarf_aranges)) { 905 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 906 "-generate-arange-section")); 907 } 908 909 // Pass vector library arguments to LTO. 910 Arg *ArgVecLib = Args.getLastArg(options::OPT_fveclib); 911 if (ArgVecLib && ArgVecLib->getNumValues() == 1) { 912 // Map the vector library names from clang front-end to opt front-end. The 913 // values are taken from the TargetLibraryInfo class command line options. 914 std::optional<StringRef> OptVal = 915 llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue()) 916 .Case("Accelerate", "Accelerate") 917 .Case("LIBMVEC", "LIBMVEC-X86") 918 .Case("MASSV", "MASSV") 919 .Case("SVML", "SVML") 920 .Case("SLEEF", "sleefgnuabi") 921 .Case("Darwin_libsystem_m", "Darwin_libsystem_m") 922 .Case("ArmPL", "ArmPL") 923 .Case("none", "none") 924 .Default(std::nullopt); 925 926 if (OptVal) 927 CmdArgs.push_back(Args.MakeArgString( 928 Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value())); 929 } 930 931 // Try to pass driver level flags relevant to LTO code generation down to 932 // the plugin. 933 934 // Handle flags for selecting CPU variants. 935 std::string CPU = getCPUName(D, Args, Triple); 936 if (!CPU.empty()) 937 CmdArgs.push_back( 938 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU)); 939 940 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 941 // The optimization level matches 942 // CompilerInvocation.cpp:getOptimizationLevel(). 943 StringRef OOpt; 944 if (A->getOption().matches(options::OPT_O4) || 945 A->getOption().matches(options::OPT_Ofast)) 946 OOpt = "3"; 947 else if (A->getOption().matches(options::OPT_O)) { 948 OOpt = A->getValue(); 949 if (OOpt == "g") 950 OOpt = "1"; 951 else if (OOpt == "s" || OOpt == "z") 952 OOpt = "2"; 953 } else if (A->getOption().matches(options::OPT_O0)) 954 OOpt = "0"; 955 if (!OOpt.empty()) { 956 CmdArgs.push_back( 957 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt)); 958 if (IsAMDGCN) 959 CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt)); 960 } 961 } 962 963 if (Args.hasArg(options::OPT_gsplit_dwarf)) 964 CmdArgs.push_back(Args.MakeArgString( 965 Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo")); 966 967 if (IsThinLTO && !IsOSAIX) 968 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto")); 969 else if (IsThinLTO && IsOSAIX) 970 CmdArgs.push_back(Args.MakeArgString(Twine("-bdbg:thinlto"))); 971 972 // Matrix intrinsic lowering happens at link time with ThinLTO. Enable 973 // LowerMatrixIntrinsicsPass, which is transitively called by 974 // buildThinLTODefaultPipeline under EnableMatrix. 975 if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) && 976 Args.hasArg(options::OPT_fenable_matrix)) 977 CmdArgs.push_back( 978 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-matrix")); 979 980 StringRef Parallelism = getLTOParallelism(Args, D); 981 if (!Parallelism.empty()) 982 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 983 ParallelismOpt + Parallelism)); 984 985 // Pass down GlobalISel options. 986 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel, 987 options::OPT_fno_global_isel)) { 988 // Parsing -fno-global-isel explicitly gives architectures that enable GISel 989 // by default a chance to disable it. 990 CmdArgs.push_back(Args.MakeArgString( 991 Twine(PluginOptPrefix) + "-global-isel=" + 992 (A->getOption().matches(options::OPT_fglobal_isel) ? "1" : "0"))); 993 } 994 995 // If an explicit debugger tuning argument appeared, pass it along. 996 if (Arg *A = 997 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { 998 if (A->getOption().matches(options::OPT_glldb)) 999 CmdArgs.push_back( 1000 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb")); 1001 else if (A->getOption().matches(options::OPT_gsce)) 1002 CmdArgs.push_back( 1003 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce")); 1004 else if (A->getOption().matches(options::OPT_gdbx)) 1005 CmdArgs.push_back( 1006 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx")); 1007 else 1008 CmdArgs.push_back( 1009 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb")); 1010 } 1011 1012 if (IsOSAIX) { 1013 if (!ToolChain.useIntegratedAs()) 1014 CmdArgs.push_back( 1015 Args.MakeArgString(Twine(PluginOptPrefix) + "-no-integrated-as=1")); 1016 1017 // On AIX, clang assumes strict-dwarf is true if any debug option is 1018 // specified, unless it is told explicitly not to assume so. 1019 Arg *A = Args.getLastArg(options::OPT_g_Group); 1020 bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) && 1021 !A->getOption().matches(options::OPT_ggdb0); 1022 if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf, 1023 options::OPT_gno_strict_dwarf, true)) 1024 CmdArgs.push_back( 1025 Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true")); 1026 1027 for (const Arg *A : Args.filtered_reverse(options::OPT_mabi_EQ)) { 1028 StringRef V = A->getValue(); 1029 if (V == "vec-default") 1030 break; 1031 if (V == "vec-extabi") { 1032 CmdArgs.push_back( 1033 Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi")); 1034 break; 1035 } 1036 } 1037 } 1038 1039 bool UseSeparateSections = 1040 isUseSeparateSections(ToolChain.getEffectiveTriple()); 1041 1042 if (Args.hasFlag(options::OPT_ffunction_sections, 1043 options::OPT_fno_function_sections, UseSeparateSections)) 1044 CmdArgs.push_back( 1045 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1")); 1046 else if (Args.hasArg(options::OPT_fno_function_sections)) 1047 CmdArgs.push_back( 1048 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0")); 1049 1050 bool DataSectionsTurnedOff = false; 1051 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 1052 UseSeparateSections)) { 1053 CmdArgs.push_back( 1054 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1")); 1055 } else if (Args.hasArg(options::OPT_fno_data_sections)) { 1056 DataSectionsTurnedOff = true; 1057 CmdArgs.push_back( 1058 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0")); 1059 } 1060 1061 if (Args.hasArg(options::OPT_mxcoff_roptr) || 1062 Args.hasArg(options::OPT_mno_xcoff_roptr)) { 1063 bool HasRoptr = Args.hasFlag(options::OPT_mxcoff_roptr, 1064 options::OPT_mno_xcoff_roptr, false); 1065 StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr"; 1066 if (!IsOSAIX) 1067 D.Diag(diag::err_drv_unsupported_opt_for_target) 1068 << OptStr << Triple.str(); 1069 1070 if (HasRoptr) { 1071 // The data sections option is on by default on AIX. We only need to error 1072 // out when -fno-data-sections is specified explicitly to turn off data 1073 // sections. 1074 if (DataSectionsTurnedOff) 1075 D.Diag(diag::err_roptr_requires_data_sections); 1076 1077 CmdArgs.push_back( 1078 Args.MakeArgString(Twine(PluginOptPrefix) + "-mxcoff-roptr")); 1079 } 1080 } 1081 1082 // Pass an option to enable split machine functions. 1083 if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions, 1084 options::OPT_fno_split_machine_functions)) { 1085 if (A->getOption().matches(options::OPT_fsplit_machine_functions)) 1086 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 1087 "-split-machine-functions")); 1088 } 1089 1090 if (Arg *A = getLastProfileSampleUseArg(Args)) { 1091 StringRef FName = A->getValue(); 1092 if (!llvm::sys::fs::exists(FName)) 1093 D.Diag(diag::err_drv_no_such_file) << FName; 1094 else 1095 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 1096 "sample-profile=" + FName)); 1097 } 1098 1099 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) { 1100 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1101 "cs-profile-generate")); 1102 if (CSPGOGenerateArg->getOption().matches( 1103 options::OPT_fcs_profile_generate_EQ)) { 1104 SmallString<128> Path(CSPGOGenerateArg->getValue()); 1105 llvm::sys::path::append(Path, "default_%m.profraw"); 1106 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1107 "cs-profile-path=" + Path)); 1108 } else 1109 CmdArgs.push_back( 1110 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1111 "cs-profile-path=default_%m.profraw")); 1112 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) { 1113 SmallString<128> Path( 1114 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 1115 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 1116 llvm::sys::path::append(Path, "default.profdata"); 1117 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + 1118 "cs-profile-path=" + Path)); 1119 } 1120 1121 // This controls whether or not we perform JustMyCode instrumentation. 1122 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) { 1123 if (ToolChain.getEffectiveTriple().isOSBinFormatELF()) 1124 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + 1125 "-enable-jmc-instrument")); 1126 else 1127 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only); 1128 } 1129 1130 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls, 1131 Triple.hasDefaultEmulatedTLS())) { 1132 CmdArgs.push_back( 1133 Args.MakeArgString(Twine(PluginOptPrefix) + "-emulated-tls")); 1134 } 1135 if (isTLSDESCEnabled(ToolChain, Args)) 1136 CmdArgs.push_back( 1137 Args.MakeArgString(Twine(PluginOptPrefix) + "-enable-tlsdesc")); 1138 1139 if (Args.hasFlag(options::OPT_fstack_size_section, 1140 options::OPT_fno_stack_size_section, false)) 1141 CmdArgs.push_back( 1142 Args.MakeArgString(Twine(PluginOptPrefix) + "-stack-size-section")); 1143 1144 // Setup statistics file output. 1145 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 1146 if (!StatsFile.empty()) 1147 CmdArgs.push_back( 1148 Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile)); 1149 1150 // Setup crash diagnostics dir. 1151 if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir)) 1152 CmdArgs.push_back(Args.MakeArgString( 1153 Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue())); 1154 1155 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix); 1156 1157 // Handle remark diagnostics on screen options: '-Rpass-*'. 1158 renderRpassOptions(Args, CmdArgs, PluginOptPrefix); 1159 1160 // Handle serialized remarks options: '-fsave-optimization-record' 1161 // and '-foptimization-record-*'. 1162 if (willEmitRemarks(Args)) 1163 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input, 1164 Output, PluginOptPrefix); 1165 1166 // Handle remarks hotness/threshold related options. 1167 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix); 1168 1169 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(), 1170 /*IsLTO=*/true, PluginOptPrefix); 1171 1172 bool IsELF = Triple.isOSBinFormatELF(); 1173 bool Crel = false; 1174 bool ImplicitMapSyms = false; 1175 for (const Arg *A : Args.filtered(options::OPT_Wa_COMMA)) { 1176 for (StringRef V : A->getValues()) { 1177 auto Equal = V.split('='); 1178 auto checkArg = [&](bool ValidTarget, 1179 std::initializer_list<const char *> Set) { 1180 if (!ValidTarget) { 1181 D.Diag(diag::err_drv_unsupported_opt_for_target) 1182 << (Twine("-Wa,") + Equal.first + "=").str() 1183 << Triple.getTriple(); 1184 } else if (!llvm::is_contained(Set, Equal.second)) { 1185 D.Diag(diag::err_drv_unsupported_option_argument) 1186 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second; 1187 } 1188 }; 1189 if (Equal.first == "-mmapsyms") { 1190 ImplicitMapSyms = Equal.second == "implicit"; 1191 checkArg(IsELF && Triple.isAArch64(), {"default", "implicit"}); 1192 } else if (V == "--crel") 1193 Crel = true; 1194 else if (V == "--no-crel") 1195 Crel = false; 1196 else 1197 continue; 1198 A->claim(); 1199 } 1200 } 1201 if (Crel) { 1202 if (IsELF && !Triple.isMIPS()) { 1203 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "-crel")); 1204 } else { 1205 D.Diag(diag::err_drv_unsupported_opt_for_target) 1206 << "-Wa,--crel" << D.getTargetTriple(); 1207 } 1208 } 1209 if (ImplicitMapSyms) 1210 CmdArgs.push_back( 1211 Args.MakeArgString(Twine(PluginOptPrefix) + "-implicit-mapsyms")); 1212 1213 if (Args.hasArg(options::OPT_ftime_report)) 1214 CmdArgs.push_back( 1215 Args.MakeArgString(Twine(PluginOptPrefix) + "-time-passes")); 1216 } 1217 1218 void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC, 1219 const ArgList &Args, 1220 ArgStringList &CmdArgs) { 1221 // Default to clang lib / lib64 folder, i.e. the same location as device 1222 // runtime. 1223 SmallString<256> DefaultLibPath = 1224 llvm::sys::path::parent_path(TC.getDriver().Dir); 1225 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 1226 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath)); 1227 } 1228 1229 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 1230 ArgStringList &CmdArgs) { 1231 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 1232 options::OPT_fno_rtlib_add_rpath, false)) 1233 return; 1234 1235 SmallVector<std::string> CandidateRPaths(TC.getArchSpecificLibPaths()); 1236 if (const auto CandidateRPath = TC.getStdlibPath()) 1237 CandidateRPaths.emplace_back(*CandidateRPath); 1238 1239 for (const auto &CandidateRPath : CandidateRPaths) { 1240 if (TC.getVFS().exists(CandidateRPath)) { 1241 CmdArgs.push_back("-rpath"); 1242 CmdArgs.push_back(Args.MakeArgString(CandidateRPath)); 1243 } 1244 } 1245 } 1246 1247 bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs, 1248 const ToolChain &TC, const ArgList &Args, 1249 bool ForceStaticHostRuntime, bool IsOffloadingHost, 1250 bool GompNeedsRT) { 1251 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 1252 options::OPT_fno_openmp, false)) { 1253 // We need libomptarget (liboffload) if it's the choosen offloading runtime. 1254 if (Args.hasFlag(options::OPT_foffload_via_llvm, 1255 options::OPT_fno_offload_via_llvm, false)) 1256 CmdArgs.push_back("-lomptarget"); 1257 return false; 1258 } 1259 1260 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 1261 1262 if (RTKind == Driver::OMPRT_Unknown) 1263 // Already diagnosed. 1264 return false; 1265 1266 if (ForceStaticHostRuntime) 1267 CmdArgs.push_back("-Bstatic"); 1268 1269 switch (RTKind) { 1270 case Driver::OMPRT_OMP: 1271 CmdArgs.push_back("-lomp"); 1272 break; 1273 case Driver::OMPRT_GOMP: 1274 CmdArgs.push_back("-lgomp"); 1275 break; 1276 case Driver::OMPRT_IOMP5: 1277 CmdArgs.push_back("-liomp5"); 1278 break; 1279 case Driver::OMPRT_Unknown: 1280 break; 1281 } 1282 1283 if (ForceStaticHostRuntime) 1284 CmdArgs.push_back("-Bdynamic"); 1285 1286 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 1287 CmdArgs.push_back("-lrt"); 1288 1289 if (IsOffloadingHost) 1290 CmdArgs.push_back("-lomptarget"); 1291 1292 if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib)) 1293 CmdArgs.push_back("-lomptarget.devicertl"); 1294 1295 addArchSpecificRPath(TC, Args, CmdArgs); 1296 1297 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs); 1298 1299 return true; 1300 } 1301 1302 void tools::addOpenMPHostOffloadingArgs(const Compilation &C, 1303 const JobAction &JA, 1304 const llvm::opt::ArgList &Args, 1305 llvm::opt::ArgStringList &CmdArgs) { 1306 if (!JA.isHostOffloading(Action::OFK_OpenMP)) 1307 return; 1308 1309 // For all the host OpenMP offloading compile jobs we need to pass the targets 1310 // information using -fopenmp-targets= option. 1311 constexpr llvm::StringLiteral Targets("-fopenmp-targets="); 1312 1313 SmallVector<std::string> Triples; 1314 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); 1315 std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples), 1316 [](auto TC) { return TC.second->getTripleString(); }); 1317 CmdArgs.push_back( 1318 Args.MakeArgString(Twine(Targets) + llvm::join(Triples, ","))); 1319 } 1320 1321 /// Add Fortran runtime libs 1322 void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args, 1323 llvm::opt::ArgStringList &CmdArgs) { 1324 // Link FortranRuntime and FortranDecimal 1325 // These are handled earlier on Windows by telling the frontend driver to 1326 // add the correct libraries to link against as dependents in the object 1327 // file. 1328 if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1329 StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary(); 1330 F128LibName.consume_front_insensitive("lib"); 1331 if (!F128LibName.empty()) { 1332 bool AsNeeded = !TC.getTriple().isOSAIX(); 1333 CmdArgs.push_back("-lFortranFloat128Math"); 1334 if (AsNeeded) 1335 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true); 1336 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName)); 1337 if (AsNeeded) 1338 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false); 1339 } 1340 CmdArgs.push_back("-lFortranRuntime"); 1341 CmdArgs.push_back("-lFortranDecimal"); 1342 addArchSpecificRPath(TC, Args, CmdArgs); 1343 } 1344 1345 // libomp needs libatomic for atomic operations if using libgcc 1346 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 1347 options::OPT_fno_openmp, false)) { 1348 Driver::OpenMPRuntimeKind OMPRuntime = 1349 TC.getDriver().getOpenMPRuntime(Args); 1350 ToolChain::RuntimeLibType RuntimeLib = TC.GetRuntimeLibType(Args); 1351 if (OMPRuntime == Driver::OMPRT_OMP && RuntimeLib == ToolChain::RLT_Libgcc) 1352 CmdArgs.push_back("-latomic"); 1353 } 1354 } 1355 1356 void tools::addFortranRuntimeLibraryPath(const ToolChain &TC, 1357 const llvm::opt::ArgList &Args, 1358 ArgStringList &CmdArgs) { 1359 // Default to the <driver-path>/../lib directory. This works fine on the 1360 // platforms that we have tested so far. We will probably have to re-fine 1361 // this in the future. In particular, on some platforms, we may need to use 1362 // lib64 instead of lib. 1363 SmallString<256> DefaultLibPath = 1364 llvm::sys::path::parent_path(TC.getDriver().Dir); 1365 llvm::sys::path::append(DefaultLibPath, "lib"); 1366 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) 1367 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath)); 1368 else 1369 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath)); 1370 } 1371 1372 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 1373 ArgStringList &CmdArgs, StringRef Sanitizer, 1374 bool IsShared, bool IsWhole) { 1375 // Wrap any static runtimes that must be forced into executable in 1376 // whole-archive. 1377 if (IsWhole) CmdArgs.push_back("--whole-archive"); 1378 CmdArgs.push_back(TC.getCompilerRTArgString( 1379 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 1380 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 1381 1382 if (IsShared) { 1383 addArchSpecificRPath(TC, Args, CmdArgs); 1384 } 1385 } 1386 1387 // Tries to use a file with the list of dynamic symbols that need to be exported 1388 // from the runtime library. Returns true if the file was found. 1389 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 1390 ArgStringList &CmdArgs, 1391 StringRef Sanitizer) { 1392 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args); 1393 1394 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 1395 // the option, so don't try to pass it. 1396 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) 1397 return true; 1398 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 1399 if (llvm::sys::fs::exists(SanRT + ".syms")) { 1400 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 1401 return true; 1402 } 1403 return false; 1404 } 1405 1406 void tools::addAsNeededOption(const ToolChain &TC, 1407 const llvm::opt::ArgList &Args, 1408 llvm::opt::ArgStringList &CmdArgs, 1409 bool as_needed) { 1410 assert(!TC.getTriple().isOSAIX() && 1411 "AIX linker does not support any form of --as-needed option yet."); 1412 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args); 1413 1414 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases 1415 // for the native forms -z ignore/-z record, they are missing in Illumos, 1416 // so always use the native form. 1417 // GNU ld doesn't support -z ignore/-z record, so don't use them even on 1418 // Solaris. 1419 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) { 1420 CmdArgs.push_back("-z"); 1421 CmdArgs.push_back(as_needed ? "ignore" : "record"); 1422 } else { 1423 CmdArgs.push_back(as_needed ? "--as-needed" : "--no-as-needed"); 1424 } 1425 } 1426 1427 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 1428 const llvm::opt::ArgList &Args, 1429 ArgStringList &CmdArgs) { 1430 // Force linking against the system libraries sanitizers depends on 1431 // (see PR15823 why this is necessary). 1432 addAsNeededOption(TC, Args, CmdArgs, false); 1433 // There's no libpthread or librt on RTEMS & Android. 1434 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 1435 !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) { 1436 CmdArgs.push_back("-lpthread"); 1437 if (!TC.getTriple().isOSOpenBSD()) 1438 CmdArgs.push_back("-lrt"); 1439 } 1440 CmdArgs.push_back("-lm"); 1441 // There's no libdl on all OSes. 1442 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() && 1443 !TC.getTriple().isOSOpenBSD() && 1444 TC.getTriple().getOS() != llvm::Triple::RTEMS) 1445 CmdArgs.push_back("-ldl"); 1446 // Required for backtrace on some OSes 1447 if (TC.getTriple().isOSFreeBSD() || 1448 TC.getTriple().isOSNetBSD() || 1449 TC.getTriple().isOSOpenBSD()) 1450 CmdArgs.push_back("-lexecinfo"); 1451 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl 1452 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv 1453 // requirement. 1454 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() && 1455 !TC.getTriple().isMusl()) 1456 CmdArgs.push_back("-lresolv"); 1457 } 1458 1459 static void 1460 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 1461 SmallVectorImpl<StringRef> &SharedRuntimes, 1462 SmallVectorImpl<StringRef> &StaticRuntimes, 1463 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 1464 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 1465 SmallVectorImpl<StringRef> &RequiredSymbols) { 1466 assert(!TC.getTriple().isOSDarwin() && "it's not used by Darwin"); 1467 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args); 1468 // Collect shared runtimes. 1469 if (SanArgs.needsSharedRt()) { 1470 if (SanArgs.needsAsanRt()) { 1471 SharedRuntimes.push_back("asan"); 1472 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 1473 HelperStaticRuntimes.push_back("asan-preinit"); 1474 } 1475 if (SanArgs.needsMemProfRt()) { 1476 SharedRuntimes.push_back("memprof"); 1477 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 1478 HelperStaticRuntimes.push_back("memprof-preinit"); 1479 } 1480 if (SanArgs.needsNsanRt()) 1481 SharedRuntimes.push_back("nsan"); 1482 if (SanArgs.needsUbsanRt()) { 1483 if (SanArgs.requiresMinimalRuntime()) 1484 SharedRuntimes.push_back("ubsan_minimal"); 1485 else 1486 SharedRuntimes.push_back("ubsan_standalone"); 1487 } 1488 if (SanArgs.needsScudoRt()) { 1489 SharedRuntimes.push_back("scudo_standalone"); 1490 } 1491 if (SanArgs.needsTsanRt()) 1492 SharedRuntimes.push_back("tsan"); 1493 if (SanArgs.needsTysanRt()) 1494 SharedRuntimes.push_back("tysan"); 1495 if (SanArgs.needsHwasanRt()) { 1496 if (SanArgs.needsHwasanAliasesRt()) 1497 SharedRuntimes.push_back("hwasan_aliases"); 1498 else 1499 SharedRuntimes.push_back("hwasan"); 1500 if (!Args.hasArg(options::OPT_shared)) 1501 HelperStaticRuntimes.push_back("hwasan-preinit"); 1502 } 1503 if (SanArgs.needsRtsanRt() && SanArgs.linkRuntimes()) 1504 SharedRuntimes.push_back("rtsan"); 1505 } 1506 1507 // The stats_client library is also statically linked into DSOs. 1508 if (SanArgs.needsStatsRt()) 1509 StaticRuntimes.push_back("stats_client"); 1510 1511 // Always link the static runtime regardless of DSO or executable. 1512 if (SanArgs.needsAsanRt()) 1513 HelperStaticRuntimes.push_back("asan_static"); 1514 1515 // Collect static runtimes. 1516 if (Args.hasArg(options::OPT_shared)) { 1517 // Don't link static runtimes into DSOs. 1518 return; 1519 } 1520 1521 // Each static runtime that has a DSO counterpart above is excluded below, 1522 // but runtimes that exist only as static are not affected by needsSharedRt. 1523 1524 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) { 1525 StaticRuntimes.push_back("asan"); 1526 if (SanArgs.linkCXXRuntimes()) 1527 StaticRuntimes.push_back("asan_cxx"); 1528 } 1529 1530 if (!SanArgs.needsSharedRt() && SanArgs.needsRtsanRt() && 1531 SanArgs.linkRuntimes()) 1532 StaticRuntimes.push_back("rtsan"); 1533 1534 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) { 1535 StaticRuntimes.push_back("memprof"); 1536 if (SanArgs.linkCXXRuntimes()) 1537 StaticRuntimes.push_back("memprof_cxx"); 1538 } 1539 1540 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) { 1541 if (SanArgs.needsHwasanAliasesRt()) { 1542 StaticRuntimes.push_back("hwasan_aliases"); 1543 if (SanArgs.linkCXXRuntimes()) 1544 StaticRuntimes.push_back("hwasan_aliases_cxx"); 1545 } else { 1546 StaticRuntimes.push_back("hwasan"); 1547 if (SanArgs.linkCXXRuntimes()) 1548 StaticRuntimes.push_back("hwasan_cxx"); 1549 } 1550 } 1551 if (SanArgs.needsDfsanRt()) 1552 StaticRuntimes.push_back("dfsan"); 1553 if (SanArgs.needsLsanRt()) 1554 StaticRuntimes.push_back("lsan"); 1555 if (SanArgs.needsMsanRt()) { 1556 StaticRuntimes.push_back("msan"); 1557 if (SanArgs.linkCXXRuntimes()) 1558 StaticRuntimes.push_back("msan_cxx"); 1559 } 1560 if (!SanArgs.needsSharedRt() && SanArgs.needsNsanRt()) 1561 StaticRuntimes.push_back("nsan"); 1562 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) { 1563 StaticRuntimes.push_back("tsan"); 1564 if (SanArgs.linkCXXRuntimes()) 1565 StaticRuntimes.push_back("tsan_cxx"); 1566 } 1567 if (!SanArgs.needsSharedRt() && SanArgs.needsTysanRt()) 1568 StaticRuntimes.push_back("tysan"); 1569 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) { 1570 if (SanArgs.requiresMinimalRuntime()) { 1571 StaticRuntimes.push_back("ubsan_minimal"); 1572 } else { 1573 StaticRuntimes.push_back("ubsan_standalone"); 1574 } 1575 } 1576 if (SanArgs.needsSafeStackRt()) { 1577 NonWholeStaticRuntimes.push_back("safestack"); 1578 RequiredSymbols.push_back("__safestack_init"); 1579 } 1580 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) { 1581 if (SanArgs.needsCfiRt()) 1582 StaticRuntimes.push_back("cfi"); 1583 if (SanArgs.needsCfiDiagRt()) 1584 StaticRuntimes.push_back("cfi_diag"); 1585 } 1586 if (SanArgs.linkCXXRuntimes() && !SanArgs.requiresMinimalRuntime() && 1587 ((!SanArgs.needsSharedRt() && SanArgs.needsUbsanCXXRt()) || 1588 SanArgs.needsCfiDiagRt())) { 1589 StaticRuntimes.push_back("ubsan_standalone_cxx"); 1590 } 1591 if (SanArgs.needsStatsRt()) { 1592 NonWholeStaticRuntimes.push_back("stats"); 1593 RequiredSymbols.push_back("__sanitizer_stats_register"); 1594 } 1595 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) { 1596 StaticRuntimes.push_back("scudo_standalone"); 1597 if (SanArgs.linkCXXRuntimes()) 1598 StaticRuntimes.push_back("scudo_standalone_cxx"); 1599 } 1600 } 1601 1602 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 1603 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 1604 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 1605 ArgStringList &CmdArgs) { 1606 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args); 1607 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 1608 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 1609 if (SanArgs.linkRuntimes()) { 1610 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 1611 NonWholeStaticRuntimes, HelperStaticRuntimes, 1612 RequiredSymbols); 1613 } 1614 1615 // -u options must be added before the runtime libs that resolve them. 1616 for (auto S : RequiredSymbols) { 1617 CmdArgs.push_back("-u"); 1618 CmdArgs.push_back(Args.MakeArgString(S)); 1619 } 1620 1621 // Inject libfuzzer dependencies. 1622 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 1623 !Args.hasArg(options::OPT_shared)) { 1624 1625 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 1626 if (SanArgs.needsFuzzerInterceptors()) 1627 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false, 1628 true); 1629 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) { 1630 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && 1631 !Args.hasArg(options::OPT_static); 1632 if (OnlyLibstdcxxStatic) 1633 CmdArgs.push_back("-Bstatic"); 1634 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 1635 if (OnlyLibstdcxxStatic) 1636 CmdArgs.push_back("-Bdynamic"); 1637 } 1638 } 1639 1640 for (auto RT : SharedRuntimes) 1641 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 1642 for (auto RT : HelperStaticRuntimes) 1643 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 1644 bool AddExportDynamic = false; 1645 for (auto RT : StaticRuntimes) { 1646 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 1647 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 1648 } 1649 for (auto RT : NonWholeStaticRuntimes) { 1650 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 1651 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 1652 } 1653 // If there is a static runtime with no dynamic list, force all the symbols 1654 // to be dynamic to be sure we export sanitizer interface functions. 1655 if (AddExportDynamic) 1656 CmdArgs.push_back("--export-dynamic"); 1657 1658 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 1659 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check"); 1660 1661 if (SanArgs.hasMemTag()) { 1662 if (!TC.getTriple().isAndroid()) { 1663 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1664 << "-fsanitize=memtag*" << TC.getTriple().str(); 1665 } 1666 CmdArgs.push_back( 1667 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode())); 1668 if (SanArgs.hasMemtagHeap()) 1669 CmdArgs.push_back("--android-memtag-heap"); 1670 if (SanArgs.hasMemtagStack()) 1671 CmdArgs.push_back("--android-memtag-stack"); 1672 } 1673 1674 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 1675 } 1676 1677 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 1678 if (Args.hasArg(options::OPT_shared)) { 1679 if (TC.getXRayArgs().needsXRayDSORt()) { 1680 CmdArgs.push_back("--whole-archive"); 1681 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray-dso")); 1682 CmdArgs.push_back("--no-whole-archive"); 1683 return true; 1684 } 1685 } else if (TC.getXRayArgs().needsXRayRt()) { 1686 CmdArgs.push_back("--whole-archive"); 1687 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 1688 for (const auto &Mode : TC.getXRayArgs().modeList()) 1689 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 1690 CmdArgs.push_back("--no-whole-archive"); 1691 return true; 1692 } 1693 1694 return false; 1695 } 1696 1697 void tools::linkXRayRuntimeDeps(const ToolChain &TC, 1698 const llvm::opt::ArgList &Args, 1699 ArgStringList &CmdArgs) { 1700 addAsNeededOption(TC, Args, CmdArgs, false); 1701 CmdArgs.push_back("-lpthread"); 1702 if (!TC.getTriple().isOSOpenBSD()) 1703 CmdArgs.push_back("-lrt"); 1704 CmdArgs.push_back("-lm"); 1705 1706 if (!TC.getTriple().isOSFreeBSD() && 1707 !TC.getTriple().isOSNetBSD() && 1708 !TC.getTriple().isOSOpenBSD()) 1709 CmdArgs.push_back("-ldl"); 1710 } 1711 1712 bool tools::areOptimizationsEnabled(const ArgList &Args) { 1713 // Find the last -O arg and see if it is non-zero. 1714 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 1715 return !A->getOption().matches(options::OPT_O0); 1716 // Defaults to -O0. 1717 return false; 1718 } 1719 1720 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args, 1721 const InputInfo &Input, 1722 const InputInfo &Output) { 1723 auto AddPostfix = [JA](auto &F) { 1724 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP) 1725 F += (Twine("_") + JA.getOffloadingArch()).str(); 1726 F += ".dwo"; 1727 }; 1728 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 1729 if (StringRef(A->getValue()) == "single" && Output.isFilename()) 1730 return Args.MakeArgString(Output.getFilename()); 1731 1732 SmallString<128> T; 1733 if (const Arg *A = Args.getLastArg(options::OPT_dumpdir)) { 1734 T = A->getValue(); 1735 } else { 1736 Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o); 1737 if (FinalOutput && Args.hasArg(options::OPT_c)) { 1738 T = FinalOutput->getValue(); 1739 llvm::sys::path::remove_filename(T); 1740 llvm::sys::path::append(T, 1741 llvm::sys::path::stem(FinalOutput->getValue())); 1742 AddPostfix(T); 1743 return Args.MakeArgString(T); 1744 } 1745 } 1746 1747 T += llvm::sys::path::stem(Input.getBaseInput()); 1748 AddPostfix(T); 1749 return Args.MakeArgString(T); 1750 } 1751 1752 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 1753 const JobAction &JA, const ArgList &Args, 1754 const InputInfo &Output, const char *OutFile) { 1755 ArgStringList ExtractArgs; 1756 ExtractArgs.push_back("--extract-dwo"); 1757 1758 ArgStringList StripArgs; 1759 StripArgs.push_back("--strip-dwo"); 1760 1761 // Grabbing the output of the earlier compile step. 1762 StripArgs.push_back(Output.getFilename()); 1763 ExtractArgs.push_back(Output.getFilename()); 1764 ExtractArgs.push_back(OutFile); 1765 1766 const char *Exec = 1767 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 1768 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 1769 1770 // First extract the dwo sections. 1771 C.addCommand(std::make_unique<Command>(JA, T, 1772 ResponseFileSupport::AtFileCurCP(), 1773 Exec, ExtractArgs, II, Output)); 1774 1775 // Then remove them from the original .o file. 1776 C.addCommand(std::make_unique<Command>( 1777 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output)); 1778 } 1779 1780 // Claim options we don't want to warn if they are unused. We do this for 1781 // options that build systems might add but are unused when assembling or only 1782 // running the preprocessor for example. 1783 void tools::claimNoWarnArgs(const ArgList &Args) { 1784 // Don't warn about unused -f(no-)?lto. This can happen when we're 1785 // preprocessing, precompiling or assembling. 1786 Args.ClaimAllArgs(options::OPT_flto_EQ); 1787 Args.ClaimAllArgs(options::OPT_flto); 1788 Args.ClaimAllArgs(options::OPT_fno_lto); 1789 } 1790 1791 Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) { 1792 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 1793 options::OPT_fcs_profile_generate_EQ, 1794 options::OPT_fno_profile_generate); 1795 if (CSPGOGenerateArg && 1796 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 1797 CSPGOGenerateArg = nullptr; 1798 1799 return CSPGOGenerateArg; 1800 } 1801 1802 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 1803 auto *ProfileUseArg = Args.getLastArg( 1804 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 1805 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 1806 options::OPT_fno_profile_instr_use); 1807 1808 if (ProfileUseArg && 1809 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 1810 ProfileUseArg = nullptr; 1811 1812 return ProfileUseArg; 1813 } 1814 1815 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 1816 auto *ProfileSampleUseArg = Args.getLastArg( 1817 options::OPT_fprofile_sample_use_EQ, options::OPT_fno_profile_sample_use); 1818 1819 if (ProfileSampleUseArg && (ProfileSampleUseArg->getOption().matches( 1820 options::OPT_fno_profile_sample_use))) 1821 return nullptr; 1822 1823 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ); 1824 } 1825 1826 const char *tools::RelocationModelName(llvm::Reloc::Model Model) { 1827 switch (Model) { 1828 case llvm::Reloc::Static: 1829 return "static"; 1830 case llvm::Reloc::PIC_: 1831 return "pic"; 1832 case llvm::Reloc::DynamicNoPIC: 1833 return "dynamic-no-pic"; 1834 case llvm::Reloc::ROPI: 1835 return "ropi"; 1836 case llvm::Reloc::RWPI: 1837 return "rwpi"; 1838 case llvm::Reloc::ROPI_RWPI: 1839 return "ropi-rwpi"; 1840 } 1841 llvm_unreachable("Unknown Reloc::Model kind"); 1842 } 1843 1844 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 1845 /// smooshes them together with platform defaults, to decide whether 1846 /// this compile should be using PIC mode or not. Returns a tuple of 1847 /// (RelocationModel, PICLevel, IsPIE). 1848 std::tuple<llvm::Reloc::Model, unsigned, bool> 1849 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 1850 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 1851 const llvm::Triple &Triple = ToolChain.getTriple(); 1852 1853 bool PIE = ToolChain.isPIEDefault(Args); 1854 bool PIC = PIE || ToolChain.isPICDefault(); 1855 // The Darwin/MachO default to use PIC does not apply when using -static. 1856 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 1857 PIE = PIC = false; 1858 bool IsPICLevelTwo = PIC; 1859 1860 bool KernelOrKext = 1861 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 1862 1863 // Android-specific defaults for PIC/PIE 1864 if (Triple.isAndroid()) { 1865 switch (Triple.getArch()) { 1866 case llvm::Triple::x86: 1867 case llvm::Triple::x86_64: 1868 PIC = true; // "-fPIC" 1869 IsPICLevelTwo = true; 1870 break; 1871 1872 default: 1873 PIC = true; // "-fpic" 1874 break; 1875 } 1876 } 1877 1878 // OHOS-specific defaults for PIC/PIE 1879 if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64) 1880 PIC = true; 1881 1882 // OpenBSD-specific defaults for PIE 1883 if (Triple.isOSOpenBSD()) { 1884 switch (ToolChain.getArch()) { 1885 case llvm::Triple::arm: 1886 case llvm::Triple::aarch64: 1887 case llvm::Triple::mips64: 1888 case llvm::Triple::mips64el: 1889 case llvm::Triple::x86: 1890 case llvm::Triple::x86_64: 1891 IsPICLevelTwo = false; // "-fpie" 1892 break; 1893 1894 case llvm::Triple::ppc: 1895 case llvm::Triple::sparcv9: 1896 IsPICLevelTwo = true; // "-fPIE" 1897 break; 1898 1899 default: 1900 break; 1901 } 1902 } 1903 1904 // The last argument relating to either PIC or PIE wins, and no 1905 // other argument is used. If the last argument is any flavor of the 1906 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 1907 // option implicitly enables PIC at the same level. 1908 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 1909 options::OPT_fpic, options::OPT_fno_pic, 1910 options::OPT_fPIE, options::OPT_fno_PIE, 1911 options::OPT_fpie, options::OPT_fno_pie); 1912 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg && 1913 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 1914 options::OPT_fPIE, options::OPT_fpie)) { 1915 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1916 << LastPICArg->getSpelling() << Triple.str(); 1917 if (Triple.getArch() == llvm::Triple::x86_64) 1918 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 1919 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1920 } 1921 1922 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 1923 // is forced, then neither PIC nor PIE flags will have no effect. 1924 if (!ToolChain.isPICDefaultForced()) { 1925 if (LastPICArg) { 1926 Option O = LastPICArg->getOption(); 1927 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 1928 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 1929 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 1930 PIC = 1931 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1932 IsPICLevelTwo = 1933 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1934 } else { 1935 PIE = PIC = false; 1936 if (EffectiveTriple.isPS()) { 1937 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1938 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1939 if (Model != "kernel") { 1940 PIC = true; 1941 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic) 1942 << LastPICArg->getSpelling() 1943 << (EffectiveTriple.isPS4() ? "PS4" : "PS5"); 1944 } 1945 } 1946 } 1947 } 1948 } 1949 1950 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but 1951 // the PIC level would've been set to level 1, force it back to level 2 PIC 1952 // instead. 1953 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS())) 1954 IsPICLevelTwo |= ToolChain.isPICDefault(); 1955 1956 // This kernel flags are a trump-card: they will disable PIC/PIE 1957 // generation, independent of the argument order. 1958 if (KernelOrKext && 1959 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1960 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit())) 1961 PIC = PIE = false; 1962 1963 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1964 // This is a very special mode. It trumps the other modes, almost no one 1965 // uses it, and it isn't even valid on any OS but Darwin. 1966 if (!Triple.isOSDarwin()) 1967 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1968 << A->getSpelling() << Triple.str(); 1969 1970 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1971 1972 // Only a forced PIC mode can cause the actual compile to have PIC defines 1973 // etc., no flags are sufficient. This behavior was selected to closely 1974 // match that of llvm-gcc and Apple GCC before that. 1975 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1976 1977 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1978 } 1979 1980 bool EmbeddedPISupported; 1981 switch (Triple.getArch()) { 1982 case llvm::Triple::arm: 1983 case llvm::Triple::armeb: 1984 case llvm::Triple::thumb: 1985 case llvm::Triple::thumbeb: 1986 EmbeddedPISupported = true; 1987 break; 1988 default: 1989 EmbeddedPISupported = false; 1990 break; 1991 } 1992 1993 bool ROPI = false, RWPI = false; 1994 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1995 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1996 if (!EmbeddedPISupported) 1997 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1998 << LastROPIArg->getSpelling() << Triple.str(); 1999 ROPI = true; 2000 } 2001 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 2002 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 2003 if (!EmbeddedPISupported) 2004 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 2005 << LastRWPIArg->getSpelling() << Triple.str(); 2006 RWPI = true; 2007 } 2008 2009 // ROPI and RWPI are not compatible with PIC or PIE. 2010 if ((ROPI || RWPI) && (PIC || PIE)) 2011 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 2012 2013 if (Triple.isMIPS()) { 2014 StringRef CPUName; 2015 StringRef ABIName; 2016 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 2017 // When targeting the N64 ABI, PIC is the default, except in the case 2018 // when the -mno-abicalls option is used. In that case we exit 2019 // at next check regardless of PIC being set below. 2020 if (ABIName == "n64") 2021 PIC = true; 2022 // When targettng MIPS with -mno-abicalls, it's always static. 2023 if(Args.hasArg(options::OPT_mno_abicalls)) 2024 return std::make_tuple(llvm::Reloc::Static, 0U, false); 2025 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 2026 // does not use PIC level 2 for historical reasons. 2027 IsPICLevelTwo = false; 2028 } 2029 2030 if (PIC) 2031 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 2032 2033 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 2034 if (ROPI && RWPI) 2035 RelocM = llvm::Reloc::ROPI_RWPI; 2036 else if (ROPI) 2037 RelocM = llvm::Reloc::ROPI; 2038 else if (RWPI) 2039 RelocM = llvm::Reloc::RWPI; 2040 2041 return std::make_tuple(RelocM, 0U, false); 2042 } 2043 2044 // `-falign-functions` indicates that the functions should be aligned to the 2045 // backend's preferred alignment. 2046 // 2047 // `-falign-functions=1` is the same as `-fno-align-functions`. 2048 // 2049 // The scalar `n` in `-falign-functions=n` must be an integral value between 2050 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 2051 // the nearest power-of-two. 2052 // 2053 // If we return `0`, the frontend will default to the backend's preferred 2054 // alignment. 2055 // 2056 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 2057 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 2058 // alignment. For unaligned functions, we default to the backend's preferred 2059 // alignment. 2060 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 2061 const ArgList &Args) { 2062 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 2063 options::OPT_falign_functions_EQ, 2064 options::OPT_fno_align_functions); 2065 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 2066 return 0; 2067 2068 if (A->getOption().matches(options::OPT_falign_functions)) 2069 return 0; 2070 2071 unsigned Value = 0; 2072 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 2073 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 2074 << A->getAsString(Args) << A->getValue(); 2075 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 2076 } 2077 2078 void tools::addDebugInfoKind( 2079 ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) { 2080 switch (DebugInfoKind) { 2081 case llvm::codegenoptions::DebugDirectivesOnly: 2082 CmdArgs.push_back("-debug-info-kind=line-directives-only"); 2083 break; 2084 case llvm::codegenoptions::DebugLineTablesOnly: 2085 CmdArgs.push_back("-debug-info-kind=line-tables-only"); 2086 break; 2087 case llvm::codegenoptions::DebugInfoConstructor: 2088 CmdArgs.push_back("-debug-info-kind=constructor"); 2089 break; 2090 case llvm::codegenoptions::LimitedDebugInfo: 2091 CmdArgs.push_back("-debug-info-kind=limited"); 2092 break; 2093 case llvm::codegenoptions::FullDebugInfo: 2094 CmdArgs.push_back("-debug-info-kind=standalone"); 2095 break; 2096 case llvm::codegenoptions::UnusedTypeInfo: 2097 CmdArgs.push_back("-debug-info-kind=unused-types"); 2098 break; 2099 default: 2100 break; 2101 } 2102 } 2103 2104 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases 2105 // to the corresponding DebugInfoKind. 2106 llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) { 2107 assert(A.getOption().matches(options::OPT_gN_Group) && 2108 "Not a -g option that specifies a debug-info level"); 2109 if (A.getOption().matches(options::OPT_g0) || 2110 A.getOption().matches(options::OPT_ggdb0)) 2111 return llvm::codegenoptions::NoDebugInfo; 2112 if (A.getOption().matches(options::OPT_gline_tables_only) || 2113 A.getOption().matches(options::OPT_ggdb1)) 2114 return llvm::codegenoptions::DebugLineTablesOnly; 2115 if (A.getOption().matches(options::OPT_gline_directives_only)) 2116 return llvm::codegenoptions::DebugDirectivesOnly; 2117 return llvm::codegenoptions::DebugInfoConstructor; 2118 } 2119 2120 static unsigned ParseDebugDefaultVersion(const ToolChain &TC, 2121 const ArgList &Args) { 2122 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 2123 2124 if (!A) 2125 return 0; 2126 2127 unsigned Value = 0; 2128 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 2129 Value < 2) 2130 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 2131 << A->getAsString(Args) << A->getValue(); 2132 return Value; 2133 } 2134 2135 unsigned tools::DwarfVersionNum(StringRef ArgValue) { 2136 return llvm::StringSwitch<unsigned>(ArgValue) 2137 .Case("-gdwarf-2", 2) 2138 .Case("-gdwarf-3", 3) 2139 .Case("-gdwarf-4", 4) 2140 .Case("-gdwarf-5", 5) 2141 .Default(0); 2142 } 2143 2144 const Arg *tools::getDwarfNArg(const ArgList &Args) { 2145 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3, 2146 options::OPT_gdwarf_4, options::OPT_gdwarf_5, 2147 options::OPT_gdwarf); 2148 } 2149 2150 unsigned tools::getDwarfVersion(const ToolChain &TC, 2151 const llvm::opt::ArgList &Args) { 2152 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args); 2153 if (const Arg *GDwarfN = getDwarfNArg(Args)) 2154 if (int N = DwarfVersionNum(GDwarfN->getSpelling())) { 2155 DwarfVersion = N; 2156 if (DwarfVersion == 5 && TC.getTriple().isOSAIX()) 2157 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 2158 << GDwarfN->getSpelling() << TC.getTriple().str(); 2159 } 2160 if (DwarfVersion == 0) { 2161 DwarfVersion = TC.GetDefaultDwarfVersion(); 2162 assert(DwarfVersion && "toolchain default DWARF version must be nonzero"); 2163 } 2164 return DwarfVersion; 2165 } 2166 2167 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 2168 ArgStringList &CmdArgs) { 2169 llvm::Reloc::Model RelocationModel; 2170 unsigned PICLevel; 2171 bool IsPIE; 2172 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 2173 2174 if (RelocationModel != llvm::Reloc::Static) 2175 CmdArgs.push_back("-KPIC"); 2176 } 2177 2178 /// Determine whether Objective-C automated reference counting is 2179 /// enabled. 2180 bool tools::isObjCAutoRefCount(const ArgList &Args) { 2181 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 2182 } 2183 2184 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 2185 2186 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, 2187 const ArgList &Args) { 2188 if (Args.hasArg(options::OPT_static_libgcc) || 2189 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) || 2190 // The Android NDK only provides libunwind.a, not libunwind.so. 2191 TC.getTriple().isAndroid()) 2192 return LibGccType::StaticLibGcc; 2193 if (Args.hasArg(options::OPT_shared_libgcc)) 2194 return LibGccType::SharedLibGcc; 2195 return LibGccType::UnspecifiedLibGcc; 2196 } 2197 2198 // Gcc adds libgcc arguments in various ways: 2199 // 2200 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 2201 // g++ <none>: -lgcc_s -lgcc 2202 // gcc shared: -lgcc_s -lgcc 2203 // g++ shared: -lgcc_s -lgcc 2204 // gcc static: -lgcc -lgcc_eh 2205 // g++ static: -lgcc -lgcc_eh 2206 // gcc static-pie: -lgcc -lgcc_eh 2207 // g++ static-pie: -lgcc -lgcc_eh 2208 // 2209 // Also, certain targets need additional adjustments. 2210 2211 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 2212 ArgStringList &CmdArgs, const ArgList &Args) { 2213 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 2214 // By default OHOS binaries are linked statically to libunwind. 2215 if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) { 2216 CmdArgs.push_back("-l:libunwind.a"); 2217 return; 2218 } 2219 2220 // Targets that don't use unwind libraries. 2221 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || 2222 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || 2223 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None) 2224 return; 2225 2226 LibGccType LGT = getLibGccType(TC, D, Args); 2227 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 2228 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) && 2229 !TC.getTriple().isAndroid() && 2230 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX(); 2231 if (AsNeeded) 2232 addAsNeededOption(TC, Args, CmdArgs, true); 2233 2234 switch (UNW) { 2235 case ToolChain::UNW_None: 2236 return; 2237 case ToolChain::UNW_Libgcc: { 2238 if (LGT == LibGccType::StaticLibGcc) 2239 CmdArgs.push_back("-lgcc_eh"); 2240 else 2241 CmdArgs.push_back("-lgcc_s"); 2242 break; 2243 } 2244 case ToolChain::UNW_CompilerRT: 2245 if (TC.getTriple().isOSAIX()) { 2246 // AIX only has libunwind as a shared library. So do not pass 2247 // anything in if -static is specified. 2248 if (LGT != LibGccType::StaticLibGcc) 2249 CmdArgs.push_back("-lunwind"); 2250 } else if (LGT == LibGccType::StaticLibGcc) { 2251 CmdArgs.push_back("-l:libunwind.a"); 2252 } else if (LGT == LibGccType::SharedLibGcc) { 2253 if (TC.getTriple().isOSCygMing()) 2254 CmdArgs.push_back("-l:libunwind.dll.a"); 2255 else 2256 CmdArgs.push_back("-l:libunwind.so"); 2257 } else { 2258 // Let the linker choose between libunwind.so and libunwind.a 2259 // depending on what's available, and depending on the -static flag 2260 CmdArgs.push_back("-lunwind"); 2261 } 2262 break; 2263 } 2264 2265 if (AsNeeded) 2266 addAsNeededOption(TC, Args, CmdArgs, false); 2267 } 2268 2269 static void AddLibgcc(const ToolChain &TC, const Driver &D, 2270 ArgStringList &CmdArgs, const ArgList &Args) { 2271 LibGccType LGT = getLibGccType(TC, D, Args); 2272 if (LGT == LibGccType::StaticLibGcc || 2273 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX())) 2274 CmdArgs.push_back("-lgcc"); 2275 AddUnwindLibrary(TC, D, CmdArgs, Args); 2276 if (LGT == LibGccType::SharedLibGcc || 2277 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX())) 2278 CmdArgs.push_back("-lgcc"); 2279 } 2280 2281 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 2282 ArgStringList &CmdArgs, const ArgList &Args) { 2283 // Make use of compiler-rt if --rtlib option is used 2284 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 2285 2286 switch (RLT) { 2287 case ToolChain::RLT_CompilerRT: 2288 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 2289 AddUnwindLibrary(TC, D, CmdArgs, Args); 2290 break; 2291 case ToolChain::RLT_Libgcc: 2292 // Make sure libgcc is not used under MSVC environment by default 2293 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 2294 // Issue error diagnostic if libgcc is explicitly specified 2295 // through command line as --rtlib option argument. 2296 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ); 2297 if (A && A->getValue() != StringRef("platform")) { 2298 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 2299 << A->getValue() << "MSVC"; 2300 } 2301 } else 2302 AddLibgcc(TC, D, CmdArgs, Args); 2303 break; 2304 } 2305 2306 // On Android, the unwinder uses dl_iterate_phdr (or one of 2307 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For 2308 // statically-linked executables, these functions come from libc.a instead. 2309 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) && 2310 !Args.hasArg(options::OPT_static_pie)) 2311 CmdArgs.push_back("-ldl"); 2312 } 2313 2314 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 2315 const InputInfo &Output, 2316 const InputInfo &Input, 2317 const Driver &D) { 2318 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 2319 if (!A && !D.CCPrintInternalStats) 2320 return {}; 2321 2322 SmallString<128> StatsFile; 2323 if (A) { 2324 StringRef SaveStats = A->getValue(); 2325 if (SaveStats == "obj" && Output.isFilename()) { 2326 StatsFile.assign(Output.getFilename()); 2327 llvm::sys::path::remove_filename(StatsFile); 2328 } else if (SaveStats != "cwd") { 2329 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 2330 return {}; 2331 } 2332 2333 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 2334 llvm::sys::path::append(StatsFile, BaseName); 2335 llvm::sys::path::replace_extension(StatsFile, "stats"); 2336 } else { 2337 assert(D.CCPrintInternalStats); 2338 StatsFile.assign(D.CCPrintInternalStatReportFilename.empty() 2339 ? "-" 2340 : D.CCPrintInternalStatReportFilename); 2341 } 2342 return StatsFile; 2343 } 2344 2345 void tools::addMultilibFlag(bool Enabled, const StringRef Flag, 2346 Multilib::flags_list &Flags) { 2347 assert(Flag.front() == '-'); 2348 if (Enabled) { 2349 Flags.push_back(Flag.str()); 2350 } else { 2351 Flags.push_back(("!" + Flag.substr(1)).str()); 2352 } 2353 } 2354 2355 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, 2356 ArgStringList &CmdArgs, bool IsLTO, 2357 const StringRef PluginOptPrefix) { 2358 auto addArg = [&, IsLTO](const Twine &Arg) { 2359 if (IsLTO) { 2360 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!"); 2361 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg)); 2362 } else { 2363 CmdArgs.push_back("-mllvm"); 2364 CmdArgs.push_back(Args.MakeArgString(Arg)); 2365 } 2366 }; 2367 2368 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) { 2369 addArg(Twine("-x86-branches-within-32B-boundaries")); 2370 } 2371 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) { 2372 StringRef Value = A->getValue(); 2373 unsigned Boundary; 2374 if (Value.getAsInteger(10, Boundary) || Boundary < 16 || 2375 !llvm::isPowerOf2_64(Boundary)) { 2376 D.Diag(diag::err_drv_invalid_argument_to_option) 2377 << Value << A->getOption().getName(); 2378 } else { 2379 addArg("-x86-align-branch-boundary=" + Twine(Boundary)); 2380 } 2381 } 2382 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) { 2383 std::string AlignBranch; 2384 for (StringRef T : A->getValues()) { 2385 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && 2386 T != "ret" && T != "indirect") 2387 D.Diag(diag::err_drv_invalid_malign_branch_EQ) 2388 << T << "fused, jcc, jmp, call, ret, indirect"; 2389 if (!AlignBranch.empty()) 2390 AlignBranch += '+'; 2391 AlignBranch += T; 2392 } 2393 addArg("-x86-align-branch=" + Twine(AlignBranch)); 2394 } 2395 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) { 2396 StringRef Value = A->getValue(); 2397 unsigned PrefixSize; 2398 if (Value.getAsInteger(10, PrefixSize)) { 2399 D.Diag(diag::err_drv_invalid_argument_to_option) 2400 << Value << A->getOption().getName(); 2401 } else { 2402 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); 2403 } 2404 } 2405 } 2406 2407 /// SDLSearch: Search for Static Device Library 2408 /// The search for SDL bitcode files is consistent with how static host 2409 /// libraries are discovered. That is, the -l option triggers a search for 2410 /// files in a set of directories called the LINKPATH. The host library search 2411 /// procedure looks for a specific filename in the LINKPATH. The filename for 2412 /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an 2413 /// ordered-set of filenames that are searched. We call this ordered-set of 2414 /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific, 2415 /// architecture specific, or generic across all architectures, a naming 2416 /// convention and search order is used where the file name embeds the 2417 /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type 2418 /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of 2419 /// device-independent SDLs. To reduce congestion in host library directories, 2420 /// the search first looks for files in the “libdevice” subdirectory. SDLs that 2421 /// are bc files begin with the prefix “lib”. 2422 /// 2423 /// Machine-code SDLs can also be managed as an archive (*.a file). The 2424 /// convention has been to use the prefix “lib”. To avoid confusion with host 2425 /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives. 2426 /// 2427 static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs, 2428 llvm::opt::ArgStringList &CC1Args, 2429 const SmallVectorImpl<std::string> &LibraryPaths, 2430 StringRef Lib, StringRef Arch, StringRef Target, 2431 bool isBitCodeSDL) { 2432 SmallVector<std::string, 12> SDLs; 2433 2434 std::string LibDeviceLoc = "/libdevice"; 2435 std::string LibBcPrefix = "/libbc-"; 2436 std::string LibPrefix = "/lib"; 2437 2438 if (isBitCodeSDL) { 2439 // SEARCH-ORDER for Bitcode SDLs: 2440 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a 2441 // libbc-<libname>-<arch-name>-<device-type>.a 2442 // libdevice/libbc-<libname>-<arch-name>.a 2443 // libbc-<libname>-<arch-name>.a 2444 // libdevice/libbc-<libname>.a 2445 // libbc-<libname>.a 2446 // libdevice/lib<libname>-<arch-name>-<device-type>.bc 2447 // lib<libname>-<arch-name>-<device-type>.bc 2448 // libdevice/lib<libname>-<arch-name>.bc 2449 // lib<libname>-<arch-name>.bc 2450 // libdevice/lib<libname>.bc 2451 // lib<libname>.bc 2452 2453 for (StringRef Base : {LibBcPrefix, LibPrefix}) { 2454 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc"; 2455 2456 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), 2457 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) { 2458 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str()); 2459 SDLs.push_back(Twine(Base + Suffix + Ext).str()); 2460 } 2461 } 2462 } else { 2463 // SEARCH-ORDER for Machine-code SDLs: 2464 // libdevice/lib<libname>-<arch-name>-<device-type>.a 2465 // lib<libname>-<arch-name>-<device-type>.a 2466 // libdevice/lib<libname>-<arch-name>.a 2467 // lib<libname>-<arch-name>.a 2468 2469 const auto *Ext = ".a"; 2470 2471 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), 2472 Twine(Lib + "-" + Arch).str()}) { 2473 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str()); 2474 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str()); 2475 } 2476 } 2477 2478 // The CUDA toolchain does not use a global device llvm-link before the LLVM 2479 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is 2480 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that 2481 // will link libraries after clang compilation while the LLVM IR is still in 2482 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”. 2483 // This is a clang -cc1 option that is generated by the clang driver. The 2484 // option value must a full path to an existing file. 2485 bool FoundSDL = false; 2486 for (auto LPath : LibraryPaths) { 2487 for (auto SDL : SDLs) { 2488 auto FullName = Twine(LPath + SDL).str(); 2489 if (llvm::sys::fs::exists(FullName)) { 2490 CC1Args.push_back(DriverArgs.MakeArgString(FullName)); 2491 FoundSDL = true; 2492 break; 2493 } 2494 } 2495 if (FoundSDL) 2496 break; 2497 } 2498 return FoundSDL; 2499 } 2500 2501 /// Search if a user provided archive file lib<libname>.a exists in any of 2502 /// the library paths. If so, add a new command to clang-offload-bundler to 2503 /// unbundle this archive and create a temporary device specific archive. Name 2504 /// of this SDL is passed to the llvm-link tool. 2505 static void GetSDLFromOffloadArchive( 2506 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA, 2507 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, 2508 llvm::opt::ArgStringList &CC1Args, 2509 const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib, 2510 StringRef Arch, StringRef Target, bool isBitCodeSDL) { 2511 2512 // We don't support bitcode archive bundles for nvptx 2513 if (isBitCodeSDL && Arch.contains("nvptx")) 2514 return; 2515 2516 bool FoundAOB = false; 2517 std::string ArchiveOfBundles; 2518 2519 llvm::Triple Triple(D.getTargetTriple()); 2520 bool IsMSVC = Triple.isWindowsMSVCEnvironment(); 2521 auto Ext = IsMSVC ? ".lib" : ".a"; 2522 if (!Lib.starts_with(":") && !Lib.starts_with("-l")) { 2523 if (llvm::sys::fs::exists(Lib)) { 2524 ArchiveOfBundles = Lib; 2525 FoundAOB = true; 2526 } 2527 } else { 2528 Lib.consume_front("-l"); 2529 for (auto LPath : LibraryPaths) { 2530 ArchiveOfBundles.clear(); 2531 auto LibFile = (Lib.starts_with(":") ? Lib.drop_front() 2532 : IsMSVC ? Lib + Ext 2533 : "lib" + Lib + Ext) 2534 .str(); 2535 for (auto Prefix : {"/libdevice/", "/"}) { 2536 auto AOB = Twine(LPath + Prefix + LibFile).str(); 2537 if (llvm::sys::fs::exists(AOB)) { 2538 ArchiveOfBundles = AOB; 2539 FoundAOB = true; 2540 break; 2541 } 2542 } 2543 if (FoundAOB) 2544 break; 2545 } 2546 } 2547 2548 if (!FoundAOB) 2549 return; 2550 2551 llvm::file_magic Magic; 2552 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic); 2553 if (EC || Magic != llvm::file_magic::archive) 2554 return; 2555 2556 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib"; 2557 std::string OutputLib = 2558 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" + 2559 Arch + "-" + Target) 2560 .str(), 2561 "a"); 2562 2563 C.addTempFile(C.getArgs().MakeArgString(OutputLib)); 2564 2565 ArgStringList CmdArgs; 2566 SmallString<128> DeviceTriple; 2567 DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind()); 2568 DeviceTriple += '-'; 2569 std::string NormalizedTriple = T.getToolChain().getTriple().normalize(); 2570 DeviceTriple += NormalizedTriple; 2571 if (!Target.empty()) { 2572 DeviceTriple += '-'; 2573 DeviceTriple += Target; 2574 } 2575 2576 std::string UnbundleArg("-unbundle"); 2577 std::string TypeArg("-type=a"); 2578 std::string InputArg("-input=" + ArchiveOfBundles); 2579 std::string OffloadArg("-targets=" + std::string(DeviceTriple)); 2580 std::string OutputArg("-output=" + OutputLib); 2581 2582 const char *UBProgram = DriverArgs.MakeArgString( 2583 T.getToolChain().GetProgramPath("clang-offload-bundler")); 2584 2585 ArgStringList UBArgs; 2586 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg)); 2587 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg)); 2588 UBArgs.push_back(C.getArgs().MakeArgString(InputArg)); 2589 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg)); 2590 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg)); 2591 2592 // Add this flag to not exit from clang-offload-bundler if no compatible 2593 // code object is found in heterogenous archive library. 2594 std::string AdditionalArgs("-allow-missing-bundles"); 2595 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs)); 2596 2597 // Add this flag to treat hip and hipv4 offload kinds as compatible with 2598 // openmp offload kind while extracting code objects from a heterogenous 2599 // archive library. Vice versa is also considered compatible. 2600 std::string HipCompatibleArgs("-hip-openmp-compatible"); 2601 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs)); 2602 2603 C.addCommand(std::make_unique<Command>( 2604 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs, 2605 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib)))); 2606 2607 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib)); 2608 2609 return; 2610 } 2611 2612 // Wrapper function used by driver for adding SDLs during link phase. 2613 void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, 2614 const JobAction &JA, 2615 const InputInfoList &Inputs, 2616 const llvm::opt::ArgList &DriverArgs, 2617 llvm::opt::ArgStringList &CC1Args, 2618 StringRef Arch, StringRef Target, 2619 bool isBitCodeSDL) { 2620 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args, 2621 Arch, Target, isBitCodeSDL); 2622 } 2623 2624 // User defined Static Device Libraries(SDLs) can be passed to clang for 2625 // offloading GPU compilers. Like static host libraries, the use of a SDL is 2626 // specified with the -l command line option. The primary difference between 2627 // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs 2628 // and SEARCH-ORDER for Machine-code SDLs for the naming convention). 2629 // SDLs are of following types: 2630 // 2631 // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files. 2632 // For NVPTX, these libraries are post-clang linked following each 2633 // compilation. For AMDGPU, these libraries are linked one time 2634 // during the application link phase. 2635 // 2636 // * Machine-code SDLs: They are archive files. For AMDGPU, the process for 2637 // machine code SDLs is still in development. But they will be linked 2638 // by the LLVM tool lld. 2639 // 2640 // * Bundled objects that contain both host and device codes: Bundled objects 2641 // may also contain library code compiled from source. For NVPTX, the 2642 // bundle contains cubin. For AMDGPU, the bundle contains bitcode. 2643 // 2644 // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the 2645 // inclusion of specific SDLs such as math libraries and the OpenMP device 2646 // library libomptarget. 2647 void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T, 2648 const JobAction *JA, 2649 const InputInfoList *Inputs, const Driver &D, 2650 const llvm::opt::ArgList &DriverArgs, 2651 llvm::opt::ArgStringList &CC1Args, 2652 StringRef Arch, StringRef Target, 2653 bool isBitCodeSDL) { 2654 2655 SmallVector<std::string, 8> LibraryPaths; 2656 // Add search directories from LIBRARY_PATH env variable 2657 std::optional<std::string> LibPath = 2658 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 2659 if (LibPath) { 2660 SmallVector<StringRef, 8> Frags; 2661 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 2662 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 2663 for (StringRef Path : Frags) 2664 LibraryPaths.emplace_back(Path.trim()); 2665 } 2666 2667 // Add directories from user-specified -L options 2668 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L)) 2669 LibraryPaths.emplace_back(Search_Dir); 2670 2671 // Add path to lib-debug folders 2672 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir); 2673 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); 2674 LibraryPaths.emplace_back(DefaultLibPath.c_str()); 2675 2676 // Build list of Static Device Libraries SDLs specified by -l option 2677 llvm::SmallSet<std::string, 16> SDLNames; 2678 static const StringRef HostOnlyArchives[] = { 2679 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"}; 2680 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) { 2681 if (!llvm::is_contained(HostOnlyArchives, SDLName)) { 2682 SDLNames.insert(std::string("-l") + SDLName); 2683 } 2684 } 2685 2686 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) { 2687 auto FileName = StringRef(Input); 2688 // Clang treats any unknown file types as archives and passes them to the 2689 // linker. Files with extension 'lib' are classified as TY_Object by clang 2690 // but they are usually archives. It is OK if the file is not really an 2691 // archive since GetSDLFromOffloadArchive will check the magic of the file 2692 // and only unbundle it if it is really an archive. 2693 const StringRef LibFileExt = ".lib"; 2694 if (!llvm::sys::path::has_extension(FileName) || 2695 types::lookupTypeForExtension( 2696 llvm::sys::path::extension(FileName).drop_front()) == 2697 types::TY_INVALID || 2698 llvm::sys::path::extension(FileName) == LibFileExt) 2699 SDLNames.insert(Input); 2700 } 2701 2702 // The search stops as soon as an SDL file is found. The driver then provides 2703 // the full filename of the SDL to the llvm-link command. If no SDL is found 2704 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an 2705 // archive file lib<libname>.a exists and may contain bundled object files. 2706 for (auto SDLName : SDLNames) { 2707 // This is the only call to SDLSearch 2708 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target, 2709 isBitCodeSDL)) { 2710 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args, 2711 LibraryPaths, SDLName, Arch, Target, 2712 isBitCodeSDL); 2713 } 2714 } 2715 } 2716 2717 static llvm::opt::Arg * 2718 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) { 2719 return Args.getLastArg(options::OPT_mcode_object_version_EQ); 2720 } 2721 2722 void tools::checkAMDGPUCodeObjectVersion(const Driver &D, 2723 const llvm::opt::ArgList &Args) { 2724 const unsigned MinCodeObjVer = 4; 2725 const unsigned MaxCodeObjVer = 6; 2726 2727 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { 2728 if (CodeObjArg->getOption().getID() == 2729 options::OPT_mcode_object_version_EQ) { 2730 unsigned CodeObjVer = MaxCodeObjVer; 2731 auto Remnant = 2732 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 2733 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer) 2734 D.Diag(diag::err_drv_invalid_int_value) 2735 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); 2736 2737 // COV6 is only supported by LLVM at the time of writing this, and it's 2738 // expected to take some time before all ROCm components fully 2739 // support it. In the meantime, make sure users are aware of this. 2740 if (CodeObjVer == 6) 2741 D.Diag(diag::warn_drv_amdgpu_cov6); 2742 } 2743 } 2744 } 2745 2746 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D, 2747 const llvm::opt::ArgList &Args) { 2748 unsigned CodeObjVer = 5; // default 2749 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) 2750 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer); 2751 return CodeObjVer; 2752 } 2753 2754 bool tools::haveAMDGPUCodeObjectVersionArgument( 2755 const Driver &D, const llvm::opt::ArgList &Args) { 2756 return getAMDGPUCodeObjectArgument(D, Args) != nullptr; 2757 } 2758 2759 void tools::addMachineOutlinerArgs(const Driver &D, 2760 const llvm::opt::ArgList &Args, 2761 llvm::opt::ArgStringList &CmdArgs, 2762 const llvm::Triple &Triple, bool IsLTO, 2763 const StringRef PluginOptPrefix) { 2764 auto addArg = [&, IsLTO](const Twine &Arg) { 2765 if (IsLTO) { 2766 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!"); 2767 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg)); 2768 } else { 2769 CmdArgs.push_back("-mllvm"); 2770 CmdArgs.push_back(Args.MakeArgString(Arg)); 2771 } 2772 }; 2773 2774 if (Arg *A = Args.getLastArg(options::OPT_moutline, 2775 options::OPT_mno_outline)) { 2776 if (A->getOption().matches(options::OPT_moutline)) { 2777 // We only support -moutline in AArch64 and ARM targets right now. If 2778 // we're not compiling for these, emit a warning and ignore the flag. 2779 // Otherwise, add the proper mllvm flags. 2780 if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) { 2781 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 2782 } else { 2783 addArg(Twine("-enable-machine-outliner")); 2784 } 2785 } else { 2786 // Disable all outlining behaviour. 2787 addArg(Twine("-enable-machine-outliner=never")); 2788 } 2789 } 2790 2791 auto *CodeGenDataGenArg = 2792 Args.getLastArg(options::OPT_fcodegen_data_generate_EQ); 2793 auto *CodeGenDataUseArg = Args.getLastArg(options::OPT_fcodegen_data_use_EQ); 2794 2795 // We only allow one of them to be specified. 2796 if (CodeGenDataGenArg && CodeGenDataUseArg) 2797 D.Diag(diag::err_drv_argument_not_allowed_with) 2798 << CodeGenDataGenArg->getAsString(Args) 2799 << CodeGenDataUseArg->getAsString(Args); 2800 2801 // For codegen data gen, the output file is passed to the linker 2802 // while a boolean flag is passed to the LLVM backend. 2803 if (CodeGenDataGenArg) 2804 addArg(Twine("-codegen-data-generate")); 2805 2806 // For codegen data use, the input file is passed to the LLVM backend. 2807 if (CodeGenDataUseArg) 2808 addArg(Twine("-codegen-data-use-path=") + CodeGenDataUseArg->getValue()); 2809 } 2810 2811 void tools::addOpenMPDeviceRTL(const Driver &D, 2812 const llvm::opt::ArgList &DriverArgs, 2813 llvm::opt::ArgStringList &CC1Args, 2814 StringRef BitcodeSuffix, 2815 const llvm::Triple &Triple, 2816 const ToolChain &HostTC) { 2817 SmallVector<StringRef, 8> LibraryPaths; 2818 2819 // Add user defined library paths from LIBRARY_PATH. 2820 std::optional<std::string> LibPath = 2821 llvm::sys::Process::GetEnv("LIBRARY_PATH"); 2822 if (LibPath) { 2823 SmallVector<StringRef, 8> Frags; 2824 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 2825 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr); 2826 for (StringRef Path : Frags) 2827 LibraryPaths.emplace_back(Path.trim()); 2828 } 2829 2830 // Check all of the standard library search paths used by the compiler. 2831 for (const auto &LibPath : HostTC.getFilePaths()) 2832 LibraryPaths.emplace_back(LibPath); 2833 2834 OptSpecifier LibomptargetBCPathOpt = 2835 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ 2836 : Triple.isNVPTX() ? options::OPT_libomptarget_nvptx_bc_path_EQ 2837 : options::OPT_libomptarget_spirv_bc_path_EQ; 2838 2839 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" 2840 : Triple.isNVPTX() ? "nvptx" 2841 : "spirv64"; 2842 std::string LibOmpTargetName = ("libomptarget-" + ArchPrefix + ".bc").str(); 2843 2844 // First check whether user specifies bc library 2845 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) { 2846 SmallString<128> LibOmpTargetFile(A->getValue()); 2847 if (llvm::sys::fs::exists(LibOmpTargetFile) && 2848 llvm::sys::fs::is_directory(LibOmpTargetFile)) { 2849 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 2850 } 2851 2852 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 2853 CC1Args.push_back("-mlink-builtin-bitcode"); 2854 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 2855 } else { 2856 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found) 2857 << LibOmpTargetFile; 2858 } 2859 } else { 2860 bool FoundBCLibrary = false; 2861 2862 for (StringRef LibraryPath : LibraryPaths) { 2863 SmallString<128> LibOmpTargetFile(LibraryPath); 2864 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName); 2865 if (llvm::sys::fs::exists(LibOmpTargetFile)) { 2866 CC1Args.push_back("-mlink-builtin-bitcode"); 2867 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile)); 2868 FoundBCLibrary = true; 2869 break; 2870 } 2871 } 2872 2873 if (!FoundBCLibrary) 2874 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime) 2875 << LibOmpTargetName << ArchPrefix; 2876 } 2877 } 2878 void tools::addHIPRuntimeLibArgs(const ToolChain &TC, Compilation &C, 2879 const llvm::opt::ArgList &Args, 2880 llvm::opt::ArgStringList &CmdArgs) { 2881 if ((C.getActiveOffloadKinds() & Action::OFK_HIP) && 2882 !Args.hasArg(options::OPT_nostdlib) && 2883 !Args.hasArg(options::OPT_no_hip_rt) && !Args.hasArg(options::OPT_r)) { 2884 TC.AddHIPRuntimeLibArgs(Args, CmdArgs); 2885 } else { 2886 // Claim "no HIP libraries" arguments if any 2887 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) { 2888 Arg->claim(); 2889 } 2890 } 2891 } 2892 2893 void tools::addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, 2894 const llvm::opt::ArgList &Args, 2895 llvm::opt::ArgStringList &CmdArgs, 2896 const llvm::Triple &Triple) { 2897 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics, 2898 options::OPT_mno_outline_atomics)) { 2899 // Option -moutline-atomics supported for AArch64 target only. 2900 if (!Triple.isAArch64()) { 2901 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt) 2902 << Triple.getArchName() << A->getOption().getName(); 2903 } else { 2904 if (A->getOption().matches(options::OPT_moutline_atomics)) { 2905 CmdArgs.push_back("-target-feature"); 2906 CmdArgs.push_back("+outline-atomics"); 2907 } else { 2908 CmdArgs.push_back("-target-feature"); 2909 CmdArgs.push_back("-outline-atomics"); 2910 } 2911 } 2912 } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) { 2913 CmdArgs.push_back("-target-feature"); 2914 CmdArgs.push_back("+outline-atomics"); 2915 } 2916 } 2917 2918 void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, 2919 llvm::opt::ArgStringList &CmdArgs) { 2920 if (TCArgs.hasFlag(options::OPT_offload_compress, 2921 options::OPT_no_offload_compress, false)) 2922 CmdArgs.push_back("-compress"); 2923 if (TCArgs.hasArg(options::OPT_v)) 2924 CmdArgs.push_back("-verbose"); 2925 if (auto *Arg = TCArgs.getLastArg(options::OPT_offload_compression_level_EQ)) 2926 CmdArgs.push_back( 2927 TCArgs.MakeArgString(Twine("-compression-level=") + Arg->getValue())); 2928 } 2929 2930 void tools::addMCModel(const Driver &D, const llvm::opt::ArgList &Args, 2931 const llvm::Triple &Triple, 2932 const llvm::Reloc::Model &RelocationModel, 2933 llvm::opt::ArgStringList &CmdArgs) { 2934 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { 2935 StringRef CM = A->getValue(); 2936 bool Ok = false; 2937 if (Triple.isOSAIX() && CM == "medium") 2938 CM = "large"; 2939 if (Triple.isAArch64(64)) { 2940 Ok = CM == "tiny" || CM == "small" || CM == "large"; 2941 if (CM == "large" && !Triple.isOSBinFormatMachO() && 2942 RelocationModel != llvm::Reloc::Static) 2943 D.Diag(diag::err_drv_argument_only_allowed_with) 2944 << A->getAsString(Args) << "-fno-pic"; 2945 } else if (Triple.isLoongArch()) { 2946 if (CM == "extreme" && 2947 Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false)) 2948 D.Diag(diag::err_drv_argument_not_allowed_with) 2949 << A->getAsString(Args) << "-fplt"; 2950 Ok = CM == "normal" || CM == "medium" || CM == "extreme"; 2951 // Convert to LLVM recognizable names. 2952 if (Ok) 2953 CM = llvm::StringSwitch<StringRef>(CM) 2954 .Case("normal", "small") 2955 .Case("extreme", "large") 2956 .Default(CM); 2957 } else if (Triple.isPPC64() || Triple.isOSAIX()) { 2958 Ok = CM == "small" || CM == "medium" || CM == "large"; 2959 } else if (Triple.isRISCV()) { 2960 // Large code model is disallowed to be used with PIC code model. 2961 if (CM == "large" && RelocationModel != llvm::Reloc::Static) 2962 D.Diag(diag::err_drv_argument_not_allowed_with) 2963 << A->getAsString(Args) << "-fpic"; 2964 if (CM == "medlow") 2965 CM = "small"; 2966 else if (CM == "medany") 2967 CM = "medium"; 2968 Ok = CM == "small" || CM == "medium" || 2969 (CM == "large" && Triple.isRISCV64()); 2970 } else if (Triple.getArch() == llvm::Triple::x86_64) { 2971 Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"}, 2972 CM); 2973 } else if (Triple.isNVPTX() || Triple.isAMDGPU() || Triple.isSPIRV()) { 2974 // NVPTX/AMDGPU/SPIRV does not care about the code model and will accept 2975 // whatever works for the host. 2976 Ok = true; 2977 } else if (Triple.isSPARC64()) { 2978 if (CM == "medlow") 2979 CM = "small"; 2980 else if (CM == "medmid") 2981 CM = "medium"; 2982 else if (CM == "medany") 2983 CM = "large"; 2984 Ok = CM == "small" || CM == "medium" || CM == "large"; 2985 } 2986 if (Ok) { 2987 CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM)); 2988 } else { 2989 D.Diag(diag::err_drv_unsupported_option_argument_for_target) 2990 << A->getSpelling() << CM << Triple.getTriple(); 2991 } 2992 } 2993 2994 if (Triple.getArch() == llvm::Triple::x86_64) { 2995 bool IsMediumCM = false; 2996 bool IsLargeCM = false; 2997 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { 2998 IsMediumCM = StringRef(A->getValue()) == "medium"; 2999 IsLargeCM = StringRef(A->getValue()) == "large"; 3000 } 3001 if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) { 3002 if (!IsMediumCM && !IsLargeCM) { 3003 D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model) 3004 << A->getOption().getRenderName(); 3005 } else { 3006 A->render(Args, CmdArgs); 3007 } 3008 } else if (IsMediumCM) { 3009 CmdArgs.push_back("-mlarge-data-threshold=65536"); 3010 } else if (IsLargeCM) { 3011 CmdArgs.push_back("-mlarge-data-threshold=0"); 3012 } 3013 } 3014 } 3015 3016 void tools::handleColorDiagnosticsArgs(const Driver &D, const ArgList &Args, 3017 ArgStringList &CmdArgs) { 3018 // Color diagnostics are parsed by the driver directly from argv and later 3019 // re-parsed to construct this job; claim any possible color diagnostic here 3020 // to avoid warn_drv_unused_argument and diagnose bad 3021 // OPT_fdiagnostics_color_EQ values. 3022 Args.getLastArg(options::OPT_fcolor_diagnostics, 3023 options::OPT_fno_color_diagnostics); 3024 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) { 3025 StringRef Value(A->getValue()); 3026 if (Value != "always" && Value != "never" && Value != "auto") 3027 D.Diag(diag::err_drv_invalid_argument_to_option) 3028 << Value << A->getOption().getName(); 3029 } 3030 3031 if (D.getDiags().getDiagnosticOptions().ShowColors) 3032 CmdArgs.push_back("-fcolor-diagnostics"); 3033 } 3034 3035 void tools::escapeSpacesAndBackslashes(const char *Arg, 3036 llvm::SmallVectorImpl<char> &Res) { 3037 for (; *Arg; ++Arg) { 3038 switch (*Arg) { 3039 default: 3040 break; 3041 case ' ': 3042 case '\\': 3043 Res.push_back('\\'); 3044 break; 3045 } 3046 Res.push_back(*Arg); 3047 } 3048 } 3049 3050 const char *tools::renderEscapedCommandLine(const ToolChain &TC, 3051 const llvm::opt::ArgList &Args) { 3052 const Driver &D = TC.getDriver(); 3053 const char *Exec = D.getClangProgramPath(); 3054 3055 llvm::opt::ArgStringList OriginalArgs; 3056 for (const auto &Arg : Args) 3057 Arg->render(Args, OriginalArgs); 3058 3059 llvm::SmallString<256> Flags; 3060 escapeSpacesAndBackslashes(Exec, Flags); 3061 for (const char *OriginalArg : OriginalArgs) { 3062 llvm::SmallString<128> EscapedArg; 3063 escapeSpacesAndBackslashes(OriginalArg, EscapedArg); 3064 Flags += " "; 3065 Flags += EscapedArg; 3066 } 3067 3068 return Args.MakeArgString(Flags); 3069 } 3070 3071 bool tools::shouldRecordCommandLine(const ToolChain &TC, 3072 const llvm::opt::ArgList &Args, 3073 bool &FRecordCommandLine, 3074 bool &GRecordCommandLine) { 3075 const Driver &D = TC.getDriver(); 3076 const llvm::Triple &Triple = TC.getEffectiveTriple(); 3077 const std::string &TripleStr = Triple.getTriple(); 3078 3079 FRecordCommandLine = 3080 Args.hasFlag(options::OPT_frecord_command_line, 3081 options::OPT_fno_record_command_line, false); 3082 GRecordCommandLine = 3083 Args.hasFlag(options::OPT_grecord_command_line, 3084 options::OPT_gno_record_command_line, false); 3085 if (FRecordCommandLine && !Triple.isOSBinFormatELF() && 3086 !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO()) 3087 D.Diag(diag::err_drv_unsupported_opt_for_target) 3088 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args) 3089 << TripleStr; 3090 3091 return FRecordCommandLine || TC.UseDwarfDebugFlags() || GRecordCommandLine; 3092 } 3093 3094 void tools::renderCommonIntegerOverflowOptions(const ArgList &Args, 3095 ArgStringList &CmdArgs) { 3096 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but 3097 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv. 3098 bool StrictOverflow = Args.hasFlag(options::OPT_fstrict_overflow, 3099 options::OPT_fno_strict_overflow, true); 3100 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) { 3101 if (A->getOption().matches(options::OPT_fwrapv)) 3102 CmdArgs.push_back("-fwrapv"); 3103 } else if (!StrictOverflow) { 3104 CmdArgs.push_back("-fwrapv"); 3105 } 3106 if (Arg *A = Args.getLastArg(options::OPT_fwrapv_pointer, 3107 options::OPT_fno_wrapv_pointer)) { 3108 if (A->getOption().matches(options::OPT_fwrapv_pointer)) 3109 CmdArgs.push_back("-fwrapv-pointer"); 3110 } else if (!StrictOverflow) { 3111 CmdArgs.push_back("-fwrapv-pointer"); 3112 } 3113 } 3114