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