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