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