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