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 Crel = false;
1147 for (const Arg *A : Args.filtered(options::OPT_Wa_COMMA)) {
1148 for (StringRef V : A->getValues()) {
1149 if (V == "--crel")
1150 Crel = true;
1151 else if (V == "--no-crel")
1152 Crel = false;
1153 else
1154 continue;
1155 A->claim();
1156 }
1157 }
1158 if (Crel) {
1159 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
1160 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "-crel"));
1161 } else {
1162 D.Diag(diag::err_drv_unsupported_opt_for_target)
1163 << "-Wa,--crel" << D.getTargetTriple();
1164 }
1165 }
1166}
1167
1169 const ArgList &Args,
1170 ArgStringList &CmdArgs) {
1171 // Default to clang lib / lib64 folder, i.e. the same location as device
1172 // runtime.
1173 SmallString<256> DefaultLibPath =
1174 llvm::sys::path::parent_path(TC.getDriver().Dir);
1175 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
1176 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1177}
1178
1179void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
1180 ArgStringList &CmdArgs) {
1181 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
1182 options::OPT_fno_rtlib_add_rpath, false))
1183 return;
1184
1186 if (const auto CandidateRPath = TC.getStdlibPath())
1187 CandidateRPaths.emplace_back(*CandidateRPath);
1188
1189 for (const auto &CandidateRPath : CandidateRPaths) {
1190 if (TC.getVFS().exists(CandidateRPath)) {
1191 CmdArgs.push_back("-rpath");
1192 CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
1193 }
1194 }
1195}
1196
1197bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs,
1198 const ToolChain &TC, const ArgList &Args,
1199 bool ForceStaticHostRuntime, bool IsOffloadingHost,
1200 bool GompNeedsRT) {
1201 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1202 options::OPT_fno_openmp, false)) {
1203 // We need libomptarget (liboffload) if it's the choosen offloading runtime.
1204 if (Args.hasFlag(options::OPT_foffload_via_llvm,
1205 options::OPT_fno_offload_via_llvm, false))
1206 CmdArgs.push_back("-lomptarget");
1207 return false;
1208 }
1209
1211
1212 if (RTKind == Driver::OMPRT_Unknown)
1213 // Already diagnosed.
1214 return false;
1215
1216 if (ForceStaticHostRuntime)
1217 CmdArgs.push_back("-Bstatic");
1218
1219 switch (RTKind) {
1220 case Driver::OMPRT_OMP:
1221 CmdArgs.push_back("-lomp");
1222 break;
1223 case Driver::OMPRT_GOMP:
1224 CmdArgs.push_back("-lgomp");
1225 break;
1227 CmdArgs.push_back("-liomp5");
1228 break;
1230 break;
1231 }
1232
1233 if (ForceStaticHostRuntime)
1234 CmdArgs.push_back("-Bdynamic");
1235
1236 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
1237 CmdArgs.push_back("-lrt");
1238
1239 if (IsOffloadingHost)
1240 CmdArgs.push_back("-lomptarget");
1241
1242 if (IsOffloadingHost && !Args.hasArg(options::OPT_nogpulib))
1243 CmdArgs.push_back("-lomptarget.devicertl");
1244
1245 addArchSpecificRPath(TC, Args, CmdArgs);
1246
1247 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
1248
1249 return true;
1250}
1251
1253 const JobAction &JA,
1254 const llvm::opt::ArgList &Args,
1255 llvm::opt::ArgStringList &CmdArgs) {
1257 return;
1258
1259 // For all the host OpenMP offloading compile jobs we need to pass the targets
1260 // information using -fopenmp-targets= option.
1261 constexpr llvm::StringLiteral Targets("-fopenmp-targets=");
1262
1264 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
1265 std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
1266 [](auto TC) { return TC.second->getTripleString(); });
1267 CmdArgs.push_back(
1268 Args.MakeArgString(Twine(Targets) + llvm::join(Triples, ",")));
1269}
1270
1271/// Add Fortran runtime libs
1272void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args,
1273 llvm::opt::ArgStringList &CmdArgs) {
1274 // Link FortranRuntime and FortranDecimal
1275 // These are handled earlier on Windows by telling the frontend driver to
1276 // add the correct libraries to link against as dependents in the object
1277 // file.
1278 if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1279 StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary();
1280 F128LibName.consume_front_insensitive("lib");
1281 if (!F128LibName.empty()) {
1282 bool AsNeeded = !TC.getTriple().isOSAIX();
1283 CmdArgs.push_back("-lFortranFloat128Math");
1284 if (AsNeeded)
1285 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
1286 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
1287 if (AsNeeded)
1288 addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
1289 }
1290 CmdArgs.push_back("-lFortranRuntime");
1291 CmdArgs.push_back("-lFortranDecimal");
1292 }
1293}
1294
1296 const llvm::opt::ArgList &Args,
1297 ArgStringList &CmdArgs) {
1298 // Default to the <driver-path>/../lib directory. This works fine on the
1299 // platforms that we have tested so far. We will probably have to re-fine
1300 // this in the future. In particular, on some platforms, we may need to use
1301 // lib64 instead of lib.
1302 SmallString<256> DefaultLibPath =
1303 llvm::sys::path::parent_path(TC.getDriver().Dir);
1304 llvm::sys::path::append(DefaultLibPath, "lib");
1305 if (TC.getTriple().isKnownWindowsMSVCEnvironment())
1306 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
1307 else
1308 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
1309}
1310
1311static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
1312 ArgStringList &CmdArgs, StringRef Sanitizer,
1313 bool IsShared, bool IsWhole) {
1314 // Wrap any static runtimes that must be forced into executable in
1315 // whole-archive.
1316 if (IsWhole) CmdArgs.push_back("--whole-archive");
1317 CmdArgs.push_back(TC.getCompilerRTArgString(
1318 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
1319 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
1320
1321 if (IsShared) {
1322 addArchSpecificRPath(TC, Args, CmdArgs);
1323 }
1324}
1325
1326// Tries to use a file with the list of dynamic symbols that need to be exported
1327// from the runtime library. Returns true if the file was found.
1328static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
1329 ArgStringList &CmdArgs,
1330 StringRef Sanitizer) {
1331 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1332
1333 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
1334 // the option, so don't try to pass it.
1335 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd)
1336 return true;
1337 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
1338 if (llvm::sys::fs::exists(SanRT + ".syms")) {
1339 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
1340 return true;
1341 }
1342 return false;
1343}
1344
1346 const llvm::opt::ArgList &Args,
1347 llvm::opt::ArgStringList &CmdArgs,
1348 bool as_needed) {
1349 assert(!TC.getTriple().isOSAIX() &&
1350 "AIX linker does not support any form of --as-needed option yet.");
1351 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1352
1353 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
1354 // for the native forms -z ignore/-z record, they are missing in Illumos,
1355 // so always use the native form.
1356 // GNU ld doesn't support -z ignore/-z record, so don't use them even on
1357 // Solaris.
1358 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) {
1359 CmdArgs.push_back("-z");
1360 CmdArgs.push_back(as_needed ? "ignore" : "record");
1361 } else {
1362 CmdArgs.push_back(as_needed ? "--as-needed" : "--no-as-needed");
1363 }
1364}
1365
1367 const llvm::opt::ArgList &Args,
1368 ArgStringList &CmdArgs) {
1369 // Force linking against the system libraries sanitizers depends on
1370 // (see PR15823 why this is necessary).
1371 addAsNeededOption(TC, Args, CmdArgs, false);
1372 // There's no libpthread or librt on RTEMS & Android.
1373 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
1374 !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) {
1375 CmdArgs.push_back("-lpthread");
1376 if (!TC.getTriple().isOSOpenBSD())
1377 CmdArgs.push_back("-lrt");
1378 }
1379 CmdArgs.push_back("-lm");
1380 // There's no libdl on all OSes.
1381 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
1382 !TC.getTriple().isOSOpenBSD() &&
1383 TC.getTriple().getOS() != llvm::Triple::RTEMS)
1384 CmdArgs.push_back("-ldl");
1385 // Required for backtrace on some OSes
1386 if (TC.getTriple().isOSFreeBSD() ||
1387 TC.getTriple().isOSNetBSD() ||
1388 TC.getTriple().isOSOpenBSD())
1389 CmdArgs.push_back("-lexecinfo");
1390 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
1391 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
1392 // requirement.
1393 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
1394 !TC.getTriple().isMusl())
1395 CmdArgs.push_back("-lresolv");
1396}
1397
1398static void
1399collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1400 SmallVectorImpl<StringRef> &SharedRuntimes,
1401 SmallVectorImpl<StringRef> &StaticRuntimes,
1402 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
1403 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
1404 SmallVectorImpl<StringRef> &RequiredSymbols) {
1405 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1406 // Collect shared runtimes.
1407 if (SanArgs.needsSharedRt()) {
1408 if (SanArgs.needsAsanRt()) {
1409 SharedRuntimes.push_back("asan");
1410 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1411 HelperStaticRuntimes.push_back("asan-preinit");
1412 }
1413 if (SanArgs.needsMemProfRt()) {
1414 SharedRuntimes.push_back("memprof");
1415 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1416 HelperStaticRuntimes.push_back("memprof-preinit");
1417 }
1418 if (SanArgs.needsNsanRt())
1419 SharedRuntimes.push_back("nsan");
1420 if (SanArgs.needsUbsanRt()) {
1421 if (SanArgs.requiresMinimalRuntime())
1422 SharedRuntimes.push_back("ubsan_minimal");
1423 else
1424 SharedRuntimes.push_back("ubsan_standalone");
1425 }
1426 if (SanArgs.needsScudoRt()) {
1427 SharedRuntimes.push_back("scudo_standalone");
1428 }
1429 if (SanArgs.needsTsanRt())
1430 SharedRuntimes.push_back("tsan");
1431 if (SanArgs.needsHwasanRt()) {
1432 if (SanArgs.needsHwasanAliasesRt())
1433 SharedRuntimes.push_back("hwasan_aliases");
1434 else
1435 SharedRuntimes.push_back("hwasan");
1436 if (!Args.hasArg(options::OPT_shared))
1437 HelperStaticRuntimes.push_back("hwasan-preinit");
1438 }
1439 }
1440
1441 // The stats_client library is also statically linked into DSOs.
1442 if (SanArgs.needsStatsRt())
1443 StaticRuntimes.push_back("stats_client");
1444
1445 // Always link the static runtime regardless of DSO or executable.
1446 if (SanArgs.needsAsanRt())
1447 HelperStaticRuntimes.push_back("asan_static");
1448
1449 // Collect static runtimes.
1450 if (Args.hasArg(options::OPT_shared)) {
1451 // Don't link static runtimes into DSOs.
1452 return;
1453 }
1454
1455 // Each static runtime that has a DSO counterpart above is excluded below,
1456 // but runtimes that exist only as static are not affected by needsSharedRt.
1457
1458 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) {
1459 StaticRuntimes.push_back("asan");
1460 if (SanArgs.linkCXXRuntimes())
1461 StaticRuntimes.push_back("asan_cxx");
1462 }
1463
1464 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) {
1465 StaticRuntimes.push_back("memprof");
1466 if (SanArgs.linkCXXRuntimes())
1467 StaticRuntimes.push_back("memprof_cxx");
1468 }
1469
1470 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) {
1471 if (SanArgs.needsHwasanAliasesRt()) {
1472 StaticRuntimes.push_back("hwasan_aliases");
1473 if (SanArgs.linkCXXRuntimes())
1474 StaticRuntimes.push_back("hwasan_aliases_cxx");
1475 } else {
1476 StaticRuntimes.push_back("hwasan");
1477 if (SanArgs.linkCXXRuntimes())
1478 StaticRuntimes.push_back("hwasan_cxx");
1479 }
1480 }
1481 if (SanArgs.needsDfsanRt())
1482 StaticRuntimes.push_back("dfsan");
1483 if (SanArgs.needsLsanRt())
1484 StaticRuntimes.push_back("lsan");
1485 if (SanArgs.needsMsanRt()) {
1486 StaticRuntimes.push_back("msan");
1487 if (SanArgs.linkCXXRuntimes())
1488 StaticRuntimes.push_back("msan_cxx");
1489 }
1490 if (!SanArgs.needsSharedRt() && SanArgs.needsNsanRt())
1491 StaticRuntimes.push_back("nsan");
1492 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
1493 StaticRuntimes.push_back("tsan");
1494 if (SanArgs.linkCXXRuntimes())
1495 StaticRuntimes.push_back("tsan_cxx");
1496 }
1497 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) {
1498 if (SanArgs.requiresMinimalRuntime()) {
1499 StaticRuntimes.push_back("ubsan_minimal");
1500 } else {
1501 StaticRuntimes.push_back("ubsan_standalone");
1502 if (SanArgs.linkCXXRuntimes())
1503 StaticRuntimes.push_back("ubsan_standalone_cxx");
1504 }
1505 }
1506 if (SanArgs.needsSafeStackRt()) {
1507 NonWholeStaticRuntimes.push_back("safestack");
1508 RequiredSymbols.push_back("__safestack_init");
1509 }
1510 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) {
1511 if (SanArgs.needsCfiRt())
1512 StaticRuntimes.push_back("cfi");
1513 if (SanArgs.needsCfiDiagRt()) {
1514 StaticRuntimes.push_back("cfi_diag");
1515 if (SanArgs.linkCXXRuntimes())
1516 StaticRuntimes.push_back("ubsan_standalone_cxx");
1517 }
1518 }
1519 if (SanArgs.needsStatsRt()) {
1520 NonWholeStaticRuntimes.push_back("stats");
1521 RequiredSymbols.push_back("__sanitizer_stats_register");
1522 }
1523 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) {
1524 StaticRuntimes.push_back("scudo_standalone");
1525 if (SanArgs.linkCXXRuntimes())
1526 StaticRuntimes.push_back("scudo_standalone_cxx");
1527 }
1528}
1529
1530// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1531// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
1532bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1533 ArgStringList &CmdArgs) {
1534 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1535 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1536 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1537 if (SanArgs.linkRuntimes()) {
1538 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1539 NonWholeStaticRuntimes, HelperStaticRuntimes,
1540 RequiredSymbols);
1541 }
1542
1543 // -u options must be added before the runtime libs that resolve them.
1544 for (auto S : RequiredSymbols) {
1545 CmdArgs.push_back("-u");
1546 CmdArgs.push_back(Args.MakeArgString(S));
1547 }
1548
1549 // Inject libfuzzer dependencies.
1550 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1551 !Args.hasArg(options::OPT_shared)) {
1552
1553 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1554 if (SanArgs.needsFuzzerInterceptors())
1555 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1556 true);
1557 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1558 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1559 !Args.hasArg(options::OPT_static);
1560 if (OnlyLibstdcxxStatic)
1561 CmdArgs.push_back("-Bstatic");
1562 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1563 if (OnlyLibstdcxxStatic)
1564 CmdArgs.push_back("-Bdynamic");
1565 }
1566 }
1567
1568 for (auto RT : SharedRuntimes)
1569 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1570 for (auto RT : HelperStaticRuntimes)
1571 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1572 bool AddExportDynamic = false;
1573 for (auto RT : StaticRuntimes) {
1574 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1575 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1576 }
1577 for (auto RT : NonWholeStaticRuntimes) {
1578 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1579 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1580 }
1581 // If there is a static runtime with no dynamic list, force all the symbols
1582 // to be dynamic to be sure we export sanitizer interface functions.
1583 if (AddExportDynamic)
1584 CmdArgs.push_back("--export-dynamic");
1585
1586 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1587 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1588
1589 if (SanArgs.hasMemTag()) {
1590 if (!TC.getTriple().isAndroid()) {
1591 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1592 << "-fsanitize=memtag*" << TC.getTriple().str();
1593 }
1594 CmdArgs.push_back(
1595 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1596 if (SanArgs.hasMemtagHeap())
1597 CmdArgs.push_back("--android-memtag-heap");
1598 if (SanArgs.hasMemtagStack())
1599 CmdArgs.push_back("--android-memtag-stack");
1600 }
1601
1602 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1603}
1604
1605bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1606 if (Args.hasArg(options::OPT_shared))
1607 return false;
1608
1609 if (TC.getXRayArgs().needsXRayRt()) {
1610 CmdArgs.push_back("--whole-archive");
1611 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1612 for (const auto &Mode : TC.getXRayArgs().modeList())
1613 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1614 CmdArgs.push_back("--no-whole-archive");
1615 return true;
1616 }
1617
1618 return false;
1619}
1620
1622 const llvm::opt::ArgList &Args,
1623 ArgStringList &CmdArgs) {
1624 addAsNeededOption(TC, Args, CmdArgs, false);
1625 CmdArgs.push_back("-lpthread");
1626 if (!TC.getTriple().isOSOpenBSD())
1627 CmdArgs.push_back("-lrt");
1628 CmdArgs.push_back("-lm");
1629
1630 if (!TC.getTriple().isOSFreeBSD() &&
1631 !TC.getTriple().isOSNetBSD() &&
1632 !TC.getTriple().isOSOpenBSD())
1633 CmdArgs.push_back("-ldl");
1634}
1635
1636bool tools::areOptimizationsEnabled(const ArgList &Args) {
1637 // Find the last -O arg and see if it is non-zero.
1638 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1639 return !A->getOption().matches(options::OPT_O0);
1640 // Defaults to -O0.
1641 return false;
1642}
1643
1644const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1645 const InputInfo &Input,
1646 const InputInfo &Output) {
1647 auto AddPostfix = [JA](auto &F) {
1649 F += (Twine("_") + JA.getOffloadingArch()).str();
1650 F += ".dwo";
1651 };
1652 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1653 if (StringRef(A->getValue()) == "single" && Output.isFilename())
1654 return Args.MakeArgString(Output.getFilename());
1655
1657 if (const Arg *A = Args.getLastArg(options::OPT_dumpdir)) {
1658 T = A->getValue();
1659 } else {
1660 Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o);
1661 if (FinalOutput && Args.hasArg(options::OPT_c)) {
1662 T = FinalOutput->getValue();
1663 llvm::sys::path::remove_filename(T);
1664 llvm::sys::path::append(T,
1665 llvm::sys::path::stem(FinalOutput->getValue()));
1666 AddPostfix(T);
1667 return Args.MakeArgString(T);
1668 }
1669 }
1670
1671 T += llvm::sys::path::stem(Input.getBaseInput());
1672 AddPostfix(T);
1673 return Args.MakeArgString(T);
1674}
1675
1676void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1677 const JobAction &JA, const ArgList &Args,
1678 const InputInfo &Output, const char *OutFile) {
1679 ArgStringList ExtractArgs;
1680 ExtractArgs.push_back("--extract-dwo");
1681
1682 ArgStringList StripArgs;
1683 StripArgs.push_back("--strip-dwo");
1684
1685 // Grabbing the output of the earlier compile step.
1686 StripArgs.push_back(Output.getFilename());
1687 ExtractArgs.push_back(Output.getFilename());
1688 ExtractArgs.push_back(OutFile);
1689
1690 const char *Exec =
1691 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1692 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1693
1694 // First extract the dwo sections.
1695 C.addCommand(std::make_unique<Command>(JA, T,
1697 Exec, ExtractArgs, II, Output));
1698
1699 // Then remove them from the original .o file.
1700 C.addCommand(std::make_unique<Command>(
1701 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1702}
1703
1704// Claim options we don't want to warn if they are unused. We do this for
1705// options that build systems might add but are unused when assembling or only
1706// running the preprocessor for example.
1707void tools::claimNoWarnArgs(const ArgList &Args) {
1708 // Don't warn about unused -f(no-)?lto. This can happen when we're
1709 // preprocessing, precompiling or assembling.
1710 Args.ClaimAllArgs(options::OPT_flto_EQ);
1711 Args.ClaimAllArgs(options::OPT_flto);
1712 Args.ClaimAllArgs(options::OPT_fno_lto);
1713}
1714
1715Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) {
1716 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
1717 options::OPT_fcs_profile_generate_EQ,
1718 options::OPT_fno_profile_generate);
1719 if (CSPGOGenerateArg &&
1720 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
1721 CSPGOGenerateArg = nullptr;
1722
1723 return CSPGOGenerateArg;
1724}
1725
1726Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1727 auto *ProfileUseArg = Args.getLastArg(
1728 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1729 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1730 options::OPT_fno_profile_instr_use);
1731
1732 if (ProfileUseArg &&
1733 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1734 ProfileUseArg = nullptr;
1735
1736 return ProfileUseArg;
1737}
1738
1739Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1740 auto *ProfileSampleUseArg = Args.getLastArg(
1741 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1742 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1743 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1744
1745 if (ProfileSampleUseArg &&
1746 (ProfileSampleUseArg->getOption().matches(
1747 options::OPT_fno_profile_sample_use) ||
1748 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1749 return nullptr;
1750
1751 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1752 options::OPT_fauto_profile_EQ);
1753}
1754
1755const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
1756 switch (Model) {
1757 case llvm::Reloc::Static:
1758 return "static";
1759 case llvm::Reloc::PIC_:
1760 return "pic";
1761 case llvm::Reloc::DynamicNoPIC:
1762 return "dynamic-no-pic";
1763 case llvm::Reloc::ROPI:
1764 return "ropi";
1765 case llvm::Reloc::RWPI:
1766 return "rwpi";
1767 case llvm::Reloc::ROPI_RWPI:
1768 return "ropi-rwpi";
1769 }
1770 llvm_unreachable("Unknown Reloc::Model kind");
1771}
1772
1773/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
1774/// smooshes them together with platform defaults, to decide whether
1775/// this compile should be using PIC mode or not. Returns a tuple of
1776/// (RelocationModel, PICLevel, IsPIE).
1777std::tuple<llvm::Reloc::Model, unsigned, bool>
1778tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1779 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1780 const llvm::Triple &Triple = ToolChain.getTriple();
1781
1782 bool PIE = ToolChain.isPIEDefault(Args);
1783 bool PIC = PIE || ToolChain.isPICDefault();
1784 // The Darwin/MachO default to use PIC does not apply when using -static.
1785 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1786 PIE = PIC = false;
1787 bool IsPICLevelTwo = PIC;
1788
1789 bool KernelOrKext =
1790 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1791
1792 // Android-specific defaults for PIC/PIE
1793 if (Triple.isAndroid()) {
1794 switch (Triple.getArch()) {
1795 case llvm::Triple::arm:
1796 case llvm::Triple::armeb:
1797 case llvm::Triple::thumb:
1798 case llvm::Triple::thumbeb:
1799 case llvm::Triple::aarch64:
1800 case llvm::Triple::mips:
1801 case llvm::Triple::mipsel:
1802 case llvm::Triple::mips64:
1803 case llvm::Triple::mips64el:
1804 PIC = true; // "-fpic"
1805 break;
1806
1807 case llvm::Triple::x86:
1808 case llvm::Triple::x86_64:
1809 PIC = true; // "-fPIC"
1810 IsPICLevelTwo = true;
1811 break;
1812
1813 default:
1814 break;
1815 }
1816 }
1817
1818 // OHOS-specific defaults for PIC/PIE
1819 if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64)
1820 PIC = true;
1821
1822 // OpenBSD-specific defaults for PIE
1823 if (Triple.isOSOpenBSD()) {
1824 switch (ToolChain.getArch()) {
1825 case llvm::Triple::arm:
1826 case llvm::Triple::aarch64:
1827 case llvm::Triple::mips64:
1828 case llvm::Triple::mips64el:
1829 case llvm::Triple::x86:
1830 case llvm::Triple::x86_64:
1831 IsPICLevelTwo = false; // "-fpie"
1832 break;
1833
1834 case llvm::Triple::ppc:
1835 case llvm::Triple::sparcv9:
1836 IsPICLevelTwo = true; // "-fPIE"
1837 break;
1838
1839 default:
1840 break;
1841 }
1842 }
1843
1844 // The last argument relating to either PIC or PIE wins, and no
1845 // other argument is used. If the last argument is any flavor of the
1846 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1847 // option implicitly enables PIC at the same level.
1848 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1849 options::OPT_fpic, options::OPT_fno_pic,
1850 options::OPT_fPIE, options::OPT_fno_PIE,
1851 options::OPT_fpie, options::OPT_fno_pie);
1852 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1853 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1854 options::OPT_fPIE, options::OPT_fpie)) {
1855 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1856 << LastPICArg->getSpelling() << Triple.str();
1857 if (Triple.getArch() == llvm::Triple::x86_64)
1858 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1859 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1860 }
1861
1862 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1863 // is forced, then neither PIC nor PIE flags will have no effect.
1865 if (LastPICArg) {
1866 Option O = LastPICArg->getOption();
1867 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1868 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1869 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1870 PIC =
1871 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1872 IsPICLevelTwo =
1873 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1874 } else {
1875 PIE = PIC = false;
1876 if (EffectiveTriple.isPS()) {
1877 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1878 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1879 if (Model != "kernel") {
1880 PIC = true;
1881 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1882 << LastPICArg->getSpelling()
1883 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1884 }
1885 }
1886 }
1887 }
1888 }
1889
1890 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1891 // the PIC level would've been set to level 1, force it back to level 2 PIC
1892 // instead.
1893 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1894 IsPICLevelTwo |= ToolChain.isPICDefault();
1895
1896 // This kernel flags are a trump-card: they will disable PIC/PIE
1897 // generation, independent of the argument order.
1898 if (KernelOrKext &&
1899 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1900 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1901 PIC = PIE = false;
1902
1903 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1904 // This is a very special mode. It trumps the other modes, almost no one
1905 // uses it, and it isn't even valid on any OS but Darwin.
1906 if (!Triple.isOSDarwin())
1907 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1908 << A->getSpelling() << Triple.str();
1909
1910 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1911
1912 // Only a forced PIC mode can cause the actual compile to have PIC defines
1913 // etc., no flags are sufficient. This behavior was selected to closely
1914 // match that of llvm-gcc and Apple GCC before that.
1916
1917 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1918 }
1919
1920 bool EmbeddedPISupported;
1921 switch (Triple.getArch()) {
1922 case llvm::Triple::arm:
1923 case llvm::Triple::armeb:
1924 case llvm::Triple::thumb:
1925 case llvm::Triple::thumbeb:
1926 EmbeddedPISupported = true;
1927 break;
1928 default:
1929 EmbeddedPISupported = false;
1930 break;
1931 }
1932
1933 bool ROPI = false, RWPI = false;
1934 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1935 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1936 if (!EmbeddedPISupported)
1937 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1938 << LastROPIArg->getSpelling() << Triple.str();
1939 ROPI = true;
1940 }
1941 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1942 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1943 if (!EmbeddedPISupported)
1944 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1945 << LastRWPIArg->getSpelling() << Triple.str();
1946 RWPI = true;
1947 }
1948
1949 // ROPI and RWPI are not compatible with PIC or PIE.
1950 if ((ROPI || RWPI) && (PIC || PIE))
1951 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1952
1953 if (Triple.isMIPS()) {
1954 StringRef CPUName;
1955 StringRef ABIName;
1956 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1957 // When targeting the N64 ABI, PIC is the default, except in the case
1958 // when the -mno-abicalls option is used. In that case we exit
1959 // at next check regardless of PIC being set below.
1960 if (ABIName == "n64")
1961 PIC = true;
1962 // When targettng MIPS with -mno-abicalls, it's always static.
1963 if(Args.hasArg(options::OPT_mno_abicalls))
1964 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1965 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1966 // does not use PIC level 2 for historical reasons.
1967 IsPICLevelTwo = false;
1968 }
1969
1970 if (PIC)
1971 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1972
1973 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1974 if (ROPI && RWPI)
1975 RelocM = llvm::Reloc::ROPI_RWPI;
1976 else if (ROPI)
1977 RelocM = llvm::Reloc::ROPI;
1978 else if (RWPI)
1979 RelocM = llvm::Reloc::RWPI;
1980
1981 return std::make_tuple(RelocM, 0U, false);
1982}
1983
1984// `-falign-functions` indicates that the functions should be aligned to the
1985// backend's preferred alignment.
1986//
1987// `-falign-functions=1` is the same as `-fno-align-functions`.
1988//
1989// The scalar `n` in `-falign-functions=n` must be an integral value between
1990// [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1991// the nearest power-of-two.
1992//
1993// If we return `0`, the frontend will default to the backend's preferred
1994// alignment.
1995//
1996// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1997// to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1998// alignment. For unaligned functions, we default to the backend's preferred
1999// alignment.
2000unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
2001 const ArgList &Args) {
2002 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
2003 options::OPT_falign_functions_EQ,
2004 options::OPT_fno_align_functions);
2005 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
2006 return 0;
2007
2008 if (A->getOption().matches(options::OPT_falign_functions))
2009 return 0;
2010
2011 unsigned Value = 0;
2012 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
2013 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2014 << A->getAsString(Args) << A->getValue();
2015 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
2016}
2017
2019 ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
2020 switch (DebugInfoKind) {
2021 case llvm::codegenoptions::DebugDirectivesOnly:
2022 CmdArgs.push_back("-debug-info-kind=line-directives-only");
2023 break;
2024 case llvm::codegenoptions::DebugLineTablesOnly:
2025 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2026 break;
2027 case llvm::codegenoptions::DebugInfoConstructor:
2028 CmdArgs.push_back("-debug-info-kind=constructor");
2029 break;
2030 case llvm::codegenoptions::LimitedDebugInfo:
2031 CmdArgs.push_back("-debug-info-kind=limited");
2032 break;
2033 case llvm::codegenoptions::FullDebugInfo:
2034 CmdArgs.push_back("-debug-info-kind=standalone");
2035 break;
2036 case llvm::codegenoptions::UnusedTypeInfo:
2037 CmdArgs.push_back("-debug-info-kind=unused-types");
2038 break;
2039 default:
2040 break;
2041 }
2042}
2043
2044// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2045// to the corresponding DebugInfoKind.
2046llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
2047 assert(A.getOption().matches(options::OPT_gN_Group) &&
2048 "Not a -g option that specifies a debug-info level");
2049 if (A.getOption().matches(options::OPT_g0) ||
2050 A.getOption().matches(options::OPT_ggdb0))
2051 return llvm::codegenoptions::NoDebugInfo;
2052 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2053 A.getOption().matches(options::OPT_ggdb1))
2054 return llvm::codegenoptions::DebugLineTablesOnly;
2055 if (A.getOption().matches(options::OPT_gline_directives_only))
2056 return llvm::codegenoptions::DebugDirectivesOnly;
2057 return llvm::codegenoptions::DebugInfoConstructor;
2058}
2059
2060static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
2061 const ArgList &Args) {
2062 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
2063
2064 if (!A)
2065 return 0;
2066
2067 unsigned Value = 0;
2068 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
2069 Value < 2)
2070 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
2071 << A->getAsString(Args) << A->getValue();
2072 return Value;
2073}
2074
2075unsigned tools::DwarfVersionNum(StringRef ArgValue) {
2076 return llvm::StringSwitch<unsigned>(ArgValue)
2077 .Case("-gdwarf-2", 2)
2078 .Case("-gdwarf-3", 3)
2079 .Case("-gdwarf-4", 4)
2080 .Case("-gdwarf-5", 5)
2081 .Default(0);
2082}
2083
2084const Arg *tools::getDwarfNArg(const ArgList &Args) {
2085 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
2086 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
2087 options::OPT_gdwarf);
2088}
2089
2091 const llvm::opt::ArgList &Args) {
2092 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args);
2093 if (const Arg *GDwarfN = getDwarfNArg(Args))
2094 if (int N = DwarfVersionNum(GDwarfN->getSpelling())) {
2095 DwarfVersion = N;
2096 if (DwarfVersion == 5 && TC.getTriple().isOSAIX())
2097 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
2098 << GDwarfN->getSpelling() << TC.getTriple().str();
2099 }
2100 if (DwarfVersion == 0) {
2101 DwarfVersion = TC.GetDefaultDwarfVersion();
2102 assert(DwarfVersion && "toolchain default DWARF version must be nonzero");
2103 }
2104 return DwarfVersion;
2105}
2106
2107void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
2108 ArgStringList &CmdArgs) {
2109 llvm::Reloc::Model RelocationModel;
2110 unsigned PICLevel;
2111 bool IsPIE;
2112 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
2113
2114 if (RelocationModel != llvm::Reloc::Static)
2115 CmdArgs.push_back("-KPIC");
2116}
2117
2118/// Determine whether Objective-C automated reference counting is
2119/// enabled.
2120bool tools::isObjCAutoRefCount(const ArgList &Args) {
2121 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
2122}
2123
2125
2126static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
2127 const ArgList &Args) {
2128 if (Args.hasArg(options::OPT_static_libgcc) ||
2129 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
2130 // The Android NDK only provides libunwind.a, not libunwind.so.
2131 TC.getTriple().isAndroid())
2133 if (Args.hasArg(options::OPT_shared_libgcc))
2136}
2137
2138// Gcc adds libgcc arguments in various ways:
2139//
2140// gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
2141// g++ <none>: -lgcc_s -lgcc
2142// gcc shared: -lgcc_s -lgcc
2143// g++ shared: -lgcc_s -lgcc
2144// gcc static: -lgcc -lgcc_eh
2145// g++ static: -lgcc -lgcc_eh
2146// gcc static-pie: -lgcc -lgcc_eh
2147// g++ static-pie: -lgcc -lgcc_eh
2148//
2149// Also, certain targets need additional adjustments.
2150
2151static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
2152 ArgStringList &CmdArgs, const ArgList &Args) {
2154 // By default OHOS binaries are linked statically to libunwind.
2155 if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) {
2156 CmdArgs.push_back("-l:libunwind.a");
2157 return;
2158 }
2159
2160 // Targets that don't use unwind libraries.
2161 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
2162 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
2163 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
2164 return;
2165
2166 LibGccType LGT = getLibGccType(TC, D, Args);
2167 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
2168 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
2169 !TC.getTriple().isAndroid() &&
2170 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
2171 if (AsNeeded)
2172 addAsNeededOption(TC, Args, CmdArgs, true);
2173
2174 switch (UNW) {
2176 return;
2177 case ToolChain::UNW_Libgcc: {
2178 if (LGT == LibGccType::StaticLibGcc)
2179 CmdArgs.push_back("-lgcc_eh");
2180 else
2181 CmdArgs.push_back("-lgcc_s");
2182 break;
2183 }
2185 if (TC.getTriple().isOSAIX()) {
2186 // AIX only has libunwind as a shared library. So do not pass
2187 // anything in if -static is specified.
2188 if (LGT != LibGccType::StaticLibGcc)
2189 CmdArgs.push_back("-lunwind");
2190 } else if (LGT == LibGccType::StaticLibGcc) {
2191 CmdArgs.push_back("-l:libunwind.a");
2192 } else if (LGT == LibGccType::SharedLibGcc) {
2193 if (TC.getTriple().isOSCygMing())
2194 CmdArgs.push_back("-l:libunwind.dll.a");
2195 else
2196 CmdArgs.push_back("-l:libunwind.so");
2197 } else {
2198 // Let the linker choose between libunwind.so and libunwind.a
2199 // depending on what's available, and depending on the -static flag
2200 CmdArgs.push_back("-lunwind");
2201 }
2202 break;
2203 }
2204
2205 if (AsNeeded)
2206 addAsNeededOption(TC, Args, CmdArgs, false);
2207}
2208
2209static void AddLibgcc(const ToolChain &TC, const Driver &D,
2210 ArgStringList &CmdArgs, const ArgList &Args) {
2211 LibGccType LGT = getLibGccType(TC, D, Args);
2212 if (LGT == LibGccType::StaticLibGcc ||
2213 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
2214 CmdArgs.push_back("-lgcc");
2215 AddUnwindLibrary(TC, D, CmdArgs, Args);
2216 if (LGT == LibGccType::SharedLibGcc ||
2217 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
2218 CmdArgs.push_back("-lgcc");
2219}
2220
2221void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
2222 ArgStringList &CmdArgs, const ArgList &Args) {
2223 // Make use of compiler-rt if --rtlib option is used
2225
2226 switch (RLT) {
2228 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2229 AddUnwindLibrary(TC, D, CmdArgs, Args);
2230 break;
2232 // Make sure libgcc is not used under MSVC environment by default
2233 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
2234 // Issue error diagnostic if libgcc is explicitly specified
2235 // through command line as --rtlib option argument.
2236 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
2237 if (A && A->getValue() != StringRef("platform")) {
2238 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
2239 << A->getValue() << "MSVC";
2240 }
2241 } else
2242 AddLibgcc(TC, D, CmdArgs, Args);
2243 break;
2244 }
2245
2246 // On Android, the unwinder uses dl_iterate_phdr (or one of
2247 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
2248 // statically-linked executables, these functions come from libc.a instead.
2249 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
2250 !Args.hasArg(options::OPT_static_pie))
2251 CmdArgs.push_back("-ldl");
2252}
2253
2254SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
2255 const InputInfo &Output,
2256 const InputInfo &Input,
2257 const Driver &D) {
2258 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
2259 if (!A && !D.CCPrintInternalStats)
2260 return {};
2261
2262 SmallString<128> StatsFile;
2263 if (A) {
2264 StringRef SaveStats = A->getValue();
2265 if (SaveStats == "obj" && Output.isFilename()) {
2266 StatsFile.assign(Output.getFilename());
2267 llvm::sys::path::remove_filename(StatsFile);
2268 } else if (SaveStats != "cwd") {
2269 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
2270 return {};
2271 }
2272
2273 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
2274 llvm::sys::path::append(StatsFile, BaseName);
2275 llvm::sys::path::replace_extension(StatsFile, "stats");
2276 } else {
2277 assert(D.CCPrintInternalStats);
2278 StatsFile.assign(D.CCPrintInternalStatReportFilename.empty()
2279 ? "-"
2280 : D.CCPrintInternalStatReportFilename);
2281 }
2282 return StatsFile;
2283}
2284
2285void tools::addMultilibFlag(bool Enabled, const StringRef Flag,
2286 Multilib::flags_list &Flags) {
2287 assert(Flag.front() == '-');
2288 if (Enabled) {
2289 Flags.push_back(Flag.str());
2290 } else {
2291 Flags.push_back(("!" + Flag.substr(1)).str());
2292 }
2293}
2294
2295void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
2296 ArgStringList &CmdArgs, bool IsLTO,
2297 const StringRef PluginOptPrefix) {
2298 auto addArg = [&, IsLTO](const Twine &Arg) {
2299 if (IsLTO) {
2300 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2301 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2302 } else {
2303 CmdArgs.push_back("-mllvm");
2304 CmdArgs.push_back(Args.MakeArgString(Arg));
2305 }
2306 };
2307
2308 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
2309 addArg(Twine("-x86-branches-within-32B-boundaries"));
2310 }
2311 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
2312 StringRef Value = A->getValue();
2313 unsigned Boundary;
2314 if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
2315 !llvm::isPowerOf2_64(Boundary)) {
2316 D.Diag(diag::err_drv_invalid_argument_to_option)
2317 << Value << A->getOption().getName();
2318 } else {
2319 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
2320 }
2321 }
2322 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
2323 std::string AlignBranch;
2324 for (StringRef T : A->getValues()) {
2325 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
2326 T != "ret" && T != "indirect")
2327 D.Diag(diag::err_drv_invalid_malign_branch_EQ)
2328 << T << "fused, jcc, jmp, call, ret, indirect";
2329 if (!AlignBranch.empty())
2330 AlignBranch += '+';
2331 AlignBranch += T;
2332 }
2333 addArg("-x86-align-branch=" + Twine(AlignBranch));
2334 }
2335 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
2336 StringRef Value = A->getValue();
2337 unsigned PrefixSize;
2338 if (Value.getAsInteger(10, PrefixSize)) {
2339 D.Diag(diag::err_drv_invalid_argument_to_option)
2340 << Value << A->getOption().getName();
2341 } else {
2342 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
2343 }
2344 }
2345}
2346
2347/// SDLSearch: Search for Static Device Library
2348/// The search for SDL bitcode files is consistent with how static host
2349/// libraries are discovered. That is, the -l option triggers a search for
2350/// files in a set of directories called the LINKPATH. The host library search
2351/// procedure looks for a specific filename in the LINKPATH. The filename for
2352/// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
2353/// ordered-set of filenames that are searched. We call this ordered-set of
2354/// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
2355/// architecture specific, or generic across all architectures, a naming
2356/// convention and search order is used where the file name embeds the
2357/// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
2358/// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
2359/// device-independent SDLs. To reduce congestion in host library directories,
2360/// the search first looks for files in the “libdevice” subdirectory. SDLs that
2361/// are bc files begin with the prefix “lib”.
2362///
2363/// Machine-code SDLs can also be managed as an archive (*.a file). The
2364/// convention has been to use the prefix “lib”. To avoid confusion with host
2365/// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
2366///
2367static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
2368 llvm::opt::ArgStringList &CC1Args,
2369 const SmallVectorImpl<std::string> &LibraryPaths,
2370 StringRef Lib, StringRef Arch, StringRef Target,
2371 bool isBitCodeSDL) {
2373
2374 std::string LibDeviceLoc = "/libdevice";
2375 std::string LibBcPrefix = "/libbc-";
2376 std::string LibPrefix = "/lib";
2377
2378 if (isBitCodeSDL) {
2379 // SEARCH-ORDER for Bitcode SDLs:
2380 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
2381 // libbc-<libname>-<arch-name>-<device-type>.a
2382 // libdevice/libbc-<libname>-<arch-name>.a
2383 // libbc-<libname>-<arch-name>.a
2384 // libdevice/libbc-<libname>.a
2385 // libbc-<libname>.a
2386 // libdevice/lib<libname>-<arch-name>-<device-type>.bc
2387 // lib<libname>-<arch-name>-<device-type>.bc
2388 // libdevice/lib<libname>-<arch-name>.bc
2389 // lib<libname>-<arch-name>.bc
2390 // libdevice/lib<libname>.bc
2391 // lib<libname>.bc
2392
2393 for (StringRef Base : {LibBcPrefix, LibPrefix}) {
2394 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
2395
2396 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2397 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
2398 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
2399 SDLs.push_back(Twine(Base + Suffix + Ext).str());
2400 }
2401 }
2402 } else {
2403 // SEARCH-ORDER for Machine-code SDLs:
2404 // libdevice/lib<libname>-<arch-name>-<device-type>.a
2405 // lib<libname>-<arch-name>-<device-type>.a
2406 // libdevice/lib<libname>-<arch-name>.a
2407 // lib<libname>-<arch-name>.a
2408
2409 const auto *Ext = ".a";
2410
2411 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2412 Twine(Lib + "-" + Arch).str()}) {
2413 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
2414 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
2415 }
2416 }
2417
2418 // The CUDA toolchain does not use a global device llvm-link before the LLVM
2419 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
2420 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
2421 // will link libraries after clang compilation while the LLVM IR is still in
2422 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
2423 // This is a clang -cc1 option that is generated by the clang driver. The
2424 // option value must a full path to an existing file.
2425 bool FoundSDL = false;
2426 for (auto LPath : LibraryPaths) {
2427 for (auto SDL : SDLs) {
2428 auto FullName = Twine(LPath + SDL).str();
2429 if (llvm::sys::fs::exists(FullName)) {
2430 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
2431 FoundSDL = true;
2432 break;
2433 }
2434 }
2435 if (FoundSDL)
2436 break;
2437 }
2438 return FoundSDL;
2439}
2440
2441/// Search if a user provided archive file lib<libname>.a exists in any of
2442/// the library paths. If so, add a new command to clang-offload-bundler to
2443/// unbundle this archive and create a temporary device specific archive. Name
2444/// of this SDL is passed to the llvm-link tool.
2446 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
2447 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
2448 llvm::opt::ArgStringList &CC1Args,
2449 const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib,
2450 StringRef Arch, StringRef Target, bool isBitCodeSDL) {
2451
2452 // We don't support bitcode archive bundles for nvptx
2453 if (isBitCodeSDL && Arch.contains("nvptx"))
2454 return;
2455
2456 bool FoundAOB = false;
2457 std::string ArchiveOfBundles;
2458
2459 llvm::Triple Triple(D.getTargetTriple());
2460 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
2461 auto Ext = IsMSVC ? ".lib" : ".a";
2462 if (!Lib.starts_with(":") && !Lib.starts_with("-l")) {
2463 if (llvm::sys::fs::exists(Lib)) {
2464 ArchiveOfBundles = Lib;
2465 FoundAOB = true;
2466 }
2467 } else {
2468 Lib.consume_front("-l");
2469 for (auto LPath : LibraryPaths) {
2470 ArchiveOfBundles.clear();
2471 auto LibFile = (Lib.starts_with(":") ? Lib.drop_front()
2472 : IsMSVC ? Lib + Ext
2473 : "lib" + Lib + Ext)
2474 .str();
2475 for (auto Prefix : {"/libdevice/", "/"}) {
2476 auto AOB = Twine(LPath + Prefix + LibFile).str();
2477 if (llvm::sys::fs::exists(AOB)) {
2478 ArchiveOfBundles = AOB;
2479 FoundAOB = true;
2480 break;
2481 }
2482 }
2483 if (FoundAOB)
2484 break;
2485 }
2486 }
2487
2488 if (!FoundAOB)
2489 return;
2490
2491 llvm::file_magic Magic;
2492 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic);
2493 if (EC || Magic != llvm::file_magic::archive)
2494 return;
2495
2496 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
2497 std::string OutputLib =
2498 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" +
2499 Arch + "-" + Target)
2500 .str(),
2501 "a");
2502
2503 C.addTempFile(C.getArgs().MakeArgString(OutputLib));
2504
2505 ArgStringList CmdArgs;
2506 SmallString<128> DeviceTriple;
2508 DeviceTriple += '-';
2509 std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
2510 DeviceTriple += NormalizedTriple;
2511 if (!Target.empty()) {
2512 DeviceTriple += '-';
2513 DeviceTriple += Target;
2514 }
2515
2516 std::string UnbundleArg("-unbundle");
2517 std::string TypeArg("-type=a");
2518 std::string InputArg("-input=" + ArchiveOfBundles);
2519 std::string OffloadArg("-targets=" + std::string(DeviceTriple));
2520 std::string OutputArg("-output=" + OutputLib);
2521
2522 const char *UBProgram = DriverArgs.MakeArgString(
2523 T.getToolChain().GetProgramPath("clang-offload-bundler"));
2524
2525 ArgStringList UBArgs;
2526 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
2527 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
2528 UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
2529 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
2530 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
2531
2532 // Add this flag to not exit from clang-offload-bundler if no compatible
2533 // code object is found in heterogenous archive library.
2534 std::string AdditionalArgs("-allow-missing-bundles");
2535 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
2536
2537 // Add this flag to treat hip and hipv4 offload kinds as compatible with
2538 // openmp offload kind while extracting code objects from a heterogenous
2539 // archive library. Vice versa is also considered compatible.
2540 std::string HipCompatibleArgs("-hip-openmp-compatible");
2541 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
2542
2543 C.addCommand(std::make_unique<Command>(
2544 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
2545 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
2546
2547 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
2548
2549 return;
2550}
2551
2552// Wrapper function used by driver for adding SDLs during link phase.
2554 const JobAction &JA,
2555 const InputInfoList &Inputs,
2556 const llvm::opt::ArgList &DriverArgs,
2557 llvm::opt::ArgStringList &CC1Args,
2558 StringRef Arch, StringRef Target,
2559 bool isBitCodeSDL) {
2560 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
2561 Arch, Target, isBitCodeSDL);
2562}
2563
2564// User defined Static Device Libraries(SDLs) can be passed to clang for
2565// offloading GPU compilers. Like static host libraries, the use of a SDL is
2566// specified with the -l command line option. The primary difference between
2567// host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
2568// and SEARCH-ORDER for Machine-code SDLs for the naming convention).
2569// SDLs are of following types:
2570//
2571// * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
2572// For NVPTX, these libraries are post-clang linked following each
2573// compilation. For AMDGPU, these libraries are linked one time
2574// during the application link phase.
2575//
2576// * Machine-code SDLs: They are archive files. For AMDGPU, the process for
2577// machine code SDLs is still in development. But they will be linked
2578// by the LLVM tool lld.
2579//
2580// * Bundled objects that contain both host and device codes: Bundled objects
2581// may also contain library code compiled from source. For NVPTX, the
2582// bundle contains cubin. For AMDGPU, the bundle contains bitcode.
2583//
2584// For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
2585// inclusion of specific SDLs such as math libraries and the OpenMP device
2586// library libomptarget.
2588 const JobAction *JA,
2589 const InputInfoList *Inputs, const Driver &D,
2590 const llvm::opt::ArgList &DriverArgs,
2591 llvm::opt::ArgStringList &CC1Args,
2592 StringRef Arch, StringRef Target,
2593 bool isBitCodeSDL) {
2594
2595 SmallVector<std::string, 8> LibraryPaths;
2596 // Add search directories from LIBRARY_PATH env variable
2597 std::optional<std::string> LibPath =
2598 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2599 if (LibPath) {
2601 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2602 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2603 for (StringRef Path : Frags)
2604 LibraryPaths.emplace_back(Path.trim());
2605 }
2606
2607 // Add directories from user-specified -L options
2608 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
2609 LibraryPaths.emplace_back(Search_Dir);
2610
2611 // Add path to lib-debug folders
2612 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2613 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2614 LibraryPaths.emplace_back(DefaultLibPath.c_str());
2615
2616 // Build list of Static Device Libraries SDLs specified by -l option
2617 llvm::SmallSet<std::string, 16> SDLNames;
2618 static const StringRef HostOnlyArchives[] = {
2619 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2620 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
2621 if (!llvm::is_contained(HostOnlyArchives, SDLName)) {
2622 SDLNames.insert(std::string("-l") + SDLName);
2623 }
2624 }
2625
2626 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) {
2627 auto FileName = StringRef(Input);
2628 // Clang treats any unknown file types as archives and passes them to the
2629 // linker. Files with extension 'lib' are classified as TY_Object by clang
2630 // but they are usually archives. It is OK if the file is not really an
2631 // archive since GetSDLFromOffloadArchive will check the magic of the file
2632 // and only unbundle it if it is really an archive.
2633 const StringRef LibFileExt = ".lib";
2634 if (!llvm::sys::path::has_extension(FileName) ||
2636 llvm::sys::path::extension(FileName).drop_front()) ==
2638 llvm::sys::path::extension(FileName) == LibFileExt)
2639 SDLNames.insert(Input);
2640 }
2641
2642 // The search stops as soon as an SDL file is found. The driver then provides
2643 // the full filename of the SDL to the llvm-link command. If no SDL is found
2644 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an
2645 // archive file lib<libname>.a exists and may contain bundled object files.
2646 for (auto SDLName : SDLNames) {
2647 // This is the only call to SDLSearch
2648 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
2649 isBitCodeSDL)) {
2650 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
2651 LibraryPaths, SDLName, Arch, Target,
2652 isBitCodeSDL);
2653 }
2654 }
2655}
2656
2657static llvm::opt::Arg *
2658getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
2659 return Args.getLastArg(options::OPT_mcode_object_version_EQ);
2660}
2661
2663 const llvm::opt::ArgList &Args) {
2664 const unsigned MinCodeObjVer = 4;
2665 const unsigned MaxCodeObjVer = 6;
2666
2667 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2668 if (CodeObjArg->getOption().getID() ==
2669 options::OPT_mcode_object_version_EQ) {
2670 unsigned CodeObjVer = MaxCodeObjVer;
2671 auto Remnant =
2672 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2673 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2674 D.Diag(diag::err_drv_invalid_int_value)
2675 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2676
2677 // COV6 is only supported by LLVM at the time of writing this, and it's
2678 // expected to take some time before all ROCm components fully
2679 // support it. In the meantime, make sure users are aware of this.
2680 if (CodeObjVer == 6)
2681 D.Diag(diag::warn_drv_amdgpu_cov6);
2682 }
2683 }
2684}
2685
2687 const llvm::opt::ArgList &Args) {
2688 unsigned CodeObjVer = 4; // default
2689 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args))
2690 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2691 return CodeObjVer;
2692}
2693
2695 const Driver &D, const llvm::opt::ArgList &Args) {
2696 return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2697}
2698
2700 const llvm::opt::ArgList &Args,
2701 llvm::opt::ArgStringList &CmdArgs,
2702 const llvm::Triple &Triple, bool IsLTO,
2703 const StringRef PluginOptPrefix) {
2704 auto addArg = [&, IsLTO](const Twine &Arg) {
2705 if (IsLTO) {
2706 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2707 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2708 } else {
2709 CmdArgs.push_back("-mllvm");
2710 CmdArgs.push_back(Args.MakeArgString(Arg));
2711 }
2712 };
2713
2714 if (Arg *A = Args.getLastArg(options::OPT_moutline,
2715 options::OPT_mno_outline)) {
2716 if (A->getOption().matches(options::OPT_moutline)) {
2717 // We only support -moutline in AArch64 and ARM targets right now. If
2718 // we're not compiling for these, emit a warning and ignore the flag.
2719 // Otherwise, add the proper mllvm flags.
2720 if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) {
2721 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2722 } else {
2723 addArg(Twine("-enable-machine-outliner"));
2724 }
2725 } else {
2726 // Disable all outlining behaviour.
2727 addArg(Twine("-enable-machine-outliner=never"));
2728 }
2729 }
2730}
2731
2733 const llvm::opt::ArgList &DriverArgs,
2734 llvm::opt::ArgStringList &CC1Args,
2735 StringRef BitcodeSuffix,
2736 const llvm::Triple &Triple,
2737 const ToolChain &HostTC) {
2738 SmallVector<StringRef, 8> LibraryPaths;
2739
2740 // Add user defined library paths from LIBRARY_PATH.
2741 std::optional<std::string> LibPath =
2742 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2743 if (LibPath) {
2745 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2746 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2747 for (StringRef Path : Frags)
2748 LibraryPaths.emplace_back(Path.trim());
2749 }
2750
2751 // Check all of the standard library search paths used by the compiler.
2752 for (const auto &LibPath : HostTC.getFilePaths())
2753 LibraryPaths.emplace_back(LibPath);
2754
2755 OptSpecifier LibomptargetBCPathOpt =
2756 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2757 : options::OPT_libomptarget_nvptx_bc_path_EQ;
2758
2759 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2760 std::string LibOmpTargetName =
2761 ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2762
2763 // First check whether user specifies bc library
2764 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2765 SmallString<128> LibOmpTargetFile(A->getValue());
2766 if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2767 llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2768 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2769 }
2770
2771 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2772 CC1Args.push_back("-mlink-builtin-bitcode");
2773 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2774 } else {
2775 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2776 << LibOmpTargetFile;
2777 }
2778 } else {
2779 bool FoundBCLibrary = false;
2780
2781 for (StringRef LibraryPath : LibraryPaths) {
2782 SmallString<128> LibOmpTargetFile(LibraryPath);
2783 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2784 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2785 CC1Args.push_back("-mlink-builtin-bitcode");
2786 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2787 FoundBCLibrary = true;
2788 break;
2789 }
2790 }
2791
2792 if (!FoundBCLibrary)
2793 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2794 << LibOmpTargetName << ArchPrefix;
2795 }
2796}
2798 const llvm::opt::ArgList &Args,
2799 llvm::opt::ArgStringList &CmdArgs) {
2800 if ((C.getActiveOffloadKinds() & Action::OFK_HIP) &&
2801 !Args.hasArg(options::OPT_nostdlib) &&
2802 !Args.hasArg(options::OPT_no_hip_rt) && !Args.hasArg(options::OPT_r)) {
2803 TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2804 } else {
2805 // Claim "no HIP libraries" arguments if any
2806 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) {
2807 Arg->claim();
2808 }
2809 }
2810}
2811
2813 const llvm::opt::ArgList &Args,
2814 llvm::opt::ArgStringList &CmdArgs,
2815 const llvm::Triple &Triple) {
2816 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
2817 options::OPT_mno_outline_atomics)) {
2818 // Option -moutline-atomics supported for AArch64 target only.
2819 if (!Triple.isAArch64()) {
2820 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
2821 << Triple.getArchName() << A->getOption().getName();
2822 } else {
2823 if (A->getOption().matches(options::OPT_moutline_atomics)) {
2824 CmdArgs.push_back("-target-feature");
2825 CmdArgs.push_back("+outline-atomics");
2826 } else {
2827 CmdArgs.push_back("-target-feature");
2828 CmdArgs.push_back("-outline-atomics");
2829 }
2830 }
2831 } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) {
2832 CmdArgs.push_back("-target-feature");
2833 CmdArgs.push_back("+outline-atomics");
2834 }
2835}
2836
2837void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs,
2838 llvm::opt::ArgStringList &CmdArgs) {
2839 if (TCArgs.hasFlag(options::OPT_offload_compress,
2840 options::OPT_no_offload_compress, false))
2841 CmdArgs.push_back("-compress");
2842 if (TCArgs.hasArg(options::OPT_v))
2843 CmdArgs.push_back("-verbose");
2844 if (auto *Arg = TCArgs.getLastArg(options::OPT_offload_compression_level_EQ))
2845 CmdArgs.push_back(
2846 TCArgs.MakeArgString(Twine("-compression-level=") + Arg->getValue()));
2847}
2848
2849void tools::addMCModel(const Driver &D, const llvm::opt::ArgList &Args,
2850 const llvm::Triple &Triple,
2851 const llvm::Reloc::Model &RelocationModel,
2852 llvm::opt::ArgStringList &CmdArgs) {
2853 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2854 StringRef CM = A->getValue();
2855 bool Ok = false;
2856 if (Triple.isOSAIX() && CM == "medium")
2857 CM = "large";
2858 if (Triple.isAArch64(64)) {
2859 Ok = CM == "tiny" || CM == "small" || CM == "large";
2860 if (CM == "large" && !Triple.isOSBinFormatMachO() &&
2861 RelocationModel != llvm::Reloc::Static)
2862 D.Diag(diag::err_drv_argument_only_allowed_with)
2863 << A->getAsString(Args) << "-fno-pic";
2864 } else if (Triple.isLoongArch()) {
2865 if (CM == "extreme" &&
2866 Args.hasFlagNoClaim(options::OPT_fplt, options::OPT_fno_plt, false))
2867 D.Diag(diag::err_drv_argument_not_allowed_with)
2868 << A->getAsString(Args) << "-fplt";
2869 Ok = CM == "normal" || CM == "medium" || CM == "extreme";
2870 // Convert to LLVM recognizable names.
2871 if (Ok)
2872 CM = llvm::StringSwitch<StringRef>(CM)
2873 .Case("normal", "small")
2874 .Case("extreme", "large")
2875 .Default(CM);
2876 } else if (Triple.isPPC64() || Triple.isOSAIX()) {
2877 Ok = CM == "small" || CM == "medium" || CM == "large";
2878 } else if (Triple.isRISCV()) {
2879 if (CM == "medlow")
2880 CM = "small";
2881 else if (CM == "medany")
2882 CM = "medium";
2883 Ok = CM == "small" || CM == "medium";
2884 } else if (Triple.getArch() == llvm::Triple::x86_64) {
2885 Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
2886 CM);
2887 } else if (Triple.isNVPTX() || Triple.isAMDGPU() || Triple.isSPIRV()) {
2888 // NVPTX/AMDGPU/SPIRV does not care about the code model and will accept
2889 // whatever works for the host.
2890 Ok = true;
2891 } else if (Triple.isSPARC64()) {
2892 if (CM == "medlow")
2893 CM = "small";
2894 else if (CM == "medmid")
2895 CM = "medium";
2896 else if (CM == "medany")
2897 CM = "large";
2898 Ok = CM == "small" || CM == "medium" || CM == "large";
2899 }
2900 if (Ok) {
2901 CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
2902 } else {
2903 D.Diag(diag::err_drv_unsupported_option_argument_for_target)
2904 << A->getSpelling() << CM << Triple.getTriple();
2905 }
2906 }
2907
2908 if (Triple.getArch() == llvm::Triple::x86_64) {
2909 bool IsMediumCM = false;
2910 bool IsLargeCM = false;
2911 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
2912 IsMediumCM = StringRef(A->getValue()) == "medium";
2913 IsLargeCM = StringRef(A->getValue()) == "large";
2914 }
2915 if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
2916 if (!IsMediumCM && !IsLargeCM) {
2917 D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
2918 << A->getOption().getRenderName();
2919 } else {
2920 A->render(Args, CmdArgs);
2921 }
2922 } else if (IsMediumCM) {
2923 CmdArgs.push_back("-mlarge-data-threshold=65536");
2924 } else if (IsLargeCM) {
2925 CmdArgs.push_back("-mlarge-data-threshold=0");
2926 }
2927 }
2928}
#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