1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "CommonArgs.h"
10 #include "Arch/AArch64.h"
12 #include "Arch/Mips.h"
14 #include "Arch/SystemZ.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"
58 using namespace clang::driver;
59 using namespace clang::driver::tools;
60 using namespace clang;
61 using namespace llvm::opt;
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());
69 void tools::handleTargetFeaturesGroup(const ArgList &Args,
70 std::vector<StringRef> &Features,
72 for (const Arg *A : Args.filtered(Group)) {
73 StringRef Name = A->getOption().getName();
77 assert(Name.startswith("m") && "Invalid feature name.");
78 Name = Name.substr(1);
80 bool IsNegative = Name.startswith("no-");
82 Name = Name.substr(3);
83 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
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;
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;
107 UnifiedFeatures.push_back(Name);
109 return UnifiedFeatures;
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;
118 return; // Nothing to do.
120 StringRef Name(ArgName);
121 if (Name.equals("-I") || Name.equals("-L") || Name.empty())
124 StringRef Dirs(DirList);
125 if (Dirs.empty()) // Empty string should not add '.'.
128 StringRef::size_type Delim;
129 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
130 if (Delim == 0) { // Leading colon.
132 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
134 CmdArgs.push_back(ArgName);
135 CmdArgs.push_back(".");
140 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
142 CmdArgs.push_back(ArgName);
143 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
146 Dirs = Dirs.substr(Delim + 1);
149 if (Dirs.empty()) { // Trailing colon.
151 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
153 CmdArgs.push_back(ArgName);
154 CmdArgs.push_back(".");
156 } else { // Add the last path.
158 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
160 CmdArgs.push_back(ArgName);
161 CmdArgs.push_back(Args.MakeArgString(Dirs));
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();
171 // Add extra linker input arguments which are not treated as inputs
172 // (constructed via -Xarch_).
173 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
175 // LIBRARY_PATH are included before user inputs and only supported on native
177 if (!TC.isCrossCompiling())
178 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
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)))
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();
193 // Add filenames immediately.
194 if (II.isFilename()) {
195 CmdArgs.push_back(II.getFilename());
199 // Otherwise, this is a linker input argument.
200 const Arg &A = II.getInputArg();
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.
210 A.render(Args, CmdArgs);
212 A.renderAsInput(Args, CmdArgs);
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
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));
230 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
231 << A->getOption().getName() << V;
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));
243 Features.push_back(Args.MakeArgString("-" + FeatureName));
247 /// Get the (LLVM) name of the R600 gpu we are targeting.
248 static std::string getR600TargetGPU(const ArgList &Args) {
249 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
250 const char *GPUName = A->getValue();
251 return llvm::StringSwitch<const char *>(GPUName)
252 .Cases("rv630", "rv635", "r600")
253 .Cases("rv610", "rv620", "rs780", "rs880")
254 .Case("rv740", "rv770")
255 .Case("palm", "cedar")
256 .Cases("sumo", "sumo2", "sumo")
257 .Case("hemlock", "cypress")
258 .Case("aruba", "cayman")
264 static std::string getLanaiTargetCPU(const ArgList &Args) {
265 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
266 return A->getValue();
271 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
272 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
273 // If we have -mcpu=, use that.
274 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
275 StringRef CPU = A->getValue();
278 // Handle "native" by examining the host. "native" isn't meaningful when
279 // cross compiling, so only support this when the host is also WebAssembly.
281 return llvm::sys::getHostCPUName();
290 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
294 switch (T.getArch()) {
298 case llvm::Triple::aarch64:
299 case llvm::Triple::aarch64_32:
300 case llvm::Triple::aarch64_be:
301 return aarch64::getAArch64TargetCPU(Args, T, A);
303 case llvm::Triple::arm:
304 case llvm::Triple::armeb:
305 case llvm::Triple::thumb:
306 case llvm::Triple::thumbeb: {
307 StringRef MArch, MCPU;
308 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
309 return arm::getARMTargetCPU(MCPU, MArch, T);
312 case llvm::Triple::avr:
313 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
314 return A->getValue();
317 case llvm::Triple::mips:
318 case llvm::Triple::mipsel:
319 case llvm::Triple::mips64:
320 case llvm::Triple::mips64el: {
323 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
324 return std::string(CPUName);
327 case llvm::Triple::nvptx:
328 case llvm::Triple::nvptx64:
329 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
330 return A->getValue();
333 case llvm::Triple::ppc:
334 case llvm::Triple::ppc64:
335 case llvm::Triple::ppc64le: {
336 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
337 // LLVM may default to generating code for the native CPU,
338 // but, like gcc, we default to a more generic option for
339 // each architecture. (except on AIX)
340 if (!TargetCPUName.empty())
341 return TargetCPUName;
344 TargetCPUName = "pwr4";
345 else if (T.getArch() == llvm::Triple::ppc64le)
346 TargetCPUName = "ppc64le";
347 else if (T.getArch() == llvm::Triple::ppc64)
348 TargetCPUName = "ppc64";
350 TargetCPUName = "ppc";
352 return TargetCPUName;
354 case llvm::Triple::riscv32:
355 case llvm::Triple::riscv64:
356 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
357 return A->getValue();
360 case llvm::Triple::bpfel:
361 case llvm::Triple::bpfeb:
362 case llvm::Triple::sparc:
363 case llvm::Triple::sparcel:
364 case llvm::Triple::sparcv9:
365 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
366 return A->getValue();
369 case llvm::Triple::x86:
370 case llvm::Triple::x86_64:
371 return x86::getX86TargetCPU(Args, T);
373 case llvm::Triple::hexagon:
375 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
377 case llvm::Triple::lanai:
378 return getLanaiTargetCPU(Args);
380 case llvm::Triple::systemz:
381 return systemz::getSystemZTargetCPU(Args);
383 case llvm::Triple::r600:
384 case llvm::Triple::amdgcn:
385 return getR600TargetGPU(Args);
387 case llvm::Triple::wasm32:
388 case llvm::Triple::wasm64:
389 return std::string(getWebAssemblyTargetCPU(Args));
393 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
394 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
397 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
398 D.Diag(diag::err_drv_invalid_int_value)
399 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
400 return LtoJobsArg->getValue();
403 // CloudABI uses -ffunction-sections and -fdata-sections by default.
404 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
405 return Triple.getOS() == llvm::Triple::CloudABI;
408 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
409 ArgStringList &CmdArgs, const InputInfo &Output,
410 const InputInfo &Input, bool IsThinLTO) {
411 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
412 const Driver &D = ToolChain.getDriver();
413 if (llvm::sys::path::filename(Linker) != "ld.lld" &&
414 llvm::sys::path::stem(Linker) != "ld.lld") {
415 // Tell the linker to load the plugin. This has to come before
416 // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
417 // that -Wl might forward.
418 CmdArgs.push_back("-plugin");
421 const char *Suffix = ".dll";
422 #elif defined(__APPLE__)
423 const char *Suffix = ".dylib";
425 const char *Suffix = ".so";
428 SmallString<1024> Plugin;
429 llvm::sys::path::native(
430 Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
432 CmdArgs.push_back(Args.MakeArgString(Plugin));
435 // Try to pass driver level flags relevant to LTO code generation down to
438 // Handle flags for selecting CPU variants.
439 std::string CPU = getCPUName(Args, ToolChain.getTriple());
441 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
443 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
444 // The optimization level matches
445 // CompilerInvocation.cpp:getOptimizationLevel().
447 if (A->getOption().matches(options::OPT_O4) ||
448 A->getOption().matches(options::OPT_Ofast))
450 else if (A->getOption().matches(options::OPT_O)) {
451 OOpt = A->getValue();
454 else if (OOpt == "s" || OOpt == "z")
456 } else if (A->getOption().matches(options::OPT_O0))
459 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
462 if (Args.hasArg(options::OPT_gsplit_dwarf)) {
464 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
465 Output.getFilename() + "_dwo"));
469 CmdArgs.push_back("-plugin-opt=thinlto");
471 StringRef Parallelism = getLTOParallelism(Args, D);
472 if (!Parallelism.empty())
474 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
476 // If an explicit debugger tuning argument appeared, pass it along.
477 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
478 options::OPT_ggdbN_Group)) {
479 if (A->getOption().matches(options::OPT_glldb))
480 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
481 else if (A->getOption().matches(options::OPT_gsce))
482 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
484 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
487 bool UseSeparateSections =
488 isUseSeparateSections(ToolChain.getEffectiveTriple());
490 if (Args.hasFlag(options::OPT_ffunction_sections,
491 options::OPT_fno_function_sections, UseSeparateSections)) {
492 CmdArgs.push_back("-plugin-opt=-function-sections");
495 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
496 UseSeparateSections)) {
497 CmdArgs.push_back("-plugin-opt=-data-sections");
500 if (Arg *A = getLastProfileSampleUseArg(Args)) {
501 StringRef FName = A->getValue();
502 if (!llvm::sys::fs::exists(FName))
503 D.Diag(diag::err_drv_no_such_file) << FName;
506 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
509 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
510 options::OPT_fcs_profile_generate_EQ,
511 options::OPT_fno_profile_generate);
512 if (CSPGOGenerateArg &&
513 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
514 CSPGOGenerateArg = nullptr;
516 auto *ProfileUseArg = getLastProfileUseArg(Args);
518 if (CSPGOGenerateArg) {
519 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
520 if (CSPGOGenerateArg->getOption().matches(
521 options::OPT_fcs_profile_generate_EQ)) {
522 SmallString<128> Path(CSPGOGenerateArg->getValue());
523 llvm::sys::path::append(Path, "default_%m.profraw");
525 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
528 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
529 } else if (ProfileUseArg) {
530 SmallString<128> Path(
531 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
532 if (Path.empty() || llvm::sys::fs::is_directory(Path))
533 llvm::sys::path::append(Path, "default.profdata");
534 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
538 // Need this flag to turn on new pass manager via Gold plugin.
539 if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
540 options::OPT_fno_experimental_new_pass_manager,
541 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
542 CmdArgs.push_back("-plugin-opt=new-pass-manager");
545 // Setup statistics file output.
546 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
547 if (!StatsFile.empty())
549 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
551 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
554 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
555 ArgStringList &CmdArgs) {
556 // Enable -frtlib-add-rpath by default for the case of VE.
557 const bool IsVE = TC.getTriple().isVE();
558 bool DefaultValue = IsVE;
559 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
560 options::OPT_fno_rtlib_add_rpath, DefaultValue))
563 std::string CandidateRPath = TC.getArchSpecificLibPath();
564 if (TC.getVFS().exists(CandidateRPath)) {
565 CmdArgs.push_back("-rpath");
566 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
570 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
571 const ArgList &Args, bool ForceStaticHostRuntime,
572 bool IsOffloadingHost, bool GompNeedsRT) {
573 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
574 options::OPT_fno_openmp, false))
577 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
579 if (RTKind == Driver::OMPRT_Unknown)
580 // Already diagnosed.
583 if (ForceStaticHostRuntime)
584 CmdArgs.push_back("-Bstatic");
587 case Driver::OMPRT_OMP:
588 CmdArgs.push_back("-lomp");
590 case Driver::OMPRT_GOMP:
591 CmdArgs.push_back("-lgomp");
593 case Driver::OMPRT_IOMP5:
594 CmdArgs.push_back("-liomp5");
596 case Driver::OMPRT_Unknown:
600 if (ForceStaticHostRuntime)
601 CmdArgs.push_back("-Bdynamic");
603 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
604 CmdArgs.push_back("-lrt");
606 if (IsOffloadingHost)
607 CmdArgs.push_back("-lomptarget");
609 addArchSpecificRPath(TC, Args, CmdArgs);
614 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
615 ArgStringList &CmdArgs, StringRef Sanitizer,
616 bool IsShared, bool IsWhole) {
617 // Wrap any static runtimes that must be forced into executable in
619 if (IsWhole) CmdArgs.push_back("--whole-archive");
620 CmdArgs.push_back(TC.getCompilerRTArgString(
621 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
622 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
625 addArchSpecificRPath(TC, Args, CmdArgs);
629 // Tries to use a file with the list of dynamic symbols that need to be exported
630 // from the runtime library. Returns true if the file was found.
631 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
632 ArgStringList &CmdArgs,
633 StringRef Sanitizer) {
634 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
635 // the option, so don't try to pass it.
636 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
638 // Myriad is static linking only. Furthermore, some versions of its
639 // linker have the bug where --export-dynamic overrides -static, so
640 // don't use --export-dynamic on that platform.
641 if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
643 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
644 if (llvm::sys::fs::exists(SanRT + ".syms")) {
645 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
651 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
652 ArgStringList &CmdArgs) {
653 // Fuchsia never needs these. Any sanitizer runtimes with system
654 // dependencies use the `.deplibs` feature instead.
655 if (TC.getTriple().isOSFuchsia())
658 // Force linking against the system libraries sanitizers depends on
659 // (see PR15823 why this is necessary).
660 CmdArgs.push_back("--no-as-needed");
661 // There's no libpthread or librt on RTEMS & Android.
662 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
663 !TC.getTriple().isAndroid()) {
664 CmdArgs.push_back("-lpthread");
665 if (!TC.getTriple().isOSOpenBSD())
666 CmdArgs.push_back("-lrt");
668 CmdArgs.push_back("-lm");
669 // There's no libdl on all OSes.
670 if (!TC.getTriple().isOSFreeBSD() &&
671 !TC.getTriple().isOSNetBSD() &&
672 !TC.getTriple().isOSOpenBSD() &&
673 TC.getTriple().getOS() != llvm::Triple::RTEMS)
674 CmdArgs.push_back("-ldl");
675 // Required for backtrace on some OSes
676 if (TC.getTriple().isOSFreeBSD() ||
677 TC.getTriple().isOSNetBSD())
678 CmdArgs.push_back("-lexecinfo");
682 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
683 SmallVectorImpl<StringRef> &SharedRuntimes,
684 SmallVectorImpl<StringRef> &StaticRuntimes,
685 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
686 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
687 SmallVectorImpl<StringRef> &RequiredSymbols) {
688 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
689 // Collect shared runtimes.
690 if (SanArgs.needsSharedRt()) {
691 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
692 SharedRuntimes.push_back("asan");
693 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
694 HelperStaticRuntimes.push_back("asan-preinit");
696 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
697 if (SanArgs.requiresMinimalRuntime())
698 SharedRuntimes.push_back("ubsan_minimal");
700 SharedRuntimes.push_back("ubsan_standalone");
702 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
703 if (SanArgs.requiresMinimalRuntime())
704 SharedRuntimes.push_back("scudo_minimal");
706 SharedRuntimes.push_back("scudo");
708 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes())
709 SharedRuntimes.push_back("hwasan");
712 // The stats_client library is also statically linked into DSOs.
713 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
714 StaticRuntimes.push_back("stats_client");
716 // Collect static runtimes.
717 if (Args.hasArg(options::OPT_shared)) {
718 // Don't link static runtimes into DSOs.
722 // Each static runtime that has a DSO counterpart above is excluded below,
723 // but runtimes that exist only as static are not affected by needsSharedRt.
725 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
726 StaticRuntimes.push_back("asan");
727 if (SanArgs.linkCXXRuntimes())
728 StaticRuntimes.push_back("asan_cxx");
731 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
732 StaticRuntimes.push_back("hwasan");
733 if (SanArgs.linkCXXRuntimes())
734 StaticRuntimes.push_back("hwasan_cxx");
736 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
737 StaticRuntimes.push_back("dfsan");
738 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
739 StaticRuntimes.push_back("lsan");
740 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
741 StaticRuntimes.push_back("msan");
742 if (SanArgs.linkCXXRuntimes())
743 StaticRuntimes.push_back("msan_cxx");
745 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) {
746 StaticRuntimes.push_back("tsan");
747 if (SanArgs.linkCXXRuntimes())
748 StaticRuntimes.push_back("tsan_cxx");
750 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
751 if (SanArgs.requiresMinimalRuntime()) {
752 StaticRuntimes.push_back("ubsan_minimal");
754 StaticRuntimes.push_back("ubsan_standalone");
755 if (SanArgs.linkCXXRuntimes())
756 StaticRuntimes.push_back("ubsan_standalone_cxx");
759 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
760 NonWholeStaticRuntimes.push_back("safestack");
761 RequiredSymbols.push_back("__safestack_init");
763 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
764 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
765 StaticRuntimes.push_back("cfi");
766 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
767 StaticRuntimes.push_back("cfi_diag");
768 if (SanArgs.linkCXXRuntimes())
769 StaticRuntimes.push_back("ubsan_standalone_cxx");
772 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
773 NonWholeStaticRuntimes.push_back("stats");
774 RequiredSymbols.push_back("__sanitizer_stats_register");
776 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
777 if (SanArgs.requiresMinimalRuntime()) {
778 StaticRuntimes.push_back("scudo_minimal");
779 if (SanArgs.linkCXXRuntimes())
780 StaticRuntimes.push_back("scudo_cxx_minimal");
782 StaticRuntimes.push_back("scudo");
783 if (SanArgs.linkCXXRuntimes())
784 StaticRuntimes.push_back("scudo_cxx");
789 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
790 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
791 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
792 ArgStringList &CmdArgs) {
793 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
794 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
795 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
796 NonWholeStaticRuntimes, HelperStaticRuntimes,
799 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
800 // Inject libfuzzer dependencies.
801 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
802 !Args.hasArg(options::OPT_shared)) {
804 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
805 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
806 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
809 for (auto RT : SharedRuntimes)
810 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
811 for (auto RT : HelperStaticRuntimes)
812 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
813 bool AddExportDynamic = false;
814 for (auto RT : StaticRuntimes) {
815 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
816 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
818 for (auto RT : NonWholeStaticRuntimes) {
819 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
820 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
822 for (auto S : RequiredSymbols) {
823 CmdArgs.push_back("-u");
824 CmdArgs.push_back(Args.MakeArgString(S));
826 // If there is a static runtime with no dynamic list, force all the symbols
827 // to be dynamic to be sure we export sanitizer interface functions.
828 if (AddExportDynamic)
829 CmdArgs.push_back("--export-dynamic");
831 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
832 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
834 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
837 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
838 if (Args.hasArg(options::OPT_shared))
841 if (TC.getXRayArgs().needsXRayRt()) {
842 CmdArgs.push_back("-whole-archive");
843 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
844 for (const auto &Mode : TC.getXRayArgs().modeList())
845 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
846 CmdArgs.push_back("-no-whole-archive");
853 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
854 CmdArgs.push_back("--no-as-needed");
855 CmdArgs.push_back("-lpthread");
856 if (!TC.getTriple().isOSOpenBSD())
857 CmdArgs.push_back("-lrt");
858 CmdArgs.push_back("-lm");
860 if (!TC.getTriple().isOSFreeBSD() &&
861 !TC.getTriple().isOSNetBSD() &&
862 !TC.getTriple().isOSOpenBSD())
863 CmdArgs.push_back("-ldl");
866 bool tools::areOptimizationsEnabled(const ArgList &Args) {
867 // Find the last -O arg and see if it is non-zero.
868 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
869 return !A->getOption().matches(options::OPT_O0);
874 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input,
875 const InputInfo &Output) {
876 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
877 if (StringRef(A->getValue()) == "single")
878 return Args.MakeArgString(Output.getFilename());
880 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
881 if (FinalOutput && Args.hasArg(options::OPT_c)) {
882 SmallString<128> T(FinalOutput->getValue());
883 llvm::sys::path::replace_extension(T, "dwo");
884 return Args.MakeArgString(T);
886 // Use the compilation dir.
888 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
889 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
890 llvm::sys::path::replace_extension(F, "dwo");
892 return Args.MakeArgString(F);
896 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
897 const JobAction &JA, const ArgList &Args,
898 const InputInfo &Output, const char *OutFile) {
899 ArgStringList ExtractArgs;
900 ExtractArgs.push_back("--extract-dwo");
902 ArgStringList StripArgs;
903 StripArgs.push_back("--strip-dwo");
905 // Grabbing the output of the earlier compile step.
906 StripArgs.push_back(Output.getFilename());
907 ExtractArgs.push_back(Output.getFilename());
908 ExtractArgs.push_back(OutFile);
911 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
912 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
914 // First extract the dwo sections.
915 C.addCommand(std::make_unique<Command>(
916 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, ExtractArgs, II));
918 // Then remove them from the original .o file.
919 C.addCommand(std::make_unique<Command>(
920 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II));
923 // Claim options we don't want to warn if they are unused. We do this for
924 // options that build systems might add but are unused when assembling or only
925 // running the preprocessor for example.
926 void tools::claimNoWarnArgs(const ArgList &Args) {
927 // Don't warn about unused -f(no-)?lto. This can happen when we're
928 // preprocessing, precompiling or assembling.
929 Args.ClaimAllArgs(options::OPT_flto_EQ);
930 Args.ClaimAllArgs(options::OPT_flto);
931 Args.ClaimAllArgs(options::OPT_fno_lto);
934 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
935 auto *ProfileUseArg = Args.getLastArg(
936 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
937 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
938 options::OPT_fno_profile_instr_use);
941 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
942 ProfileUseArg = nullptr;
944 return ProfileUseArg;
947 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
948 auto *ProfileSampleUseArg = Args.getLastArg(
949 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
950 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
951 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
953 if (ProfileSampleUseArg &&
954 (ProfileSampleUseArg->getOption().matches(
955 options::OPT_fno_profile_sample_use) ||
956 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
959 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
960 options::OPT_fauto_profile_EQ);
963 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
964 /// smooshes them together with platform defaults, to decide whether
965 /// this compile should be using PIC mode or not. Returns a tuple of
966 /// (RelocationModel, PICLevel, IsPIE).
967 std::tuple<llvm::Reloc::Model, unsigned, bool>
968 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
969 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
970 const llvm::Triple &Triple = ToolChain.getTriple();
972 bool PIE = ToolChain.isPIEDefault();
973 bool PIC = PIE || ToolChain.isPICDefault();
974 // The Darwin/MachO default to use PIC does not apply when using -static.
975 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
977 bool IsPICLevelTwo = PIC;
980 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
982 // Android-specific defaults for PIC/PIE
983 if (Triple.isAndroid()) {
984 switch (Triple.getArch()) {
985 case llvm::Triple::arm:
986 case llvm::Triple::armeb:
987 case llvm::Triple::thumb:
988 case llvm::Triple::thumbeb:
989 case llvm::Triple::aarch64:
990 case llvm::Triple::mips:
991 case llvm::Triple::mipsel:
992 case llvm::Triple::mips64:
993 case llvm::Triple::mips64el:
994 PIC = true; // "-fpic"
997 case llvm::Triple::x86:
998 case llvm::Triple::x86_64:
999 PIC = true; // "-fPIC"
1000 IsPICLevelTwo = true;
1008 // OpenBSD-specific defaults for PIE
1009 if (Triple.isOSOpenBSD()) {
1010 switch (ToolChain.getArch()) {
1011 case llvm::Triple::arm:
1012 case llvm::Triple::aarch64:
1013 case llvm::Triple::mips64:
1014 case llvm::Triple::mips64el:
1015 case llvm::Triple::x86:
1016 case llvm::Triple::x86_64:
1017 IsPICLevelTwo = false; // "-fpie"
1020 case llvm::Triple::ppc:
1021 case llvm::Triple::sparc:
1022 case llvm::Triple::sparcel:
1023 case llvm::Triple::sparcv9:
1024 IsPICLevelTwo = true; // "-fPIE"
1032 // AMDGPU-specific defaults for PIC.
1033 if (Triple.getArch() == llvm::Triple::amdgcn)
1036 // The last argument relating to either PIC or PIE wins, and no
1037 // other argument is used. If the last argument is any flavor of the
1038 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1039 // option implicitly enables PIC at the same level.
1040 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1041 options::OPT_fpic, options::OPT_fno_pic,
1042 options::OPT_fPIE, options::OPT_fno_PIE,
1043 options::OPT_fpie, options::OPT_fno_pie);
1044 if (Triple.isOSWindows() && LastPICArg &&
1046 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1047 options::OPT_fPIE, options::OPT_fpie)) {
1048 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1049 << LastPICArg->getSpelling() << Triple.str();
1050 if (Triple.getArch() == llvm::Triple::x86_64)
1051 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1052 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1055 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1056 // is forced, then neither PIC nor PIE flags will have no effect.
1057 if (!ToolChain.isPICDefaultForced()) {
1059 Option O = LastPICArg->getOption();
1060 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1061 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1062 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1064 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1066 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1069 if (EffectiveTriple.isPS4CPU()) {
1070 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1071 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1072 if (Model != "kernel") {
1074 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1075 << LastPICArg->getSpelling();
1082 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1083 // PIC level would've been set to level 1, force it back to level 2 PIC
1085 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1086 IsPICLevelTwo |= ToolChain.isPICDefault();
1088 // This kernel flags are a trump-card: they will disable PIC/PIE
1089 // generation, independent of the argument order.
1091 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1092 !EffectiveTriple.isWatchOS()))
1095 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1096 // This is a very special mode. It trumps the other modes, almost no one
1097 // uses it, and it isn't even valid on any OS but Darwin.
1098 if (!Triple.isOSDarwin())
1099 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1100 << A->getSpelling() << Triple.str();
1102 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1104 // Only a forced PIC mode can cause the actual compile to have PIC defines
1105 // etc., no flags are sufficient. This behavior was selected to closely
1106 // match that of llvm-gcc and Apple GCC before that.
1107 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1109 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1112 bool EmbeddedPISupported;
1113 switch (Triple.getArch()) {
1114 case llvm::Triple::arm:
1115 case llvm::Triple::armeb:
1116 case llvm::Triple::thumb:
1117 case llvm::Triple::thumbeb:
1118 EmbeddedPISupported = true;
1121 EmbeddedPISupported = false;
1125 bool ROPI = false, RWPI = false;
1126 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1127 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1128 if (!EmbeddedPISupported)
1129 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1130 << LastROPIArg->getSpelling() << Triple.str();
1133 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1134 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1135 if (!EmbeddedPISupported)
1136 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1137 << LastRWPIArg->getSpelling() << Triple.str();
1141 // ROPI and RWPI are not compatible with PIC or PIE.
1142 if ((ROPI || RWPI) && (PIC || PIE))
1143 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1145 if (Triple.isMIPS()) {
1148 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1149 // When targeting the N64 ABI, PIC is the default, except in the case
1150 // when the -mno-abicalls option is used. In that case we exit
1151 // at next check regardless of PIC being set below.
1152 if (ABIName == "n64")
1154 // When targettng MIPS with -mno-abicalls, it's always static.
1155 if(Args.hasArg(options::OPT_mno_abicalls))
1156 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1157 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1158 // does not use PIC level 2 for historical reasons.
1159 IsPICLevelTwo = false;
1163 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1165 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1167 RelocM = llvm::Reloc::ROPI_RWPI;
1169 RelocM = llvm::Reloc::ROPI;
1171 RelocM = llvm::Reloc::RWPI;
1173 return std::make_tuple(RelocM, 0U, false);
1176 // `-falign-functions` indicates that the functions should be aligned to a
1177 // 16-byte boundary.
1179 // `-falign-functions=1` is the same as `-fno-align-functions`.
1181 // The scalar `n` in `-falign-functions=n` must be an integral value between
1182 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1183 // the nearest power-of-two.
1185 // If we return `0`, the frontend will default to the backend's preferred
1188 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1189 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1190 // alignment. For unaligned functions, we default to the backend's preferred
1192 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1193 const ArgList &Args) {
1194 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1195 options::OPT_falign_functions_EQ,
1196 options::OPT_fno_align_functions);
1197 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1200 if (A->getOption().matches(options::OPT_falign_functions))
1204 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1205 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1206 << A->getAsString(Args) << A->getValue();
1207 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1210 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1211 const ArgList &Args) {
1212 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1218 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1220 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1221 << A->getAsString(Args) << A->getValue();
1225 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1226 ArgStringList &CmdArgs) {
1227 llvm::Reloc::Model RelocationModel;
1230 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1232 if (RelocationModel != llvm::Reloc::Static)
1233 CmdArgs.push_back("-KPIC");
1236 /// Determine whether Objective-C automated reference counting is
1238 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1239 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1242 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1244 static LibGccType getLibGccType(const Driver &D, const ArgList &Args) {
1245 if (Args.hasArg(options::OPT_static_libgcc) ||
1246 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
1247 return LibGccType::StaticLibGcc;
1248 if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX())
1249 return LibGccType::SharedLibGcc;
1250 return LibGccType::UnspecifiedLibGcc;
1253 // Gcc adds libgcc arguments in various ways:
1255 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1256 // g++ <none>: -lgcc_s -lgcc
1257 // gcc shared: -lgcc_s -lgcc
1258 // g++ shared: -lgcc_s -lgcc
1259 // gcc static: -lgcc -lgcc_eh
1260 // g++ static: -lgcc -lgcc_eh
1261 // gcc static-pie: -lgcc -lgcc_eh
1262 // g++ static-pie: -lgcc -lgcc_eh
1264 // Also, certain targets need additional adjustments.
1266 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1267 ArgStringList &CmdArgs, const ArgList &Args) {
1268 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1269 // Targets that don't use unwind libraries.
1270 if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() ||
1271 TC.getTriple().isOSBinFormatWasm() ||
1272 UNW == ToolChain::UNW_None)
1275 LibGccType LGT = getLibGccType(D, Args);
1276 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1277 !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
1279 CmdArgs.push_back("--as-needed");
1282 case ToolChain::UNW_None:
1284 case ToolChain::UNW_Libgcc: {
1285 if (LGT == LibGccType::StaticLibGcc)
1286 CmdArgs.push_back("-lgcc_eh");
1288 CmdArgs.push_back("-lgcc_s");
1291 case ToolChain::UNW_CompilerRT:
1292 if (LGT == LibGccType::StaticLibGcc)
1293 CmdArgs.push_back("-l:libunwind.a");
1294 else if (TC.getTriple().isOSCygMing()) {
1295 if (LGT == LibGccType::SharedLibGcc)
1296 CmdArgs.push_back("-l:libunwind.dll.a");
1298 // Let the linker choose between libunwind.dll.a and libunwind.a
1299 // depending on what's available, and depending on the -static flag
1300 CmdArgs.push_back("-lunwind");
1302 CmdArgs.push_back("-l:libunwind.so");
1307 CmdArgs.push_back("--no-as-needed");
1310 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1311 ArgStringList &CmdArgs, const ArgList &Args) {
1312 LibGccType LGT = getLibGccType(D, Args);
1313 if (LGT != LibGccType::SharedLibGcc)
1314 CmdArgs.push_back("-lgcc");
1315 AddUnwindLibrary(TC, D, CmdArgs, Args);
1316 if (LGT == LibGccType::SharedLibGcc)
1317 CmdArgs.push_back("-lgcc");
1319 // According to Android ABI, we have to link with libdl if we are
1320 // linking with non-static libgcc.
1322 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1323 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1324 if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc)
1325 CmdArgs.push_back("-ldl");
1328 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1329 ArgStringList &CmdArgs, const ArgList &Args) {
1330 // Make use of compiler-rt if --rtlib option is used
1331 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1334 case ToolChain::RLT_CompilerRT:
1335 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1336 AddUnwindLibrary(TC, D, CmdArgs, Args);
1338 case ToolChain::RLT_Libgcc:
1339 // Make sure libgcc is not used under MSVC environment by default
1340 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1341 // Issue error diagnostic if libgcc is explicitly specified
1342 // through command line as --rtlib option argument.
1343 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1344 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1345 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1348 AddLibgcc(TC, D, CmdArgs, Args);
1353 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1354 const InputInfo &Output,
1355 const InputInfo &Input,
1357 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1361 StringRef SaveStats = A->getValue();
1362 SmallString<128> StatsFile;
1363 if (SaveStats == "obj" && Output.isFilename()) {
1364 StatsFile.assign(Output.getFilename());
1365 llvm::sys::path::remove_filename(StatsFile);
1366 } else if (SaveStats != "cwd") {
1367 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1371 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1372 llvm::sys::path::append(StatsFile, BaseName);
1373 llvm::sys::path::replace_extension(StatsFile, "stats");
1377 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1378 Multilib::flags_list &Flags) {
1379 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1382 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1383 ArgStringList &CmdArgs, bool IsLTO) {
1384 auto addArg = [&, IsLTO](const Twine &Arg) {
1386 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1388 CmdArgs.push_back("-mllvm");
1389 CmdArgs.push_back(Args.MakeArgString(Arg));
1393 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1394 addArg(Twine("-x86-branches-within-32B-boundaries"));
1396 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1397 StringRef Value = A->getValue();
1399 if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1400 !llvm::isPowerOf2_64(Boundary)) {
1401 D.Diag(diag::err_drv_invalid_argument_to_option)
1402 << Value << A->getOption().getName();
1404 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1407 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1408 std::string AlignBranch;
1409 for (StringRef T : A->getValues()) {
1410 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1411 T != "ret" && T != "indirect")
1412 D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1413 << T << "fused, jcc, jmp, call, ret, indirect";
1414 if (!AlignBranch.empty())
1418 addArg("-x86-align-branch=" + Twine(AlignBranch));
1420 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1421 StringRef Value = A->getValue();
1422 unsigned PrefixSize;
1423 if (Value.getAsInteger(10, PrefixSize)) {
1424 D.Diag(diag::err_drv_invalid_argument_to_option)
1425 << Value << A->getOption().getName();
1427 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));