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/Mips.h" 13 #include "Arch/PPC.h" 14 #include "Arch/SystemZ.h" 15 #include "Arch/X86.h" 16 #include "HIP.h" 17 #include "Hexagon.h" 18 #include "InputInfo.h" 19 #include "clang/Basic/CharInfo.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/ObjCRuntime.h" 22 #include "clang/Basic/Version.h" 23 #include "clang/Config/config.h" 24 #include "clang/Driver/Action.h" 25 #include "clang/Driver/Compilation.h" 26 #include "clang/Driver/Driver.h" 27 #include "clang/Driver/DriverDiagnostic.h" 28 #include "clang/Driver/Job.h" 29 #include "clang/Driver/Options.h" 30 #include "clang/Driver/SanitizerArgs.h" 31 #include "clang/Driver/ToolChain.h" 32 #include "clang/Driver/Util.h" 33 #include "clang/Driver/XRayArgs.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallString.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/Option/Arg.h" 40 #include "llvm/Option/ArgList.h" 41 #include "llvm/Option/Option.h" 42 #include "llvm/Support/CodeGen.h" 43 #include "llvm/Support/Compression.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/FileSystem.h" 47 #include "llvm/Support/Host.h" 48 #include "llvm/Support/Path.h" 49 #include "llvm/Support/Process.h" 50 #include "llvm/Support/Program.h" 51 #include "llvm/Support/ScopedPrinter.h" 52 #include "llvm/Support/TargetParser.h" 53 #include "llvm/Support/VirtualFileSystem.h" 54 #include "llvm/Support/YAMLParser.h" 55 56 using namespace clang::driver; 57 using namespace clang::driver::tools; 58 using namespace clang; 59 using namespace llvm::opt; 60 61 void tools::addPathIfExists(const Driver &D, const Twine &Path, 62 ToolChain::path_list &Paths) { 63 if (D.getVFS().exists(Path)) 64 Paths.push_back(Path.str()); 65 } 66 67 void tools::handleTargetFeaturesGroup(const ArgList &Args, 68 std::vector<StringRef> &Features, 69 OptSpecifier Group) { 70 for (const Arg *A : Args.filtered(Group)) { 71 StringRef Name = A->getOption().getName(); 72 A->claim(); 73 74 // Skip over "-m". 75 assert(Name.startswith("m") && "Invalid feature name."); 76 Name = Name.substr(1); 77 78 bool IsNegative = Name.startswith("no-"); 79 if (IsNegative) 80 Name = Name.substr(3); 81 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); 82 } 83 } 84 85 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, 86 const char *ArgName, const char *EnvVar) { 87 const char *DirList = ::getenv(EnvVar); 88 bool CombinedArg = false; 89 90 if (!DirList) 91 return; // Nothing to do. 92 93 StringRef Name(ArgName); 94 if (Name.equals("-I") || Name.equals("-L") || Name.empty()) 95 CombinedArg = true; 96 97 StringRef Dirs(DirList); 98 if (Dirs.empty()) // Empty string should not add '.'. 99 return; 100 101 StringRef::size_type Delim; 102 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) { 103 if (Delim == 0) { // Leading colon. 104 if (CombinedArg) { 105 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 106 } else { 107 CmdArgs.push_back(ArgName); 108 CmdArgs.push_back("."); 109 } 110 } else { 111 if (CombinedArg) { 112 CmdArgs.push_back( 113 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); 114 } else { 115 CmdArgs.push_back(ArgName); 116 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); 117 } 118 } 119 Dirs = Dirs.substr(Delim + 1); 120 } 121 122 if (Dirs.empty()) { // Trailing colon. 123 if (CombinedArg) { 124 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); 125 } else { 126 CmdArgs.push_back(ArgName); 127 CmdArgs.push_back("."); 128 } 129 } else { // Add the last path. 130 if (CombinedArg) { 131 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); 132 } else { 133 CmdArgs.push_back(ArgName); 134 CmdArgs.push_back(Args.MakeArgString(Dirs)); 135 } 136 } 137 } 138 139 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, 140 const ArgList &Args, ArgStringList &CmdArgs, 141 const JobAction &JA) { 142 const Driver &D = TC.getDriver(); 143 144 // Add extra linker input arguments which are not treated as inputs 145 // (constructed via -Xarch_). 146 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); 147 148 // LIBRARY_PATH are included before user inputs and only supported on native 149 // toolchains. 150 if (!TC.isCrossCompiling()) 151 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); 152 153 for (const auto &II : Inputs) { 154 // If the current tool chain refers to an OpenMP or HIP offloading host, we 155 // should ignore inputs that refer to OpenMP or HIP offloading devices - 156 // they will be embedded according to a proper linker script. 157 if (auto *IA = II.getAction()) 158 if ((JA.isHostOffloading(Action::OFK_OpenMP) && 159 IA->isDeviceOffloading(Action::OFK_OpenMP)) || 160 (JA.isHostOffloading(Action::OFK_HIP) && 161 IA->isDeviceOffloading(Action::OFK_HIP))) 162 continue; 163 164 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType())) 165 // Don't try to pass LLVM inputs unless we have native support. 166 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); 167 168 // Add filenames immediately. 169 if (II.isFilename()) { 170 CmdArgs.push_back(II.getFilename()); 171 continue; 172 } 173 174 // Otherwise, this is a linker input argument. 175 const Arg &A = II.getInputArg(); 176 177 // Handle reserved library options. 178 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) 179 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 180 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) 181 TC.AddCCKextLibArgs(Args, CmdArgs); 182 else if (A.getOption().matches(options::OPT_z)) { 183 // Pass -z prefix for gcc linker compatibility. 184 A.claim(); 185 A.render(Args, CmdArgs); 186 } else { 187 A.renderAsInput(Args, CmdArgs); 188 } 189 } 190 } 191 192 void tools::AddTargetFeature(const ArgList &Args, 193 std::vector<StringRef> &Features, 194 OptSpecifier OnOpt, OptSpecifier OffOpt, 195 StringRef FeatureName) { 196 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { 197 if (A->getOption().matches(OnOpt)) 198 Features.push_back(Args.MakeArgString("+" + FeatureName)); 199 else 200 Features.push_back(Args.MakeArgString("-" + FeatureName)); 201 } 202 } 203 204 /// Get the (LLVM) name of the R600 gpu we are targeting. 205 static std::string getR600TargetGPU(const ArgList &Args) { 206 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 207 const char *GPUName = A->getValue(); 208 return llvm::StringSwitch<const char *>(GPUName) 209 .Cases("rv630", "rv635", "r600") 210 .Cases("rv610", "rv620", "rs780", "rs880") 211 .Case("rv740", "rv770") 212 .Case("palm", "cedar") 213 .Cases("sumo", "sumo2", "sumo") 214 .Case("hemlock", "cypress") 215 .Case("aruba", "cayman") 216 .Default(GPUName); 217 } 218 return ""; 219 } 220 221 static std::string getLanaiTargetCPU(const ArgList &Args) { 222 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 223 return A->getValue(); 224 } 225 return ""; 226 } 227 228 /// Get the (LLVM) name of the WebAssembly cpu we are targeting. 229 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { 230 // If we have -mcpu=, use that. 231 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 232 StringRef CPU = A->getValue(); 233 234 #ifdef __wasm__ 235 // Handle "native" by examining the host. "native" isn't meaningful when 236 // cross compiling, so only support this when the host is also WebAssembly. 237 if (CPU == "native") 238 return llvm::sys::getHostCPUName(); 239 #endif 240 241 return CPU; 242 } 243 244 return "generic"; 245 } 246 247 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T, 248 bool FromAs) { 249 Arg *A; 250 251 switch (T.getArch()) { 252 default: 253 return ""; 254 255 case llvm::Triple::aarch64: 256 case llvm::Triple::aarch64_32: 257 case llvm::Triple::aarch64_be: 258 return aarch64::getAArch64TargetCPU(Args, T, A); 259 260 case llvm::Triple::arm: 261 case llvm::Triple::armeb: 262 case llvm::Triple::thumb: 263 case llvm::Triple::thumbeb: { 264 StringRef MArch, MCPU; 265 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs); 266 return arm::getARMTargetCPU(MCPU, MArch, T); 267 } 268 269 case llvm::Triple::avr: 270 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ)) 271 return A->getValue(); 272 return ""; 273 274 case llvm::Triple::mips: 275 case llvm::Triple::mipsel: 276 case llvm::Triple::mips64: 277 case llvm::Triple::mips64el: { 278 StringRef CPUName; 279 StringRef ABIName; 280 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName); 281 return std::string(CPUName); 282 } 283 284 case llvm::Triple::nvptx: 285 case llvm::Triple::nvptx64: 286 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 287 return A->getValue(); 288 return ""; 289 290 case llvm::Triple::ppc: 291 case llvm::Triple::ppc64: 292 case llvm::Triple::ppc64le: { 293 std::string TargetCPUName = ppc::getPPCTargetCPU(Args); 294 // LLVM may default to generating code for the native CPU, 295 // but, like gcc, we default to a more generic option for 296 // each architecture. (except on Darwin) 297 if (TargetCPUName.empty() && !T.isOSDarwin()) { 298 if (T.getArch() == llvm::Triple::ppc64) 299 TargetCPUName = "ppc64"; 300 else if (T.getArch() == llvm::Triple::ppc64le) 301 TargetCPUName = "ppc64le"; 302 else 303 TargetCPUName = "ppc"; 304 } 305 return TargetCPUName; 306 } 307 308 case llvm::Triple::bpfel: 309 case llvm::Triple::bpfeb: 310 case llvm::Triple::sparc: 311 case llvm::Triple::sparcel: 312 case llvm::Triple::sparcv9: 313 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 314 return A->getValue(); 315 return ""; 316 317 case llvm::Triple::x86: 318 case llvm::Triple::x86_64: 319 return x86::getX86TargetCPU(Args, T); 320 321 case llvm::Triple::hexagon: 322 return "hexagon" + 323 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); 324 325 case llvm::Triple::lanai: 326 return getLanaiTargetCPU(Args); 327 328 case llvm::Triple::systemz: 329 return systemz::getSystemZTargetCPU(Args); 330 331 case llvm::Triple::r600: 332 case llvm::Triple::amdgcn: 333 return getR600TargetGPU(Args); 334 335 case llvm::Triple::wasm32: 336 case llvm::Triple::wasm64: 337 return std::string(getWebAssemblyTargetCPU(Args)); 338 } 339 } 340 341 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) { 342 unsigned Parallelism = 0; 343 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ); 344 if (LtoJobsArg && 345 StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism)) 346 D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args) 347 << LtoJobsArg->getValue(); 348 return Parallelism; 349 } 350 351 // CloudABI uses -ffunction-sections and -fdata-sections by default. 352 bool tools::isUseSeparateSections(const llvm::Triple &Triple) { 353 return Triple.getOS() == llvm::Triple::CloudABI; 354 } 355 356 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args, 357 ArgStringList &CmdArgs, const InputInfo &Output, 358 const InputInfo &Input, bool IsThinLTO) { 359 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath()); 360 if (llvm::sys::path::filename(Linker) != "ld.lld" && 361 llvm::sys::path::stem(Linker) != "ld.lld") { 362 // Tell the linker to load the plugin. This has to come before 363 // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt 364 // that -Wl might forward. 365 CmdArgs.push_back("-plugin"); 366 367 #if defined(_WIN32) 368 const char *Suffix = ".dll"; 369 #elif defined(__APPLE__) 370 const char *Suffix = ".dylib"; 371 #else 372 const char *Suffix = ".so"; 373 #endif 374 375 SmallString<1024> Plugin; 376 llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) + 377 "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + 378 Suffix, 379 Plugin); 380 CmdArgs.push_back(Args.MakeArgString(Plugin)); 381 } 382 383 // Try to pass driver level flags relevant to LTO code generation down to 384 // the plugin. 385 386 // Handle flags for selecting CPU variants. 387 std::string CPU = getCPUName(Args, ToolChain.getTriple()); 388 if (!CPU.empty()) 389 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU)); 390 391 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 392 StringRef OOpt; 393 if (A->getOption().matches(options::OPT_O4) || 394 A->getOption().matches(options::OPT_Ofast)) 395 OOpt = "3"; 396 else if (A->getOption().matches(options::OPT_O)) 397 OOpt = A->getValue(); 398 else if (A->getOption().matches(options::OPT_O0)) 399 OOpt = "0"; 400 if (!OOpt.empty()) 401 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt)); 402 } 403 404 if (Args.hasArg(options::OPT_gsplit_dwarf)) { 405 CmdArgs.push_back( 406 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") + 407 Output.getFilename() + "_dwo")); 408 } 409 410 if (IsThinLTO) 411 CmdArgs.push_back("-plugin-opt=thinlto"); 412 413 if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver())) 414 CmdArgs.push_back( 415 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism))); 416 417 // If an explicit debugger tuning argument appeared, pass it along. 418 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group, 419 options::OPT_ggdbN_Group)) { 420 if (A->getOption().matches(options::OPT_glldb)) 421 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb"); 422 else if (A->getOption().matches(options::OPT_gsce)) 423 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce"); 424 else 425 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb"); 426 } 427 428 bool UseSeparateSections = 429 isUseSeparateSections(ToolChain.getEffectiveTriple()); 430 431 if (Args.hasFlag(options::OPT_ffunction_sections, 432 options::OPT_fno_function_sections, UseSeparateSections)) { 433 CmdArgs.push_back("-plugin-opt=-function-sections"); 434 } 435 436 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 437 UseSeparateSections)) { 438 CmdArgs.push_back("-plugin-opt=-data-sections"); 439 } 440 441 if (Arg *A = getLastProfileSampleUseArg(Args)) { 442 StringRef FName = A->getValue(); 443 if (!llvm::sys::fs::exists(FName)) 444 ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName; 445 else 446 CmdArgs.push_back( 447 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName)); 448 } 449 450 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate, 451 options::OPT_fcs_profile_generate_EQ, 452 options::OPT_fno_profile_generate); 453 if (CSPGOGenerateArg && 454 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 455 CSPGOGenerateArg = nullptr; 456 457 auto *ProfileUseArg = getLastProfileUseArg(Args); 458 459 if (CSPGOGenerateArg) { 460 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate")); 461 if (CSPGOGenerateArg->getOption().matches( 462 options::OPT_fcs_profile_generate_EQ)) { 463 SmallString<128> Path(CSPGOGenerateArg->getValue()); 464 llvm::sys::path::append(Path, "default_%m.profraw"); 465 CmdArgs.push_back( 466 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path)); 467 } else 468 CmdArgs.push_back( 469 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw")); 470 } else if (ProfileUseArg) { 471 SmallString<128> Path( 472 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 473 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 474 llvm::sys::path::append(Path, "default.profdata"); 475 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + 476 Path)); 477 } 478 479 // Need this flag to turn on new pass manager via Gold plugin. 480 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager, 481 options::OPT_fno_experimental_new_pass_manager, 482 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) { 483 CmdArgs.push_back("-plugin-opt=new-pass-manager"); 484 } 485 486 // Setup statistics file output. 487 SmallString<128> StatsFile = 488 getStatsFileName(Args, Output, Input, ToolChain.getDriver()); 489 if (!StatsFile.empty()) 490 CmdArgs.push_back( 491 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile)); 492 } 493 494 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, 495 ArgStringList &CmdArgs) { 496 if (!Args.hasFlag(options::OPT_frtlib_add_rpath, 497 options::OPT_fno_rtlib_add_rpath, false)) 498 return; 499 500 std::string CandidateRPath = TC.getArchSpecificLibPath(); 501 if (TC.getVFS().exists(CandidateRPath)) { 502 CmdArgs.push_back("-rpath"); 503 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str())); 504 } 505 } 506 507 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC, 508 const ArgList &Args, bool ForceStaticHostRuntime, 509 bool IsOffloadingHost, bool GompNeedsRT) { 510 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 511 options::OPT_fno_openmp, false)) 512 return false; 513 514 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); 515 516 if (RTKind == Driver::OMPRT_Unknown) 517 // Already diagnosed. 518 return false; 519 520 if (ForceStaticHostRuntime) 521 CmdArgs.push_back("-Bstatic"); 522 523 switch (RTKind) { 524 case Driver::OMPRT_OMP: 525 CmdArgs.push_back("-lomp"); 526 break; 527 case Driver::OMPRT_GOMP: 528 CmdArgs.push_back("-lgomp"); 529 break; 530 case Driver::OMPRT_IOMP5: 531 CmdArgs.push_back("-liomp5"); 532 break; 533 case Driver::OMPRT_Unknown: 534 break; 535 } 536 537 if (ForceStaticHostRuntime) 538 CmdArgs.push_back("-Bdynamic"); 539 540 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) 541 CmdArgs.push_back("-lrt"); 542 543 if (IsOffloadingHost) 544 CmdArgs.push_back("-lomptarget"); 545 546 addArchSpecificRPath(TC, Args, CmdArgs); 547 548 return true; 549 } 550 551 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, 552 ArgStringList &CmdArgs, StringRef Sanitizer, 553 bool IsShared, bool IsWhole) { 554 // Wrap any static runtimes that must be forced into executable in 555 // whole-archive. 556 if (IsWhole) CmdArgs.push_back("--whole-archive"); 557 CmdArgs.push_back(TC.getCompilerRTArgString( 558 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); 559 if (IsWhole) CmdArgs.push_back("--no-whole-archive"); 560 561 if (IsShared) { 562 addArchSpecificRPath(TC, Args, CmdArgs); 563 } 564 } 565 566 // Tries to use a file with the list of dynamic symbols that need to be exported 567 // from the runtime library. Returns true if the file was found. 568 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, 569 ArgStringList &CmdArgs, 570 StringRef Sanitizer) { 571 // Solaris ld defaults to --export-dynamic behaviour but doesn't support 572 // the option, so don't try to pass it. 573 if (TC.getTriple().getOS() == llvm::Triple::Solaris) 574 return true; 575 // Myriad is static linking only. Furthermore, some versions of its 576 // linker have the bug where --export-dynamic overrides -static, so 577 // don't use --export-dynamic on that platform. 578 if (TC.getTriple().getVendor() == llvm::Triple::Myriad) 579 return true; 580 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer)); 581 if (llvm::sys::fs::exists(SanRT + ".syms")) { 582 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms")); 583 return true; 584 } 585 return false; 586 } 587 588 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, 589 ArgStringList &CmdArgs) { 590 // Fuchsia never needs these. Any sanitizer runtimes with system 591 // dependencies use the `.deplibs` feature instead. 592 if (TC.getTriple().isOSFuchsia()) 593 return; 594 595 // Force linking against the system libraries sanitizers depends on 596 // (see PR15823 why this is necessary). 597 CmdArgs.push_back("--no-as-needed"); 598 // There's no libpthread or librt on RTEMS & Android. 599 if (TC.getTriple().getOS() != llvm::Triple::RTEMS && 600 !TC.getTriple().isAndroid()) { 601 CmdArgs.push_back("-lpthread"); 602 if (!TC.getTriple().isOSOpenBSD()) 603 CmdArgs.push_back("-lrt"); 604 } 605 CmdArgs.push_back("-lm"); 606 // There's no libdl on all OSes. 607 if (!TC.getTriple().isOSFreeBSD() && 608 !TC.getTriple().isOSNetBSD() && 609 !TC.getTriple().isOSOpenBSD() && 610 TC.getTriple().getOS() != llvm::Triple::RTEMS) 611 CmdArgs.push_back("-ldl"); 612 // Required for backtrace on some OSes 613 if (TC.getTriple().isOSFreeBSD() || 614 TC.getTriple().isOSNetBSD()) 615 CmdArgs.push_back("-lexecinfo"); 616 } 617 618 static void 619 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 620 SmallVectorImpl<StringRef> &SharedRuntimes, 621 SmallVectorImpl<StringRef> &StaticRuntimes, 622 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, 623 SmallVectorImpl<StringRef> &HelperStaticRuntimes, 624 SmallVectorImpl<StringRef> &RequiredSymbols) { 625 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 626 // Collect shared runtimes. 627 if (SanArgs.needsSharedRt()) { 628 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 629 SharedRuntimes.push_back("asan"); 630 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid()) 631 HelperStaticRuntimes.push_back("asan-preinit"); 632 } 633 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 634 if (SanArgs.requiresMinimalRuntime()) 635 SharedRuntimes.push_back("ubsan_minimal"); 636 else 637 SharedRuntimes.push_back("ubsan_standalone"); 638 } 639 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 640 if (SanArgs.requiresMinimalRuntime()) 641 SharedRuntimes.push_back("scudo_minimal"); 642 else 643 SharedRuntimes.push_back("scudo"); 644 } 645 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) 646 SharedRuntimes.push_back("hwasan"); 647 } 648 649 // The stats_client library is also statically linked into DSOs. 650 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) 651 StaticRuntimes.push_back("stats_client"); 652 653 // Collect static runtimes. 654 if (Args.hasArg(options::OPT_shared)) { 655 // Don't link static runtimes into DSOs. 656 return; 657 } 658 659 // Each static runtime that has a DSO counterpart above is excluded below, 660 // but runtimes that exist only as static are not affected by needsSharedRt. 661 662 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) { 663 StaticRuntimes.push_back("asan"); 664 if (SanArgs.linkCXXRuntimes()) 665 StaticRuntimes.push_back("asan_cxx"); 666 } 667 668 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) { 669 StaticRuntimes.push_back("hwasan"); 670 if (SanArgs.linkCXXRuntimes()) 671 StaticRuntimes.push_back("hwasan_cxx"); 672 } 673 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes()) 674 StaticRuntimes.push_back("dfsan"); 675 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes()) 676 StaticRuntimes.push_back("lsan"); 677 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) { 678 StaticRuntimes.push_back("msan"); 679 if (SanArgs.linkCXXRuntimes()) 680 StaticRuntimes.push_back("msan_cxx"); 681 } 682 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) { 683 StaticRuntimes.push_back("tsan"); 684 if (SanArgs.linkCXXRuntimes()) 685 StaticRuntimes.push_back("tsan_cxx"); 686 } 687 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) { 688 if (SanArgs.requiresMinimalRuntime()) { 689 StaticRuntimes.push_back("ubsan_minimal"); 690 } else { 691 StaticRuntimes.push_back("ubsan_standalone"); 692 if (SanArgs.linkCXXRuntimes()) 693 StaticRuntimes.push_back("ubsan_standalone_cxx"); 694 } 695 } 696 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) { 697 NonWholeStaticRuntimes.push_back("safestack"); 698 RequiredSymbols.push_back("__safestack_init"); 699 } 700 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) { 701 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes()) 702 StaticRuntimes.push_back("cfi"); 703 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) { 704 StaticRuntimes.push_back("cfi_diag"); 705 if (SanArgs.linkCXXRuntimes()) 706 StaticRuntimes.push_back("ubsan_standalone_cxx"); 707 } 708 } 709 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) { 710 NonWholeStaticRuntimes.push_back("stats"); 711 RequiredSymbols.push_back("__sanitizer_stats_register"); 712 } 713 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) { 714 if (SanArgs.requiresMinimalRuntime()) { 715 StaticRuntimes.push_back("scudo_minimal"); 716 if (SanArgs.linkCXXRuntimes()) 717 StaticRuntimes.push_back("scudo_cxx_minimal"); 718 } else { 719 StaticRuntimes.push_back("scudo"); 720 if (SanArgs.linkCXXRuntimes()) 721 StaticRuntimes.push_back("scudo_cxx"); 722 } 723 } 724 } 725 726 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, 727 // C runtime, etc). Returns true if sanitizer system deps need to be linked in. 728 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, 729 ArgStringList &CmdArgs) { 730 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, 731 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; 732 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, 733 NonWholeStaticRuntimes, HelperStaticRuntimes, 734 RequiredSymbols); 735 736 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(); 737 // Inject libfuzzer dependencies. 738 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && 739 !Args.hasArg(options::OPT_shared)) { 740 741 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true); 742 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) 743 TC.AddCXXStdlibLibArgs(Args, CmdArgs); 744 } 745 746 for (auto RT : SharedRuntimes) 747 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false); 748 for (auto RT : HelperStaticRuntimes) 749 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 750 bool AddExportDynamic = false; 751 for (auto RT : StaticRuntimes) { 752 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true); 753 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 754 } 755 for (auto RT : NonWholeStaticRuntimes) { 756 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false); 757 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT); 758 } 759 for (auto S : RequiredSymbols) { 760 CmdArgs.push_back("-u"); 761 CmdArgs.push_back(Args.MakeArgString(S)); 762 } 763 // If there is a static runtime with no dynamic list, force all the symbols 764 // to be dynamic to be sure we export sanitizer interface functions. 765 if (AddExportDynamic) 766 CmdArgs.push_back("--export-dynamic"); 767 768 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) 769 CmdArgs.push_back("-export-dynamic-symbol=__cfi_check"); 770 771 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); 772 } 773 774 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { 775 if (Args.hasArg(options::OPT_shared)) 776 return false; 777 778 if (TC.getXRayArgs().needsXRayRt()) { 779 CmdArgs.push_back("-whole-archive"); 780 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray")); 781 for (const auto &Mode : TC.getXRayArgs().modeList()) 782 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode)); 783 CmdArgs.push_back("-no-whole-archive"); 784 return true; 785 } 786 787 return false; 788 } 789 790 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) { 791 CmdArgs.push_back("--no-as-needed"); 792 CmdArgs.push_back("-lpthread"); 793 if (!TC.getTriple().isOSOpenBSD()) 794 CmdArgs.push_back("-lrt"); 795 CmdArgs.push_back("-lm"); 796 797 if (!TC.getTriple().isOSFreeBSD() && 798 !TC.getTriple().isOSNetBSD() && 799 !TC.getTriple().isOSOpenBSD()) 800 CmdArgs.push_back("-ldl"); 801 } 802 803 bool tools::areOptimizationsEnabled(const ArgList &Args) { 804 // Find the last -O arg and see if it is non-zero. 805 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 806 return !A->getOption().matches(options::OPT_O0); 807 // Defaults to -O0. 808 return false; 809 } 810 811 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input, 812 const InputInfo &Output) { 813 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ)) 814 if (StringRef(A->getValue()) == "single") 815 return Args.MakeArgString(Output.getFilename()); 816 817 Arg *FinalOutput = Args.getLastArg(options::OPT_o); 818 if (FinalOutput && Args.hasArg(options::OPT_c)) { 819 SmallString<128> T(FinalOutput->getValue()); 820 llvm::sys::path::replace_extension(T, "dwo"); 821 return Args.MakeArgString(T); 822 } else { 823 // Use the compilation dir. 824 SmallString<128> T( 825 Args.getLastArgValue(options::OPT_fdebug_compilation_dir)); 826 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput())); 827 llvm::sys::path::replace_extension(F, "dwo"); 828 T += F; 829 return Args.MakeArgString(F); 830 } 831 } 832 833 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, 834 const JobAction &JA, const ArgList &Args, 835 const InputInfo &Output, const char *OutFile) { 836 ArgStringList ExtractArgs; 837 ExtractArgs.push_back("--extract-dwo"); 838 839 ArgStringList StripArgs; 840 StripArgs.push_back("--strip-dwo"); 841 842 // Grabbing the output of the earlier compile step. 843 StripArgs.push_back(Output.getFilename()); 844 ExtractArgs.push_back(Output.getFilename()); 845 ExtractArgs.push_back(OutFile); 846 847 const char *Exec = 848 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); 849 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); 850 851 // First extract the dwo sections. 852 C.addCommand(std::make_unique<Command>(JA, T, Exec, ExtractArgs, II)); 853 854 // Then remove them from the original .o file. 855 C.addCommand(std::make_unique<Command>(JA, T, Exec, StripArgs, II)); 856 } 857 858 // Claim options we don't want to warn if they are unused. We do this for 859 // options that build systems might add but are unused when assembling or only 860 // running the preprocessor for example. 861 void tools::claimNoWarnArgs(const ArgList &Args) { 862 // Don't warn about unused -f(no-)?lto. This can happen when we're 863 // preprocessing, precompiling or assembling. 864 Args.ClaimAllArgs(options::OPT_flto_EQ); 865 Args.ClaimAllArgs(options::OPT_flto); 866 Args.ClaimAllArgs(options::OPT_fno_lto); 867 } 868 869 Arg *tools::getLastProfileUseArg(const ArgList &Args) { 870 auto *ProfileUseArg = Args.getLastArg( 871 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ, 872 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ, 873 options::OPT_fno_profile_instr_use); 874 875 if (ProfileUseArg && 876 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use)) 877 ProfileUseArg = nullptr; 878 879 return ProfileUseArg; 880 } 881 882 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { 883 auto *ProfileSampleUseArg = Args.getLastArg( 884 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ, 885 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ, 886 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile); 887 888 if (ProfileSampleUseArg && 889 (ProfileSampleUseArg->getOption().matches( 890 options::OPT_fno_profile_sample_use) || 891 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile))) 892 return nullptr; 893 894 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ, 895 options::OPT_fauto_profile_EQ); 896 } 897 898 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, 899 /// smooshes them together with platform defaults, to decide whether 900 /// this compile should be using PIC mode or not. Returns a tuple of 901 /// (RelocationModel, PICLevel, IsPIE). 902 std::tuple<llvm::Reloc::Model, unsigned, bool> 903 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { 904 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); 905 const llvm::Triple &Triple = ToolChain.getTriple(); 906 907 bool PIE = ToolChain.isPIEDefault(); 908 bool PIC = PIE || ToolChain.isPICDefault(); 909 // The Darwin/MachO default to use PIC does not apply when using -static. 910 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static)) 911 PIE = PIC = false; 912 bool IsPICLevelTwo = PIC; 913 914 bool KernelOrKext = 915 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 916 917 // Android-specific defaults for PIC/PIE 918 if (Triple.isAndroid()) { 919 switch (Triple.getArch()) { 920 case llvm::Triple::arm: 921 case llvm::Triple::armeb: 922 case llvm::Triple::thumb: 923 case llvm::Triple::thumbeb: 924 case llvm::Triple::aarch64: 925 case llvm::Triple::mips: 926 case llvm::Triple::mipsel: 927 case llvm::Triple::mips64: 928 case llvm::Triple::mips64el: 929 PIC = true; // "-fpic" 930 break; 931 932 case llvm::Triple::x86: 933 case llvm::Triple::x86_64: 934 PIC = true; // "-fPIC" 935 IsPICLevelTwo = true; 936 break; 937 938 default: 939 break; 940 } 941 } 942 943 // OpenBSD-specific defaults for PIE 944 if (Triple.isOSOpenBSD()) { 945 switch (ToolChain.getArch()) { 946 case llvm::Triple::arm: 947 case llvm::Triple::aarch64: 948 case llvm::Triple::mips64: 949 case llvm::Triple::mips64el: 950 case llvm::Triple::x86: 951 case llvm::Triple::x86_64: 952 IsPICLevelTwo = false; // "-fpie" 953 break; 954 955 case llvm::Triple::ppc: 956 case llvm::Triple::sparc: 957 case llvm::Triple::sparcel: 958 case llvm::Triple::sparcv9: 959 IsPICLevelTwo = true; // "-fPIE" 960 break; 961 962 default: 963 break; 964 } 965 } 966 967 // AMDGPU-specific defaults for PIC. 968 if (Triple.getArch() == llvm::Triple::amdgcn) 969 PIC = true; 970 971 // The last argument relating to either PIC or PIE wins, and no 972 // other argument is used. If the last argument is any flavor of the 973 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE 974 // option implicitly enables PIC at the same level. 975 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, 976 options::OPT_fpic, options::OPT_fno_pic, 977 options::OPT_fPIE, options::OPT_fno_PIE, 978 options::OPT_fpie, options::OPT_fno_pie); 979 if (Triple.isOSWindows() && LastPICArg && 980 LastPICArg == 981 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic, 982 options::OPT_fPIE, options::OPT_fpie)) { 983 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 984 << LastPICArg->getSpelling() << Triple.str(); 985 if (Triple.getArch() == llvm::Triple::x86_64) 986 return std::make_tuple(llvm::Reloc::PIC_, 2U, false); 987 return std::make_tuple(llvm::Reloc::Static, 0U, false); 988 } 989 990 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness 991 // is forced, then neither PIC nor PIE flags will have no effect. 992 if (!ToolChain.isPICDefaultForced()) { 993 if (LastPICArg) { 994 Option O = LastPICArg->getOption(); 995 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || 996 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { 997 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); 998 PIC = 999 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); 1000 IsPICLevelTwo = 1001 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC); 1002 } else { 1003 PIE = PIC = false; 1004 if (EffectiveTriple.isPS4CPU()) { 1005 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ); 1006 StringRef Model = ModelArg ? ModelArg->getValue() : ""; 1007 if (Model != "kernel") { 1008 PIC = true; 1009 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic) 1010 << LastPICArg->getSpelling(); 1011 } 1012 } 1013 } 1014 } 1015 } 1016 1017 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the 1018 // PIC level would've been set to level 1, force it back to level 2 PIC 1019 // instead. 1020 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU())) 1021 IsPICLevelTwo |= ToolChain.isPICDefault(); 1022 1023 // This kernel flags are a trump-card: they will disable PIC/PIE 1024 // generation, independent of the argument order. 1025 if (KernelOrKext && 1026 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) && 1027 !EffectiveTriple.isWatchOS())) 1028 PIC = PIE = false; 1029 1030 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { 1031 // This is a very special mode. It trumps the other modes, almost no one 1032 // uses it, and it isn't even valid on any OS but Darwin. 1033 if (!Triple.isOSDarwin()) 1034 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1035 << A->getSpelling() << Triple.str(); 1036 1037 // FIXME: Warn when this flag trumps some other PIC or PIE flag. 1038 1039 // Only a forced PIC mode can cause the actual compile to have PIC defines 1040 // etc., no flags are sufficient. This behavior was selected to closely 1041 // match that of llvm-gcc and Apple GCC before that. 1042 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); 1043 1044 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false); 1045 } 1046 1047 bool EmbeddedPISupported; 1048 switch (Triple.getArch()) { 1049 case llvm::Triple::arm: 1050 case llvm::Triple::armeb: 1051 case llvm::Triple::thumb: 1052 case llvm::Triple::thumbeb: 1053 EmbeddedPISupported = true; 1054 break; 1055 default: 1056 EmbeddedPISupported = false; 1057 break; 1058 } 1059 1060 bool ROPI = false, RWPI = false; 1061 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi); 1062 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) { 1063 if (!EmbeddedPISupported) 1064 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1065 << LastROPIArg->getSpelling() << Triple.str(); 1066 ROPI = true; 1067 } 1068 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi); 1069 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) { 1070 if (!EmbeddedPISupported) 1071 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target) 1072 << LastRWPIArg->getSpelling() << Triple.str(); 1073 RWPI = true; 1074 } 1075 1076 // ROPI and RWPI are not compatible with PIC or PIE. 1077 if ((ROPI || RWPI) && (PIC || PIE)) 1078 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic); 1079 1080 if (Triple.isMIPS()) { 1081 StringRef CPUName; 1082 StringRef ABIName; 1083 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1084 // When targeting the N64 ABI, PIC is the default, except in the case 1085 // when the -mno-abicalls option is used. In that case we exit 1086 // at next check regardless of PIC being set below. 1087 if (ABIName == "n64") 1088 PIC = true; 1089 // When targettng MIPS with -mno-abicalls, it's always static. 1090 if(Args.hasArg(options::OPT_mno_abicalls)) 1091 return std::make_tuple(llvm::Reloc::Static, 0U, false); 1092 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, 1093 // does not use PIC level 2 for historical reasons. 1094 IsPICLevelTwo = false; 1095 } 1096 1097 if (PIC) 1098 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE); 1099 1100 llvm::Reloc::Model RelocM = llvm::Reloc::Static; 1101 if (ROPI && RWPI) 1102 RelocM = llvm::Reloc::ROPI_RWPI; 1103 else if (ROPI) 1104 RelocM = llvm::Reloc::ROPI; 1105 else if (RWPI) 1106 RelocM = llvm::Reloc::RWPI; 1107 1108 return std::make_tuple(RelocM, 0U, false); 1109 } 1110 1111 // `-falign-functions` indicates that the functions should be aligned to a 1112 // 16-byte boundary. 1113 // 1114 // `-falign-functions=1` is the same as `-fno-align-functions`. 1115 // 1116 // The scalar `n` in `-falign-functions=n` must be an integral value between 1117 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to 1118 // the nearest power-of-two. 1119 // 1120 // If we return `0`, the frontend will default to the backend's preferred 1121 // alignment. 1122 // 1123 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` 1124 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred 1125 // alignment. For unaligned functions, we default to the backend's preferred 1126 // alignment. 1127 unsigned tools::ParseFunctionAlignment(const ToolChain &TC, 1128 const ArgList &Args) { 1129 const Arg *A = Args.getLastArg(options::OPT_falign_functions, 1130 options::OPT_falign_functions_EQ, 1131 options::OPT_fno_align_functions); 1132 if (!A || A->getOption().matches(options::OPT_fno_align_functions)) 1133 return 0; 1134 1135 if (A->getOption().matches(options::OPT_falign_functions)) 1136 return 0; 1137 1138 unsigned Value = 0; 1139 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536) 1140 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1141 << A->getAsString(Args) << A->getValue(); 1142 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value; 1143 } 1144 1145 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC, 1146 const ArgList &Args) { 1147 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version); 1148 1149 if (!A) 1150 return 0; 1151 1152 unsigned Value = 0; 1153 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 || 1154 Value < 2) 1155 TC.getDriver().Diag(diag::err_drv_invalid_int_value) 1156 << A->getAsString(Args) << A->getValue(); 1157 return Value; 1158 } 1159 1160 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, 1161 ArgStringList &CmdArgs) { 1162 llvm::Reloc::Model RelocationModel; 1163 unsigned PICLevel; 1164 bool IsPIE; 1165 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args); 1166 1167 if (RelocationModel != llvm::Reloc::Static) 1168 CmdArgs.push_back("-KPIC"); 1169 } 1170 1171 /// Determine whether Objective-C automated reference counting is 1172 /// enabled. 1173 bool tools::isObjCAutoRefCount(const ArgList &Args) { 1174 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 1175 } 1176 1177 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; 1178 1179 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) { 1180 if (Args.hasArg(options::OPT_static_libgcc) || 1181 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie)) 1182 return LibGccType::StaticLibGcc; 1183 if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX()) 1184 return LibGccType::SharedLibGcc; 1185 return LibGccType::UnspecifiedLibGcc; 1186 } 1187 1188 // Gcc adds libgcc arguments in various ways: 1189 // 1190 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed 1191 // g++ <none>: -lgcc_s -lgcc 1192 // gcc shared: -lgcc_s -lgcc 1193 // g++ shared: -lgcc_s -lgcc 1194 // gcc static: -lgcc -lgcc_eh 1195 // g++ static: -lgcc -lgcc_eh 1196 // gcc static-pie: -lgcc -lgcc_eh 1197 // g++ static-pie: -lgcc -lgcc_eh 1198 // 1199 // Also, certain targets need additional adjustments. 1200 1201 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, 1202 ArgStringList &CmdArgs, const ArgList &Args) { 1203 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); 1204 // Targets that don't use unwind libraries. 1205 if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() || 1206 TC.getTriple().isOSBinFormatWasm() || 1207 UNW == ToolChain::UNW_None) 1208 return; 1209 1210 LibGccType LGT = getLibGccType(D, Args); 1211 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && 1212 !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing(); 1213 if (AsNeeded) 1214 CmdArgs.push_back("--as-needed"); 1215 1216 switch (UNW) { 1217 case ToolChain::UNW_None: 1218 return; 1219 case ToolChain::UNW_Libgcc: { 1220 if (LGT == LibGccType::StaticLibGcc) 1221 CmdArgs.push_back("-lgcc_eh"); 1222 else 1223 CmdArgs.push_back("-lgcc_s"); 1224 break; 1225 } 1226 case ToolChain::UNW_CompilerRT: 1227 if (LGT == LibGccType::StaticLibGcc) 1228 CmdArgs.push_back("-l:libunwind.a"); 1229 else 1230 CmdArgs.push_back("-l:libunwind.so"); 1231 break; 1232 } 1233 1234 if (AsNeeded) 1235 CmdArgs.push_back("--no-as-needed"); 1236 } 1237 1238 static void AddLibgcc(const ToolChain &TC, const Driver &D, 1239 ArgStringList &CmdArgs, const ArgList &Args) { 1240 LibGccType LGT = getLibGccType(D, Args); 1241 if (LGT != LibGccType::SharedLibGcc) 1242 CmdArgs.push_back("-lgcc"); 1243 AddUnwindLibrary(TC, D, CmdArgs, Args); 1244 if (LGT == LibGccType::SharedLibGcc) 1245 CmdArgs.push_back("-lgcc"); 1246 1247 // According to Android ABI, we have to link with libdl if we are 1248 // linking with non-static libgcc. 1249 // 1250 // NOTE: This fixes a link error on Android MIPS as well. The non-static 1251 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl. 1252 if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc) 1253 CmdArgs.push_back("-ldl"); 1254 } 1255 1256 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, 1257 ArgStringList &CmdArgs, const ArgList &Args) { 1258 // Make use of compiler-rt if --rtlib option is used 1259 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); 1260 1261 switch (RLT) { 1262 case ToolChain::RLT_CompilerRT: 1263 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins")); 1264 AddUnwindLibrary(TC, D, CmdArgs, Args); 1265 break; 1266 case ToolChain::RLT_Libgcc: 1267 // Make sure libgcc is not used under MSVC environment by default 1268 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { 1269 // Issue error diagnostic if libgcc is explicitly specified 1270 // through command line as --rtlib option argument. 1271 if (Args.hasArg(options::OPT_rtlib_EQ)) { 1272 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 1273 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC"; 1274 } 1275 } else 1276 AddLibgcc(TC, D, CmdArgs, Args); 1277 break; 1278 } 1279 } 1280 1281 /// Add HIP linker script arguments at the end of the argument list so that 1282 /// the fat binary is built by embedding the device images into the host. The 1283 /// linker script also defines a symbol required by the code generation so that 1284 /// the image can be retrieved at runtime. This should be used only in tool 1285 /// chains that support linker scripts. 1286 void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C, 1287 const InputInfo &Output, 1288 const InputInfoList &Inputs, const ArgList &Args, 1289 ArgStringList &CmdArgs, const JobAction &JA, 1290 const Tool &T) { 1291 1292 // If this is not a HIP host toolchain, we don't need to do anything. 1293 if (!JA.isHostOffloading(Action::OFK_HIP)) 1294 return; 1295 1296 InputInfoList DeviceInputs; 1297 for (const auto &II : Inputs) { 1298 const Action *A = II.getAction(); 1299 // Is this a device linking action? 1300 if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) { 1301 DeviceInputs.push_back(II); 1302 } 1303 } 1304 1305 if (DeviceInputs.empty()) 1306 return; 1307 1308 // Create temporary linker script. Keep it if save-temps is enabled. 1309 const char *LKS; 1310 std::string Name = 1311 std::string(llvm::sys::path::filename(Output.getFilename())); 1312 if (C.getDriver().isSaveTempsEnabled()) { 1313 LKS = C.getArgs().MakeArgString(Name + ".lk"); 1314 } else { 1315 auto TmpName = C.getDriver().GetTemporaryPath(Name, "lk"); 1316 LKS = C.addTempFile(C.getArgs().MakeArgString(TmpName)); 1317 } 1318 1319 // Add linker script option to the command. 1320 CmdArgs.push_back("-T"); 1321 CmdArgs.push_back(LKS); 1322 1323 // Create a buffer to write the contents of the linker script. 1324 std::string LksBuffer; 1325 llvm::raw_string_ostream LksStream(LksBuffer); 1326 1327 // Get the HIP offload tool chain. 1328 auto *HIPTC = static_cast<const toolchains::CudaToolChain *>( 1329 C.getSingleOffloadToolChain<Action::OFK_HIP>()); 1330 assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn && 1331 "Wrong platform"); 1332 (void)HIPTC; 1333 1334 const char *BundleFile; 1335 if (C.getDriver().isSaveTempsEnabled()) { 1336 BundleFile = C.getArgs().MakeArgString(Name + ".hipfb"); 1337 } else { 1338 auto TmpName = C.getDriver().GetTemporaryPath(Name, "hipfb"); 1339 BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpName)); 1340 } 1341 AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T); 1342 1343 // Add commands to embed target binaries. We ensure that each section and 1344 // image is 16-byte aligned. This is not mandatory, but increases the 1345 // likelihood of data to be aligned with a cache block in several main host 1346 // machines. 1347 LksStream << "/*\n"; 1348 LksStream << " HIP Offload Linker Script\n"; 1349 LksStream << " *** Automatically generated by Clang ***\n"; 1350 LksStream << "*/\n"; 1351 LksStream << "TARGET(binary)\n"; 1352 LksStream << "INPUT(" << BundleFile << ")\n"; 1353 LksStream << "SECTIONS\n"; 1354 LksStream << "{\n"; 1355 LksStream << " .hip_fatbin :\n"; 1356 LksStream << " ALIGN(0x10)\n"; 1357 LksStream << " {\n"; 1358 LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n"; 1359 LksStream << " " << BundleFile << "\n"; 1360 LksStream << " }\n"; 1361 LksStream << " /DISCARD/ :\n"; 1362 LksStream << " {\n"; 1363 LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n"; 1364 LksStream << " }\n"; 1365 LksStream << "}\n"; 1366 LksStream << "INSERT BEFORE .data\n"; 1367 LksStream.flush(); 1368 1369 // Dump the contents of the linker script if the user requested that. We 1370 // support this option to enable testing of behavior with -###. 1371 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script)) 1372 llvm::errs() << LksBuffer; 1373 1374 // If this is a dry run, do not create the linker script file. 1375 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) 1376 return; 1377 1378 // Open script file and write the contents. 1379 std::error_code EC; 1380 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::OF_None); 1381 1382 if (EC) { 1383 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 1384 return; 1385 } 1386 1387 Lksf << LksBuffer; 1388 } 1389 1390 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, 1391 const InputInfo &Output, 1392 const InputInfo &Input, 1393 const Driver &D) { 1394 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ); 1395 if (!A) 1396 return {}; 1397 1398 StringRef SaveStats = A->getValue(); 1399 SmallString<128> StatsFile; 1400 if (SaveStats == "obj" && Output.isFilename()) { 1401 StatsFile.assign(Output.getFilename()); 1402 llvm::sys::path::remove_filename(StatsFile); 1403 } else if (SaveStats != "cwd") { 1404 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; 1405 return {}; 1406 } 1407 1408 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput()); 1409 llvm::sys::path::append(StatsFile, BaseName); 1410 llvm::sys::path::replace_extension(StatsFile, "stats"); 1411 return StatsFile; 1412 } 1413 1414 void tools::addMultilibFlag(bool Enabled, const char *const Flag, 1415 Multilib::flags_list &Flags) { 1416 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag); 1417 } 1418