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 "clang/Driver/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"
26#include "ToolChains/Cuda.h"
27#include "clang/Basic/CodeGenOptions.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
30#include "clang/Driver/Compilation.h"
31#include "clang/Driver/Driver.h"
32#include "clang/Driver/InputInfo.h"
33#include "clang/Driver/Job.h"
34#include "clang/Driver/SanitizerArgs.h"
35#include "clang/Driver/ToolChain.h"
36#include "clang/Driver/Util.h"
37#include "clang/Driver/XRayArgs.h"
38#include "clang/Frontend/CompilerInvocation.h"
39#include "clang/Options/Options.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallSet.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/ADT/StringSwitch.h"
45#include "llvm/ADT/Twine.h"
46#include "llvm/BinaryFormat/Magic.h"
47#include "llvm/Config/llvm-config.h"
48#include "llvm/Option/Arg.h"
49#include "llvm/Option/ArgList.h"
50#include "llvm/Option/Option.h"
51#include "llvm/Support/CodeGen.h"
52#include "llvm/Support/Compression.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/FileSystem.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/Process.h"
57#include "llvm/Support/Program.h"
58#include "llvm/Support/Threading.h"
59#include "llvm/Support/VirtualFileSystem.h"
60#include "llvm/Support/YAMLParser.h"
61#include "llvm/TargetParser/AMDGPUTargetParser.h"
62#include "llvm/TargetParser/Host.h"
63#include "llvm/TargetParser/PPCTargetParser.h"
64#include <optional>
65
66using namespace clang::driver;
67using namespace clang::driver::tools;
68using namespace clang;
69using namespace llvm::opt;
70
71OffloadJobsOpt tools::parseOffloadJobs(const ArgList &Args) {
72 Arg *A = Args.getLastArg(Ids: options::OPT_offload_jobs_EQ);
73 if (!A)
74 return {};
75
76 StringRef Val = A->getValue();
77 if (Val.equals_insensitive(RHS: "jobserver"))
78 return {.K: OffloadJobsOpt::Kind::Jobserver, .A: A, .Value: Val};
79
80 int NumThreads;
81 if (Val.getAsInteger(Radix: 10, Result&: NumThreads) || NumThreads <= 0)
82 return {.K: OffloadJobsOpt::Kind::Invalid, .A: A, .Value: Val};
83
84 return {.K: OffloadJobsOpt::Kind::Fixed, .A: A, .Value: Val, .NumThreads: unsigned(NumThreads)};
85}
86
87static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args,
88 const llvm::Triple &Triple) {
89 if (Args.hasArg(Ids: options::OPT_pg) && !Args.hasArg(Ids: options::OPT_mfentry))
90 return true;
91
92 if (Triple.isAndroid())
93 return true;
94
95 switch (Triple.getArch()) {
96 case llvm::Triple::xcore:
97 case llvm::Triple::wasm32:
98 case llvm::Triple::wasm64:
99 case llvm::Triple::msp430:
100 // XCore never wants frame pointers, regardless of OS.
101 // WebAssembly never wants frame pointers.
102 return false;
103 case llvm::Triple::ppc:
104 case llvm::Triple::ppcle:
105 case llvm::Triple::ppc64:
106 case llvm::Triple::ppc64le:
107 case llvm::Triple::riscv32:
108 case llvm::Triple::riscv64:
109 case llvm::Triple::riscv32be:
110 case llvm::Triple::riscv64be:
111 case llvm::Triple::sparc:
112 case llvm::Triple::sparcel:
113 case llvm::Triple::sparcv9:
114 case llvm::Triple::amdgpu:
115 case llvm::Triple::r600:
116 case llvm::Triple::csky:
117 case llvm::Triple::loongarch32:
118 case llvm::Triple::loongarch64:
119 case llvm::Triple::m68k:
120 case llvm::Triple::mips64:
121 case llvm::Triple::mips64el:
122 case llvm::Triple::mips:
123 case llvm::Triple::mipsel:
124 return !clang::driver::tools::areOptimizationsEnabled(Args);
125 default:
126 break;
127 }
128
129 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
130 return !clang::driver::tools::areOptimizationsEnabled(Args);
131 }
132
133 if (Triple.isOSLinux() || Triple.isOSHurd()) {
134 switch (Triple.getArch()) {
135 // Don't use a frame pointer on linux if optimizing for certain targets.
136 case llvm::Triple::arm:
137 case llvm::Triple::armeb:
138 case llvm::Triple::thumb:
139 case llvm::Triple::thumbeb:
140 case llvm::Triple::systemz:
141 case llvm::Triple::x86:
142 case llvm::Triple::x86_64:
143 return !clang::driver::tools::areOptimizationsEnabled(Args);
144 default:
145 return true;
146 }
147 }
148
149 if (Triple.isOSWindows()) {
150 switch (Triple.getArch()) {
151 case llvm::Triple::x86:
152 return !clang::driver::tools::areOptimizationsEnabled(Args);
153 case llvm::Triple::x86_64:
154 return Triple.isOSBinFormatMachO();
155 case llvm::Triple::arm:
156 case llvm::Triple::thumb:
157 // Windows on ARM builds with FPO disabled to aid fast stack walking
158 return true;
159 default:
160 // All other supported Windows ISAs use xdata unwind information, so frame
161 // pointers are not generally useful.
162 return false;
163 }
164 }
165
166 if (arm::isARMEABIBareMetal(Triple))
167 return false;
168
169 return true;
170}
171
172static bool useLeafFramePointerForTargetByDefault(const llvm::Triple &Triple) {
173 if (Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
174 (Triple.isAndroid() && !Triple.isARM()))
175 return false;
176
177 if ((Triple.isARM() || Triple.isThumb()) && Triple.isOSBinFormatMachO())
178 return false;
179
180 return true;
181}
182
183static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
184 switch (Triple.getArch()) {
185 default:
186 return false;
187 case llvm::Triple::arm:
188 case llvm::Triple::thumb:
189 // ARM Darwin targets require a frame pointer to be always present to aid
190 // offline debugging via backtraces.
191 return Triple.isOSDarwin();
192 }
193}
194
195// True if a target-specific option requires the frame chain to be preserved,
196// even if new frame records are not created.
197static bool mustMaintainValidFrameChain(const llvm::opt::ArgList &Args,
198 const llvm::Triple &Triple) {
199 switch (Triple.getArch()) {
200 default:
201 return false;
202 case llvm::Triple::arm:
203 case llvm::Triple::armeb:
204 case llvm::Triple::thumb:
205 case llvm::Triple::thumbeb:
206 // For 32-bit Arm, the -mframe-chain=aapcs and -mframe-chain=aapcs+leaf
207 // options require the frame pointer register to be reserved (or point to a
208 // new AAPCS-compilant frame record), even with -fno-omit-frame-pointer.
209 if (Arg *A = Args.getLastArg(Ids: options::OPT_mframe_chain)) {
210 StringRef V = A->getValue();
211 return V != "none";
212 }
213 return false;
214
215 case llvm::Triple::aarch64:
216 // Arm64 Windows requires that the frame chain is valid, as there is no
217 // way to indicate during a stack walk that a frame has used the frame
218 // pointer as a general purpose register.
219 return Triple.isOSWindows();
220 }
221}
222
223// True if a target-specific option causes -fno-omit-frame-pointer to also
224// cause frame records to be created in leaf functions.
225static bool framePointerImpliesLeafFramePointer(const llvm::opt::ArgList &Args,
226 const llvm::Triple &Triple) {
227 if (Triple.isARM() || Triple.isThumb()) {
228 // For 32-bit Arm, the -mframe-chain=aapcs+leaf option causes the
229 // -fno-omit-frame-pointer optiion to imply -mno-omit-leaf-frame-pointer,
230 // but does not by itself imply either option.
231 if (Arg *A = Args.getLastArg(Ids: options::OPT_mframe_chain)) {
232 StringRef V = A->getValue();
233 return V == "aapcs+leaf";
234 }
235 return false;
236 }
237 return false;
238}
239
240clang::CodeGenOptions::FramePointerKind
241getFramePointerKind(const llvm::opt::ArgList &Args,
242 const llvm::Triple &Triple) {
243 // There are four things to consider here:
244 // * Should a frame record be created for non-leaf functions?
245 // * Should a frame record be created for leaf functions?
246 // * Is the frame pointer register reserved in non-leaf functions?
247 // i.e. must it always point to either a new, valid frame record or be
248 // un-modified?
249 // * Is the frame pointer register reserved in leaf functions?
250 //
251 // Not all combinations of these are valid:
252 // * It's not useful to have leaf frame records without non-leaf ones.
253 // * It's not useful to have frame records without reserving the frame
254 // pointer.
255 //
256 // | Frame Setup | Reg Reserved |
257 // |-----------------|-----------------|
258 // | Non-leaf | Leaf | Non-Leaf | Leaf |
259 // |----------|------|----------|------|
260 // | N | N | N | N | FramePointerKind::None
261 // | N | N | N | Y | Invalid
262 // | N | N | Y | N | Invalid
263 // | N | N | Y | Y | FramePointerKind::Reserved
264 // | N | Y | N | N | Invalid
265 // | N | Y | N | Y | Invalid
266 // | N | Y | Y | N | Invalid
267 // | N | Y | Y | Y | Invalid
268 // | Y | N | N | N | Invalid
269 // | Y | N | N | Y | Invalid
270 // | Y | N | Y | N | FramePointerKind::NonLeafNoReserve
271 // | Y | N | Y | Y | FramePointerKind::NonLeaf
272 // | Y | Y | N | N | Invalid
273 // | Y | Y | N | Y | Invalid
274 // | Y | Y | Y | N | Invalid
275 // | Y | Y | Y | Y | FramePointerKind::All
276 //
277 // The FramePointerKind::Reserved case is currently only reachable for Arm,
278 // which has the -mframe-chain= option which can (in combination with
279 // -fno-omit-frame-pointer) specify that the frame chain must be valid,
280 // without requiring new frame records to be created.
281
282 bool DefaultFP = useFramePointerForTargetByDefault(Args, Triple);
283 bool EnableFP = mustUseNonLeafFramePointerForTarget(Triple) ||
284 Args.hasFlag(Pos: options::OPT_fno_omit_frame_pointer,
285 Neg: options::OPT_fomit_frame_pointer, Default: DefaultFP);
286
287 bool DefaultLeafFP =
288 useLeafFramePointerForTargetByDefault(Triple) ||
289 (EnableFP && framePointerImpliesLeafFramePointer(Args, Triple));
290 bool EnableLeafFP =
291 Args.hasFlag(Pos: options::OPT_mno_omit_leaf_frame_pointer,
292 Neg: options::OPT_momit_leaf_frame_pointer, Default: DefaultLeafFP);
293
294 bool FPRegReserved = Args.hasFlag(Pos: options::OPT_mreserve_frame_pointer_reg,
295 Neg: options::OPT_mno_reserve_frame_pointer_reg,
296 Default: mustMaintainValidFrameChain(Args, Triple));
297
298 if (EnableFP) {
299 if (EnableLeafFP)
300 return clang::CodeGenOptions::FramePointerKind::All;
301
302 if (FPRegReserved)
303 return clang::CodeGenOptions::FramePointerKind::NonLeaf;
304
305 return clang::CodeGenOptions::FramePointerKind::NonLeafNoReserve;
306 }
307 if (FPRegReserved)
308 return clang::CodeGenOptions::FramePointerKind::Reserved;
309 return clang::CodeGenOptions::FramePointerKind::None;
310}
311
312static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs,
313 const StringRef PluginOptPrefix) {
314 if (const Arg *A = Args.getLastArg(Ids: options::OPT_Rpass_EQ))
315 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
316 "-pass-remarks=" + A->getValue()));
317
318 if (const Arg *A = Args.getLastArg(Ids: options::OPT_Rpass_missed_EQ))
319 CmdArgs.push_back(Elt: Args.MakeArgString(
320 Str: Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue()));
321
322 if (const Arg *A = Args.getLastArg(Ids: options::OPT_Rpass_analysis_EQ))
323 CmdArgs.push_back(Elt: Args.MakeArgString(
324 Str: Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue()));
325}
326
327static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
328 const llvm::Triple &Triple,
329 const InputInfo &Input,
330 const InputInfo &Output,
331 const StringRef PluginOptPrefix) {
332 StringRef Format = "yaml";
333 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
334 Format = A->getValue();
335
336 SmallString<128> F;
337 if (const Arg *A =
338 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ)) {
339 F = A->getValue();
340 F += ".";
341 } else if (const Arg *A = Args.getLastArg(Ids: options::OPT_dumpdir)) {
342 F = A->getValue();
343 } else if (Output.isFilename()) {
344 F = Output.getFilename();
345 F += ".";
346 }
347
348 assert(!F.empty() && "Cannot determine remarks output name.");
349 // Append "opt.ld.<format>" to the end of the file name.
350 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
351 "opt-remarks-filename=" + F + "opt.ld." +
352 Format));
353
354 if (const Arg *A =
355 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ))
356 CmdArgs.push_back(Elt: Args.MakeArgString(
357 Str: Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue()));
358
359 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
360 "opt-remarks-format=" + Format.data()));
361}
362
363static void renderRemarksHotnessOptions(const ArgList &Args,
364 ArgStringList &CmdArgs,
365 const StringRef PluginOptPrefix) {
366 if (Args.hasFlag(Pos: options::OPT_fdiagnostics_show_hotness,
367 Neg: options::OPT_fno_diagnostics_show_hotness, Default: false))
368 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
369 "opt-remarks-with-hotness"));
370
371 if (const Arg *A =
372 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ))
373 CmdArgs.push_back(
374 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
375 "opt-remarks-hotness-threshold=" + A->getValue()));
376}
377
378static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg,
379 llvm::Triple T,
380 StringRef Processor) {
381 // Warn no-cumode for AMDGCN processors not supporing WGP mode.
382 if (!T.isAMDGCN())
383 return false;
384 llvm::AMDGPU::GPUKind GPUKind = llvm::AMDGPU::parseArchAMDGCN(CPU: Processor);
385 if (llvm::AMDGPU::getFeatureBitset(AK: GPUKind).test(
386 I: llvm::AMDGPU::FEAT_SUPPORTS_WGP))
387 return false;
388 return TargetFeatureArg.getOption().matches(ID: options::OPT_mno_cumode);
389}
390
391void tools::addPathIfExists(const Driver &D, const Twine &Path,
392 ToolChain::path_list &Paths) {
393 if (D.getVFS().exists(Path))
394 Paths.push_back(Elt: Path.str());
395}
396
397void tools::handleTargetFeaturesGroup(const Driver &D,
398 const llvm::Triple &Triple,
399 const ArgList &Args,
400 std::vector<StringRef> &Features,
401 OptSpecifier Group) {
402 std::set<StringRef> Warned;
403 for (const Arg *A : Args.filtered(Ids: Group)) {
404 StringRef Name = A->getOption().getName();
405 A->claim();
406
407 // Skip over "-m".
408 assert(Name.starts_with("m") && "Invalid feature name.");
409 Name = Name.substr(Start: 1);
410
411 auto Proc = getCPUName(D, Args, T: Triple);
412 if (shouldIgnoreUnsupportedTargetFeature(TargetFeatureArg: *A, T: Triple, Processor: Proc)) {
413 if (Warned.count(x: Name) == 0) {
414 D.getDiags().Report(
415 DiagID: clang::diag::warn_drv_unsupported_option_for_processor)
416 << A->getAsString(Args) << Proc;
417 Warned.insert(x: Name);
418 }
419 continue;
420 }
421
422 bool IsNegative = Name.consume_front(Prefix: "no-");
423
424 Features.push_back(x: Args.MakeArgString(Str: (IsNegative ? "-" : "+") + Name));
425 }
426}
427
428SmallVector<StringRef>
429tools::unifyTargetFeatures(ArrayRef<StringRef> Features) {
430 // Only add a feature if it hasn't been seen before starting from the end.
431 SmallVector<StringRef> UnifiedFeatures;
432 llvm::DenseSet<StringRef> UsedFeatures;
433 for (StringRef Feature : llvm::reverse(C&: Features)) {
434 if (UsedFeatures.insert(V: Feature.drop_front()).second)
435 UnifiedFeatures.insert(I: UnifiedFeatures.begin(), Elt: Feature);
436 }
437
438 return UnifiedFeatures;
439}
440
441void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
442 const char *ArgName, const char *EnvVar) {
443 const char *DirList = ::getenv(name: EnvVar);
444 bool CombinedArg = false;
445
446 if (!DirList)
447 return; // Nothing to do.
448
449 StringRef Name(ArgName);
450 if (Name == "-I" || Name == "-L" || Name.empty())
451 CombinedArg = true;
452
453 StringRef Dirs(DirList);
454 if (Dirs.empty()) // Empty string should not add '.'.
455 return;
456
457 StringRef::size_type Delim;
458 while ((Delim = Dirs.find(C: llvm::sys::EnvPathSeparator)) != StringRef::npos) {
459 if (Delim == 0) { // Leading colon.
460 if (CombinedArg) {
461 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string(ArgName) + "."));
462 } else {
463 CmdArgs.push_back(Elt: ArgName);
464 CmdArgs.push_back(Elt: ".");
465 }
466 } else {
467 if (CombinedArg) {
468 CmdArgs.push_back(
469 Elt: Args.MakeArgString(Str: std::string(ArgName) + Dirs.substr(Start: 0, N: Delim)));
470 } else {
471 CmdArgs.push_back(Elt: ArgName);
472 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Dirs.substr(Start: 0, N: Delim)));
473 }
474 }
475 Dirs = Dirs.substr(Start: Delim + 1);
476 }
477
478 if (Dirs.empty()) { // Trailing colon.
479 if (CombinedArg) {
480 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string(ArgName) + "."));
481 } else {
482 CmdArgs.push_back(Elt: ArgName);
483 CmdArgs.push_back(Elt: ".");
484 }
485 } else { // Add the last path.
486 if (CombinedArg) {
487 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string(ArgName) + Dirs));
488 } else {
489 CmdArgs.push_back(Elt: ArgName);
490 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Dirs));
491 }
492 }
493}
494
495void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
496 const ArgList &Args, ArgStringList &CmdArgs,
497 const JobAction &JA) {
498 const Driver &D = TC.getDriver();
499
500 // Add extra linker input arguments which are not treated as inputs
501 // (constructed via -Xarch_).
502 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Zlinker_input);
503
504 // LIBRARY_PATH are included before user inputs and only supported on native
505 // toolchains.
506 if (!TC.isCrossCompiling())
507 addDirectoryList(Args, CmdArgs, ArgName: "-L", EnvVar: "LIBRARY_PATH");
508
509 for (const auto &II : Inputs) {
510 // If the current tool chain refers to an OpenMP offloading host, we
511 // should ignore inputs that refer to OpenMP offloading devices -
512 // they will be embedded according to a proper linker script.
513 if (auto *IA = II.getAction())
514 if ((JA.isHostOffloading(OKind: Action::OFK_OpenMP) &&
515 IA->isDeviceOffloading(OKind: Action::OFK_OpenMP)))
516 continue;
517
518 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(Id: II.getType()))
519 // Don't try to pass LLVM inputs unless we have native support.
520 D.Diag(DiagID: diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
521
522 // Add filenames immediately.
523 if (II.isFilename()) {
524 CmdArgs.push_back(Elt: II.getFilename());
525 continue;
526 }
527
528 // In some error cases, the input could be Nothing; skip those.
529 if (II.isNothing())
530 continue;
531
532 // Otherwise, this is a linker input argument.
533 const Arg &A = II.getInputArg();
534
535 // Handle reserved library options.
536 if (A.getOption().matches(ID: options::OPT_Z_reserved_lib_stdcxx))
537 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
538 else if (A.getOption().matches(ID: options::OPT_Z_reserved_lib_cckext))
539 TC.AddCCKextLibArgs(Args, CmdArgs);
540 // Do not pass OPT_rpath to linker in AIX
541 else if (A.getOption().matches(ID: options::OPT_rpath) &&
542 TC.getTriple().isOSAIX())
543 continue;
544 else
545 A.renderAsInput(Args, Output&: CmdArgs);
546 }
547 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
548 const llvm::Triple &Triple = TC.getTriple();
549 StringRef V = A->getValue();
550 if (V == "ArmPL" && (Triple.isOSLinux() || Triple.isOSDarwin())) {
551 // To support -fveclib=ArmPL we need to link against libamath. Some of the
552 // libamath functions depend on libm, at the same time, libamath exports
553 // its own implementation of some of the libm functions. These are faster
554 // and potentially less accurate implementations, hence we need to be
555 // careful what is being linked in. Since here we are interested only in
556 // the subset of libamath functions that is covered by the veclib
557 // mappings, we need to prioritize libm functions by putting -lm before
558 // -lamath (and then -lm again, to fulfill libamath requirements).
559 //
560 // Therefore we need to do the following:
561 //
562 // 1. On Linux, link only when actually needed.
563 //
564 // 2. Prefer libm functions over libamath (when no -nostdlib in use).
565 //
566 // 3. Link against libm to resolve libamath dependencies.
567 //
568 if (Triple.isOSLinux()) {
569 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--push-state"));
570 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--as-needed"));
571 }
572 if (!Args.hasArg(Ids: options::OPT_nostdlib))
573 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lm"));
574 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lamath"));
575 if (!Args.hasArg(Ids: options::OPT_nostdlib))
576 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lm"));
577 if (Triple.isOSLinux())
578 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--pop-state"));
579 addArchSpecificRPath(TC, Args, CmdArgs);
580 }
581 }
582}
583
584const char *tools::getLDMOption(const llvm::Triple &T, const ArgList &Args) {
585 switch (T.getArch()) {
586 case llvm::Triple::x86:
587 if (T.isOSIAMCU())
588 return "elf_iamcu";
589 return "elf_i386";
590 case llvm::Triple::aarch64:
591 if (T.isOSManagarm())
592 return "aarch64managarm";
593 else if (aarch64::isAArch64BareMetal(Triple: T))
594 return "aarch64elf";
595 return "aarch64linux";
596 case llvm::Triple::aarch64_be:
597 if (aarch64::isAArch64BareMetal(Triple: T))
598 return "aarch64elfb";
599 return "aarch64linuxb";
600 case llvm::Triple::arm:
601 case llvm::Triple::thumb:
602 case llvm::Triple::armeb:
603 case llvm::Triple::thumbeb: {
604 bool IsBigEndian = tools::arm::isARMBigEndian(Triple: T, Args);
605 if (arm::isARMEABIBareMetal(Triple: T))
606 return IsBigEndian ? "armelfb" : "armelf";
607 return IsBigEndian ? "armelfb_linux_eabi" : "armelf_linux_eabi";
608 }
609 case llvm::Triple::m68k:
610 return "m68kelf";
611 case llvm::Triple::ppc:
612 if (T.isOSLinux())
613 return "elf32ppclinux";
614 return "elf32ppc";
615 case llvm::Triple::ppcle:
616 if (T.isOSLinux())
617 return "elf32lppclinux";
618 return "elf32lppc";
619 case llvm::Triple::ppc64:
620 return "elf64ppc";
621 case llvm::Triple::ppc64le:
622 return "elf64lppc";
623 case llvm::Triple::riscv32:
624 return "elf32lriscv";
625 case llvm::Triple::riscv64:
626 return "elf64lriscv";
627 case llvm::Triple::riscv32be:
628 return "elf32briscv";
629 case llvm::Triple::riscv64be:
630 return "elf64briscv";
631 case llvm::Triple::sparc:
632 case llvm::Triple::sparcel:
633 return "elf32_sparc";
634 case llvm::Triple::sparcv9:
635 return "elf64_sparc";
636 case llvm::Triple::loongarch32:
637 return "elf32loongarch";
638 case llvm::Triple::loongarch64:
639 return "elf64loongarch";
640 case llvm::Triple::mips:
641 return "elf32btsmip";
642 case llvm::Triple::mipsel:
643 return "elf32ltsmip";
644 case llvm::Triple::mips64:
645 if (tools::mips::hasMipsAbiArg(Args, Value: "n32") || T.isABIN32())
646 return "elf32btsmipn32";
647 return "elf64btsmip";
648 case llvm::Triple::mips64el:
649 if (tools::mips::hasMipsAbiArg(Args, Value: "n32") || T.isABIN32())
650 return "elf32ltsmipn32";
651 return "elf64ltsmip";
652 case llvm::Triple::systemz:
653 return "elf64_s390";
654 case llvm::Triple::x86_64:
655 if (T.isX32())
656 return "elf32_x86_64";
657 return "elf_x86_64";
658 case llvm::Triple::ve:
659 return "elf64ve";
660 case llvm::Triple::csky:
661 return "cskyelf_linux";
662 default:
663 return nullptr;
664 }
665}
666
667void tools::addLinkerCompressDebugSectionsOption(
668 const ToolChain &TC, const llvm::opt::ArgList &Args,
669 llvm::opt::ArgStringList &CmdArgs) {
670 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
671 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
672 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
673 // is not translated since ld --compress-debug-sections option requires an
674 // argument.
675 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ)) {
676 StringRef V = A->getValue();
677 if (V == "none" || V == "zlib" || V == "zstd")
678 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + V));
679 else
680 TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
681 << A->getSpelling() << V;
682 }
683}
684
685void tools::renderDebugInfoCompressionArgs(const ArgList &Args,
686 ArgStringList &CmdArgs,
687 const Driver &D,
688 const ToolChain &TC) {
689 const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ);
690 if (!A)
691 return;
692 if (checkDebugInfoOption(A, Args, D, TC)) {
693 StringRef Value = A->getValue();
694 if (Value == "none") {
695 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
696 } else if (Value == "zlib") {
697 if (llvm::compression::zlib::isAvailable()) {
698 CmdArgs.push_back(
699 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
700 } else {
701 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zlib";
702 }
703 } else if (Value == "zstd") {
704 if (llvm::compression::zstd::isAvailable()) {
705 CmdArgs.push_back(
706 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
707 } else {
708 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zstd";
709 }
710 } else {
711 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
712 << A->getSpelling() << Value;
713 }
714 }
715}
716
717void tools::AddTargetFeature(const ArgList &Args,
718 std::vector<StringRef> &Features,
719 OptSpecifier OnOpt, OptSpecifier OffOpt,
720 StringRef FeatureName) {
721 if (Arg *A = Args.getLastArg(Ids: OnOpt, Ids: OffOpt)) {
722 if (A->getOption().matches(ID: OnOpt))
723 Features.push_back(x: Args.MakeArgString(Str: "+" + FeatureName));
724 else
725 Features.push_back(x: Args.MakeArgString(Str: "-" + FeatureName));
726 }
727}
728
729/// Get the (LLVM) name of the AMDGPU gpu we are targeting.
730static StringRef getAMDGPUTargetGPU(const llvm::Triple &T,
731 const ArgList &Args) {
732 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
733 return getProcessorFromTargetID(T, OffloadArch: A->getValue());
734 }
735 return "";
736}
737
738static std::string getLanaiTargetCPU(const ArgList &Args) {
739 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
740 return A->getValue();
741 }
742 return "";
743}
744
745/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
746static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
747 // If we have -mcpu=, use that.
748 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
749 StringRef CPU = A->getValue();
750
751#ifdef __wasm__
752 // Handle "native" by examining the host. "native" isn't meaningful when
753 // cross compiling, so only support this when the host is also WebAssembly.
754 if (CPU == "native")
755 return llvm::sys::getHostCPUName();
756#endif
757
758 return CPU;
759 }
760
761 return "generic";
762}
763
764std::string tools::getCPUName(const Driver &D, const ArgList &Args,
765 const llvm::Triple &T, bool FromAs) {
766 Arg *A;
767
768 switch (T.getArch()) {
769 default:
770 return "";
771
772 case llvm::Triple::aarch64:
773 case llvm::Triple::aarch64_32:
774 case llvm::Triple::aarch64_be:
775 return aarch64::getAArch64TargetCPU(Args, Triple: T, A);
776
777 case llvm::Triple::arm:
778 case llvm::Triple::armeb:
779 case llvm::Triple::thumb:
780 case llvm::Triple::thumbeb: {
781 StringRef MArch, MCPU;
782 arm::getARMArchCPUFromArgs(Args, Arch&: MArch, CPU&: MCPU, FromAs);
783 return arm::getARMTargetCPU(CPU: MCPU, Arch: MArch, Triple: T);
784 }
785
786 case llvm::Triple::avr:
787 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mmcu_EQ))
788 return A->getValue();
789 return "";
790
791 case llvm::Triple::m68k:
792 return m68k::getM68kTargetCPU(Args);
793
794 case llvm::Triple::mips:
795 case llvm::Triple::mipsel:
796 case llvm::Triple::mips64:
797 case llvm::Triple::mips64el: {
798 StringRef CPUName;
799 StringRef ABIName;
800 mips::getMipsCPUAndABI(Args, Triple: T, CPUName, ABIName);
801 return std::string(CPUName);
802 }
803
804 case llvm::Triple::nvptx:
805 case llvm::Triple::nvptx64:
806 if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ))
807 return A->getValue();
808 return "";
809
810 case llvm::Triple::ppc:
811 case llvm::Triple::ppcle:
812 case llvm::Triple::ppc64:
813 case llvm::Triple::ppc64le:
814 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
815 return std::string(
816 llvm::PPC::getNormalizedPPCTargetCPU(T, CPUName: A->getValue()));
817 return std::string(llvm::PPC::getNormalizedPPCTargetCPU(T));
818
819 case llvm::Triple::csky:
820 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
821 return A->getValue();
822 else if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ))
823 return A->getValue();
824 else
825 return "ck810";
826 case llvm::Triple::riscv32:
827 case llvm::Triple::riscv64:
828 case llvm::Triple::riscv32be:
829 case llvm::Triple::riscv64be:
830 return riscv::getRISCVTargetCPU(Args, Triple: T);
831
832 case llvm::Triple::bpfel:
833 case llvm::Triple::bpfeb:
834 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
835 return A->getValue();
836 return "";
837
838 case llvm::Triple::sparc:
839 case llvm::Triple::sparcel:
840 case llvm::Triple::sparcv9:
841 return sparc::getSparcTargetCPU(D, Args, Triple: T);
842
843 case llvm::Triple::x86:
844 case llvm::Triple::x86_64:
845 return x86::getX86TargetCPU(D, Args, Triple: T);
846
847 case llvm::Triple::hexagon:
848 return "hexagon" +
849 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
850
851 case llvm::Triple::lanai:
852 return getLanaiTargetCPU(Args);
853
854 case llvm::Triple::systemz:
855 return systemz::getSystemZTargetCPU(Args, T);
856
857 case llvm::Triple::amdgpu:
858 case llvm::Triple::r600:
859 return getAMDGPUTargetGPU(T, Args).str();
860
861 case llvm::Triple::wasm32:
862 case llvm::Triple::wasm64:
863 return std::string(getWebAssemblyTargetCPU(Args));
864
865 case llvm::Triple::loongarch32:
866 case llvm::Triple::loongarch64:
867 return loongarch::getLoongArchTargetCPU(Args, Triple: T);
868
869 case llvm::Triple::xtensa:
870 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ))
871 return A->getValue();
872 return "";
873 }
874}
875
876static void getWebAssemblyTargetFeatures(const Driver &D,
877 const llvm::Triple &Triple,
878 const ArgList &Args,
879 std::vector<StringRef> &Features) {
880 handleTargetFeaturesGroup(D, Triple, Args, Features,
881 Group: options::OPT_m_wasm_Features_Group);
882}
883
884void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
885 const ArgList &Args, ArgStringList &CmdArgs,
886 bool ForAS, bool IsAux) {
887 std::vector<StringRef> Features;
888 switch (Triple.getArch()) {
889 default:
890 break;
891 case llvm::Triple::mips:
892 case llvm::Triple::mipsel:
893 case llvm::Triple::mips64:
894 case llvm::Triple::mips64el:
895 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
896 break;
897 case llvm::Triple::arm:
898 case llvm::Triple::armeb:
899 case llvm::Triple::thumb:
900 case llvm::Triple::thumbeb:
901 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS);
902 break;
903 case llvm::Triple::ppc:
904 case llvm::Triple::ppcle:
905 case llvm::Triple::ppc64:
906 case llvm::Triple::ppc64le:
907 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
908 break;
909 case llvm::Triple::riscv32:
910 case llvm::Triple::riscv64:
911 case llvm::Triple::riscv32be:
912 case llvm::Triple::riscv64be:
913 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
914 break;
915 case llvm::Triple::systemz:
916 systemz::getSystemZTargetFeatures(D, Args, Features);
917 break;
918 case llvm::Triple::aarch64:
919 case llvm::Triple::aarch64_32:
920 case llvm::Triple::aarch64_be:
921 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
922 break;
923 case llvm::Triple::x86:
924 case llvm::Triple::x86_64:
925 x86::getX86TargetFeatures(D, Triple, Args, Features);
926 break;
927 case llvm::Triple::hexagon:
928 hexagon::getHexagonTargetFeatures(D, Triple, Args, Features);
929 break;
930 case llvm::Triple::wasm32:
931 case llvm::Triple::wasm64:
932 getWebAssemblyTargetFeatures(D, Triple, Args, Features);
933 break;
934 case llvm::Triple::sparc:
935 case llvm::Triple::sparcel:
936 case llvm::Triple::sparcv9:
937 sparc::getSparcTargetFeatures(D, Triple, Args, Features);
938 break;
939 case llvm::Triple::amdgpu:
940 case llvm::Triple::r600:
941 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features, ForAS);
942 break;
943 case llvm::Triple::nvptx:
944 case llvm::Triple::nvptx64:
945 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features);
946 break;
947 case llvm::Triple::m68k:
948 m68k::getM68kTargetFeatures(D, Triple, Args, Features);
949 break;
950 case llvm::Triple::msp430:
951 msp430::getMSP430TargetFeatures(D, Args, Features);
952 break;
953 case llvm::Triple::ve:
954 ve::getVETargetFeatures(D, Args, Features);
955 break;
956 case llvm::Triple::csky:
957 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features);
958 break;
959 case llvm::Triple::loongarch32:
960 case llvm::Triple::loongarch64:
961 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features);
962 break;
963 }
964
965 for (auto Feature : unifyTargetFeatures(Features)) {
966 CmdArgs.push_back(Elt: IsAux ? "-aux-target-feature" : "-target-feature");
967 CmdArgs.push_back(Elt: Feature.data());
968 }
969}
970
971llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
972 Arg *LtoJobsArg = Args.getLastArg(Ids: options::OPT_flto_jobs_EQ);
973 if (!LtoJobsArg)
974 return {};
975 if (!llvm::get_threadpool_strategy(Num: LtoJobsArg->getValue()))
976 D.Diag(DiagID: diag::err_drv_invalid_int_value)
977 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
978 return LtoJobsArg->getValue();
979}
980
981// PS4/PS5 uses -ffunction-sections and -fdata-sections by default.
982bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
983 return Triple.isPS();
984}
985
986void tools::addSeparateSectionFlags(const llvm::Triple &Triple,
987 const ArgList &Args,
988 ArgStringList &CmdArgs) {
989 bool UseSeparateSections = isUseSeparateSections(Triple);
990 if (Args.hasFlag(Pos: options::OPT_ffunction_sections,
991 Neg: options::OPT_fno_function_sections, Default: UseSeparateSections))
992 CmdArgs.push_back(Elt: "-ffunction-sections");
993
994 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
995 if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections,
996 Default: UseSeparateSections || HasDefaultDataSections))
997 CmdArgs.push_back(Elt: "-fdata-sections");
998}
999
1000bool tools::isTLSDESCEnabled(const ToolChain &TC,
1001 const llvm::opt::ArgList &Args) {
1002 const llvm::Triple &Triple = TC.getEffectiveTriple();
1003 Arg *A = Args.getLastArg(Ids: options::OPT_mtls_dialect_EQ);
1004 if (!A)
1005 return Triple.hasDefaultTLSDESC();
1006 StringRef V = A->getValue();
1007 bool SupportedArgument = false, EnableTLSDESC = false;
1008 bool Unsupported = !Triple.isOSBinFormatELF();
1009 if (Triple.isLoongArch() || Triple.isRISCV()) {
1010 SupportedArgument = V == "desc" || V == "trad";
1011 EnableTLSDESC = V == "desc";
1012 } else if (Triple.isX86()) {
1013 SupportedArgument = V == "gnu" || V == "gnu2";
1014 EnableTLSDESC = V == "gnu2";
1015 } else {
1016 Unsupported = true;
1017 }
1018 if (Unsupported) {
1019 TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1020 << A->getSpelling() << Triple.getTriple();
1021 } else if (!SupportedArgument) {
1022 TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument_for_target)
1023 << A->getSpelling() << V << Triple.getTriple();
1024 }
1025 return EnableTLSDESC;
1026}
1027
1028void tools::addDTLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
1029 llvm::opt::ArgStringList &CmdArgs) {
1030 if (Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_distributor_EQ)) {
1031 CmdArgs.push_back(
1032 Elt: Args.MakeArgString(Str: "--thinlto-distributor=" + Twine(A->getValue())));
1033 const Driver &D = ToolChain.getDriver();
1034 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--thinlto-remote-compiler=" +
1035 Twine(D.getDriverProgramPath())));
1036 if (auto *PA = D.getPrependArg())
1037 CmdArgs.push_back(Elt: Args.MakeArgString(
1038 Str: "--thinlto-remote-compiler-prepend-arg=" + Twine(PA)));
1039
1040 for (const auto &A :
1041 Args.getAllArgValues(Id: options::OPT_Xthinlto_distributor_EQ))
1042 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--thinlto-distributor-arg=" + A));
1043 }
1044}
1045
1046void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
1047 ArgStringList &CmdArgs, const InputInfo &Output,
1048 const InputInfoList &Inputs, bool IsThinLTO) {
1049 const llvm::Triple &Triple = ToolChain.getTriple();
1050 const bool IsOSAIX = Triple.isOSAIX();
1051 const bool IsAMDGCN = Triple.isAMDGCN();
1052 StringRef Linker = Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ);
1053 const char *LinkerPath = Args.MakeArgString(Str: ToolChain.GetLinkerPath());
1054 const Driver &D = ToolChain.getDriver();
1055 const bool IsFatLTO = Args.hasFlag(Pos: options::OPT_ffat_lto_objects,
1056 Neg: options::OPT_fno_fat_lto_objects, Default: false);
1057 const bool IsUnifiedLTO = Args.hasArg(Ids: options::OPT_funified_lto);
1058
1059 assert(!Inputs.empty() && "Must have at least one input.");
1060
1061 auto Input = llvm::find_if(
1062 Range: Inputs, P: [](const InputInfo &II) -> bool { return II.isFilename(); });
1063 if (Input == Inputs.end()) {
1064 // For a very rare case, all of the inputs to the linker are
1065 // InputArg. If that happens, just use the first InputInfo.
1066 Input = Inputs.begin();
1067 }
1068
1069 if (Linker != "lld" && Linker != "lld-link" &&
1070 llvm::sys::path::filename(path: LinkerPath) != "ld.lld" &&
1071 llvm::sys::path::stem(path: LinkerPath) != "ld.lld" && !Triple.isOSOpenBSD()) {
1072 // Tell the linker to load the plugin. This has to come before
1073 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
1074 // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
1075 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : "";
1076 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold";
1077
1078 if (!IsOSAIX)
1079 CmdArgs.push_back(Elt: "-plugin");
1080
1081#if defined(_WIN32)
1082 const char *Suffix = ".dll";
1083#elif defined(__APPLE__)
1084 const char *Suffix = ".dylib";
1085#else
1086 const char *Suffix = ".so";
1087#endif
1088
1089 SmallString<1024> Plugin;
1090 llvm::sys::path::native(path: Twine(D.Dir) +
1091 "/../" CLANG_INSTALL_LIBDIR_BASENAME +
1092 PluginName + Suffix,
1093 result&: Plugin);
1094 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginPrefix) + Plugin));
1095 } else {
1096 // Tell LLD to find and use .llvm.lto section in regular relocatable object
1097 // files
1098 if (IsFatLTO)
1099 CmdArgs.push_back(Elt: "--fat-lto-objects");
1100
1101 if (Args.hasArg(Ids: options::OPT_flto_partitions_EQ)) {
1102 int Value = 0;
1103 StringRef A = Args.getLastArgValue(Id: options::OPT_flto_partitions_EQ, Default: "8");
1104 if (A.getAsInteger(Radix: 10, Result&: Value) || (Value < 1)) {
1105 Arg *Arg = Args.getLastArg(Ids: options::OPT_flto_partitions_EQ);
1106 D.Diag(DiagID: diag::err_drv_invalid_int_value)
1107 << Arg->getAsString(Args) << Arg->getValue();
1108 }
1109 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--lto-partitions=" + A));
1110 }
1111 }
1112
1113 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
1114 const char *ExtraDash = IsOSAIX ? "-" : "";
1115 const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs=";
1116
1117 // Note, this solution is far from perfect, better to encode it into IR
1118 // metadata, but this may not be worth it, since it looks like aranges is on
1119 // the way out.
1120 if (Args.hasArg(Ids: options::OPT_gdwarf_aranges)) {
1121 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
1122 "-generate-arange-section"));
1123 }
1124
1125 // Pass vector library arguments to LTO.
1126 Arg *ArgVecLib = Args.getLastArg(Ids: options::OPT_fveclib);
1127 if (ArgVecLib && ArgVecLib->getNumValues() == 1) {
1128 // Map the vector library names from clang front-end to opt front-end. The
1129 // values are taken from the TargetLibraryInfo class command line options.
1130 std::optional<StringRef> OptVal =
1131 llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue())
1132 .Case(S: "Accelerate", Value: "Accelerate")
1133 .Case(S: "libmvec", Value: "LIBMVEC")
1134 .Case(S: "AMDLIBM", Value: "AMDLIBM")
1135 .Case(S: "MASSV", Value: "MASSV")
1136 .Case(S: "SVML", Value: "SVML")
1137 .Case(S: "SLEEF", Value: "sleefgnuabi")
1138 .Case(S: "Darwin_libsystem_m", Value: "Darwin_libsystem_m")
1139 .Case(S: "ArmPL", Value: "ArmPL")
1140 .Case(S: "none", Value: "none")
1141 .Default(Value: std::nullopt);
1142
1143 if (OptVal)
1144 CmdArgs.push_back(Elt: Args.MakeArgString(
1145 Str: Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value()));
1146 }
1147
1148 // Try to pass driver level flags relevant to LTO code generation down to
1149 // the plugin.
1150
1151 // Handle flags for selecting CPU variants.
1152 std::string CPU = getCPUName(D, Args, T: Triple);
1153 if (!CPU.empty())
1154 CmdArgs.push_back(
1155 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU));
1156
1157 if (Args.getLastArg(Ids: options::OPT_O_Group)) {
1158 unsigned OptimizationLevel =
1159 getOptimizationLevel(Args, IK: InputKind(), Diags&: D.getDiags());
1160 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash +
1161 "O" + Twine(OptimizationLevel)));
1162 if (IsAMDGCN)
1163 CmdArgs.push_back(
1164 Elt: Args.MakeArgString(Str: Twine("--lto-CGO") + Twine(OptimizationLevel)));
1165 }
1166
1167 if (Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
1168 SmallString<128> F;
1169 if (const Arg *A = Args.getLastArg(Ids: options::OPT_dumpdir)) {
1170 F = A->getValue();
1171 } else {
1172 F = Output.getFilename();
1173 F += "_";
1174 }
1175 CmdArgs.push_back(
1176 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "dwo_dir=" + F + "dwo"));
1177 }
1178
1179 if (IsThinLTO && !IsOSAIX)
1180 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "thinlto"));
1181 else if (IsThinLTO && IsOSAIX)
1182 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-bdbg:thinlto")));
1183
1184 // Matrix intrinsic lowering happens at link time with ThinLTO. Enable
1185 // LowerMatrixIntrinsicsPass, which is transitively called by
1186 // buildThinLTODefaultPipeline under EnableMatrix.
1187 if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) &&
1188 Args.hasArg(Ids: options::OPT_fenable_matrix))
1189 CmdArgs.push_back(
1190 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-enable-matrix"));
1191
1192 StringRef Parallelism = getLTOParallelism(Args, D);
1193 if (!Parallelism.empty())
1194 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
1195 ParallelismOpt + Parallelism));
1196
1197 // Forward the SLP vectorization preference to the LTO backend by toggling
1198 // the existing -vectorize-slp cl::opt, which the pass honors directly. This
1199 // avoids minting dedicated linker options for what is only pipeline tuning.
1200 if (Arg *A = Args.getLastArg(Ids: options::OPT_fslp_vectorize,
1201 Ids: options::OPT_fno_slp_vectorize))
1202 CmdArgs.push_back(Elt: Args.MakeArgString(
1203 Str: Twine(PluginOptPrefix) + "-vectorize-slp=" +
1204 (A->getOption().matches(ID: options::OPT_fslp_vectorize) ? "1" : "0")));
1205
1206 // Pass down GlobalISel options.
1207 if (Arg *A = Args.getLastArg(Ids: options::OPT_fglobal_isel,
1208 Ids: options::OPT_fno_global_isel)) {
1209 // Parsing -fno-global-isel explicitly gives architectures that enable GISel
1210 // by default a chance to disable it.
1211 CmdArgs.push_back(Elt: Args.MakeArgString(
1212 Str: Twine(PluginOptPrefix) + "-global-isel=" +
1213 (A->getOption().matches(ID: options::OPT_fglobal_isel) ? "1" : "0")));
1214 }
1215
1216 // If an explicit debugger tuning argument appeared, pass it along.
1217 if (Arg *A =
1218 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
1219 if (A->getOption().matches(ID: options::OPT_glldb))
1220 CmdArgs.push_back(
1221 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=lldb"));
1222 else if (A->getOption().matches(ID: options::OPT_gsce))
1223 CmdArgs.push_back(
1224 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=sce"));
1225 else if (A->getOption().matches(ID: options::OPT_gdbx))
1226 CmdArgs.push_back(
1227 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=dbx"));
1228 else
1229 CmdArgs.push_back(
1230 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=gdb"));
1231 }
1232
1233 if (IsOSAIX) {
1234 if (!ToolChain.useIntegratedAs())
1235 CmdArgs.push_back(
1236 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-no-integrated-as=1"));
1237
1238 // On AIX, clang assumes strict-dwarf is true if any debug option is
1239 // specified, unless it is told explicitly not to assume so.
1240 Arg *A = Args.getLastArg(Ids: options::OPT_g_Group);
1241 bool EnableDebugInfo = A && !A->getOption().matches(ID: options::OPT_g0) &&
1242 !A->getOption().matches(ID: options::OPT_ggdb0);
1243 if (EnableDebugInfo && Args.hasFlag(Pos: options::OPT_gstrict_dwarf,
1244 Neg: options::OPT_gno_strict_dwarf, Default: true))
1245 CmdArgs.push_back(
1246 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-strict-dwarf=true"));
1247
1248 for (const Arg *A : Args.filtered_reverse(Ids: options::OPT_mabi_EQ)) {
1249 StringRef V = A->getValue();
1250 if (V == "vec-default")
1251 break;
1252 if (V == "vec-extabi") {
1253 CmdArgs.push_back(
1254 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-vec-extabi"));
1255 break;
1256 }
1257 }
1258 }
1259
1260 bool UseSeparateSections =
1261 isUseSeparateSections(Triple: ToolChain.getEffectiveTriple());
1262
1263 if (Args.hasFlag(Pos: options::OPT_ffunction_sections,
1264 Neg: options::OPT_fno_function_sections, Default: UseSeparateSections))
1265 CmdArgs.push_back(
1266 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-function-sections=1"));
1267 else if (Args.hasArg(Ids: options::OPT_fno_function_sections))
1268 CmdArgs.push_back(
1269 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-function-sections=0"));
1270
1271 bool DataSectionsTurnedOff = false;
1272 if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections,
1273 Default: UseSeparateSections)) {
1274 CmdArgs.push_back(
1275 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-data-sections=1"));
1276 } else if (Args.hasArg(Ids: options::OPT_fno_data_sections)) {
1277 DataSectionsTurnedOff = true;
1278 CmdArgs.push_back(
1279 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-data-sections=0"));
1280 }
1281
1282 if (Args.hasArg(Ids: options::OPT_mxcoff_roptr) ||
1283 Args.hasArg(Ids: options::OPT_mno_xcoff_roptr)) {
1284 bool HasRoptr = Args.hasFlag(Pos: options::OPT_mxcoff_roptr,
1285 Neg: options::OPT_mno_xcoff_roptr, Default: false);
1286 StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr";
1287 if (!IsOSAIX)
1288 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1289 << OptStr << Triple.str();
1290
1291 if (HasRoptr) {
1292 // The data sections option is on by default on AIX. We only need to error
1293 // out when -fno-data-sections is specified explicitly to turn off data
1294 // sections.
1295 if (DataSectionsTurnedOff)
1296 D.Diag(DiagID: diag::err_roptr_requires_data_sections);
1297
1298 CmdArgs.push_back(
1299 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-mxcoff-roptr"));
1300 }
1301 }
1302
1303 // Pass an option to enable split machine functions.
1304 if (auto *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
1305 Ids: options::OPT_fno_split_machine_functions)) {
1306 if (A->getOption().matches(ID: options::OPT_fsplit_machine_functions))
1307 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
1308 "-split-machine-functions"));
1309 }
1310
1311 if (auto *A =
1312 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
1313 Ids: options::OPT_fno_partition_static_data_sections)) {
1314 if (A->getOption().matches(ID: options::OPT_fpartition_static_data_sections)) {
1315 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
1316 "-partition-static-data-sections"));
1317 }
1318 }
1319
1320 if (Arg *A = getLastProfileSampleUseArg(Args)) {
1321 StringRef FName = A->getValue();
1322 if (!llvm::sys::fs::exists(Path: FName))
1323 D.Diag(DiagID: diag::err_drv_no_such_file) << FName;
1324 else
1325 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
1326 "sample-profile=" + FName));
1327 }
1328
1329 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
1330 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash +
1331 "cs-profile-generate"));
1332 if (CSPGOGenerateArg->getOption().matches(
1333 ID: options::OPT_fcs_profile_generate_EQ)) {
1334 SmallString<128> Path(CSPGOGenerateArg->getValue());
1335 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
1336 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash +
1337 "cs-profile-path=" + Path));
1338 } else
1339 CmdArgs.push_back(
1340 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash +
1341 "cs-profile-path=default_%m.profraw"));
1342 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
1343 SmallString<128> Path(
1344 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
1345 if (Path.empty() || llvm::sys::fs::is_directory(Path))
1346 llvm::sys::path::append(path&: Path, a: "default.profdata");
1347 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash +
1348 "cs-profile-path=" + Path));
1349 }
1350
1351 // This controls whether or not we perform JustMyCode instrumentation.
1352 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
1353 if (ToolChain.getEffectiveTriple().isOSBinFormatELF())
1354 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) +
1355 "-enable-jmc-instrument"));
1356 else
1357 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
1358 }
1359
1360 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
1361 Default: Triple.hasDefaultEmulatedTLS())) {
1362 CmdArgs.push_back(
1363 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-emulated-tls"));
1364 }
1365 if (isTLSDESCEnabled(TC: ToolChain, Args))
1366 CmdArgs.push_back(
1367 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-enable-tlsdesc"));
1368
1369 if (Args.hasFlag(Pos: options::OPT_fstack_size_section,
1370 Neg: options::OPT_fno_stack_size_section, Default: false))
1371 CmdArgs.push_back(
1372 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-stack-size-section"));
1373
1374 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
1375 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
1376 CmdArgs.push_back(
1377 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-call-graph-section"));
1378
1379 // Setup statistics file output.
1380 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input: *Input, D);
1381 if (!StatsFile.empty())
1382 CmdArgs.push_back(
1383 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "stats-file=" + StatsFile));
1384
1385 // Setup crash diagnostics dir.
1386 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcrash_diagnostics_dir))
1387 CmdArgs.push_back(Elt: Args.MakeArgString(
1388 Str: Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue()));
1389
1390 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix);
1391
1392 // Handle remark diagnostics on screen options: '-Rpass-*'.
1393 renderRpassOptions(Args, CmdArgs, PluginOptPrefix);
1394
1395 // Handle serialized remarks options: '-fsave-optimization-record'
1396 // and '-foptimization-record-*'.
1397 if (willEmitRemarks(Args))
1398 renderRemarksOptions(Args, CmdArgs, Triple: ToolChain.getEffectiveTriple(), Input: *Input,
1399 Output, PluginOptPrefix);
1400
1401 // Handle remarks hotness/threshold related options.
1402 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix);
1403
1404 addMachineOutlinerArgs(D, Args, CmdArgs, Triple: ToolChain.getEffectiveTriple(),
1405 /*IsLTO=*/true, PluginOptPrefix);
1406
1407 bool IsELF = Triple.isOSBinFormatELF();
1408 bool Crel = false;
1409 bool ImplicitMapSyms = false;
1410 for (const Arg *A : Args.filtered(Ids: options::OPT_Wa_COMMA)) {
1411 for (StringRef V : A->getValues()) {
1412 auto Equal = V.split(Separator: '=');
1413 auto checkArg = [&](bool ValidTarget,
1414 std::initializer_list<const char *> Set) {
1415 if (!ValidTarget) {
1416 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1417 << (Twine("-Wa,") + Equal.first + "=").str()
1418 << Triple.getTriple();
1419 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
1420 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1421 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
1422 }
1423 };
1424 if (Equal.first == "-mmapsyms") {
1425 ImplicitMapSyms = Equal.second == "implicit";
1426 checkArg(IsELF && Triple.isAArch64(), {"default", "implicit"});
1427 } else if (V == "--crel")
1428 Crel = true;
1429 else if (V == "--no-crel")
1430 Crel = false;
1431 else
1432 continue;
1433 A->claim();
1434 }
1435 }
1436 if (Crel) {
1437 if (IsELF && !Triple.isMIPS()) {
1438 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-crel"));
1439 } else {
1440 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1441 << "-Wa,--crel" << D.getTargetTriple();
1442 }
1443 }
1444 if (ImplicitMapSyms)
1445 CmdArgs.push_back(
1446 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-implicit-mapsyms"));
1447
1448 if (Args.hasArg(Ids: options::OPT_ftime_report))
1449 CmdArgs.push_back(
1450 Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-time-passes"));
1451
1452 addDTLTOOptions(ToolChain, Args, CmdArgs);
1453}
1454
1455void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
1456 const ArgList &Args,
1457 ArgStringList &CmdArgs) {
1458 // Default to clang lib / lib64 folder, i.e. the same location as device
1459 // runtime.
1460 SmallString<256> DefaultLibPath =
1461 llvm::sys::path::parent_path(path: TC.getDriver().Dir);
1462 llvm::sys::path::append(path&: DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
1463 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-L" + DefaultLibPath));
1464}
1465
1466void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
1467 ArgStringList &CmdArgs) {
1468 if (!Args.hasFlag(Pos: options::OPT_frtlib_add_rpath,
1469 Neg: options::OPT_fno_rtlib_add_rpath, Default: false))
1470 return;
1471
1472 if (TC.getTriple().isOSAIX()) // TODO: AIX doesn't support -rpath option.
1473 return;
1474
1475 SmallVector<std::string> CandidateRPaths(TC.getArchSpecificLibPaths());
1476 if (const auto StdlibPath = TC.getStdlibPath()) {
1477 for (const Multilib &M : llvm::reverse(C: TC.getSelectedMultilibs())) {
1478 if (M.isDefault())
1479 continue;
1480 SmallString<128> P(*StdlibPath);
1481 llvm::sys::path::append(path&: P, a: M.gccSuffix());
1482 CandidateRPaths.emplace_back(Args: std::string(P));
1483 }
1484 CandidateRPaths.emplace_back(Args: *StdlibPath);
1485 }
1486 for (const auto &CandidateRPath : CandidateRPaths) {
1487 if (TC.getVFS().exists(Path: CandidateRPath)) {
1488 CmdArgs.push_back(Elt: "-rpath");
1489 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CandidateRPath));
1490 }
1491 }
1492}
1493
1494bool tools::addLLVMOffloadingRuntime(const Compilation &C,
1495 ArgStringList &CmdArgs,
1496 const ToolChain &TC, const ArgList &Args) {
1497
1498 if (!Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
1499 Neg: options::OPT_fno_offload_via_llvm, Default: false))
1500 return false;
1501
1502 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fgpu_default_stream_EQ);
1503 A && StringRef(A->getValue()) == "per-thread")
1504 CmdArgs.push_back(Elt: Args.MakeArgString(
1505 Str: TC.GetFilePath(Name: "LLVMOffloadKernelPerThreadDefaultStream.o")));
1506
1507 CmdArgs.push_back(Elt: "-lLLVMOffloadKernel");
1508 return true;
1509}
1510
1511bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs,
1512 const ToolChain &TC, const ArgList &Args,
1513 bool ForceStaticHostRuntime, bool IsOffloadingHost,
1514 bool GompNeedsRT) {
1515 if (!Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
1516 Neg: options::OPT_fno_openmp, Default: false))
1517 return false;
1518
1519 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
1520
1521 if (RTKind == Driver::OMPRT_Unknown)
1522 // Already diagnosed.
1523 return false;
1524
1525 if (ForceStaticHostRuntime)
1526 CmdArgs.push_back(Elt: "-Bstatic");
1527
1528 switch (RTKind) {
1529 case Driver::OMPRT_OMP:
1530 CmdArgs.push_back(Elt: "-lomp");
1531 break;
1532 case Driver::OMPRT_GOMP:
1533 CmdArgs.push_back(Elt: "-lgomp");
1534 break;
1535 case Driver::OMPRT_IOMP5:
1536 CmdArgs.push_back(Elt: "-liomp5");
1537 break;
1538 case Driver::OMPRT_Unknown:
1539 break;
1540 }
1541
1542 if (ForceStaticHostRuntime)
1543 CmdArgs.push_back(Elt: "-Bdynamic");
1544
1545 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
1546 CmdArgs.push_back(Elt: "-lrt");
1547
1548 if (IsOffloadingHost)
1549 CmdArgs.push_back(Elt: "-lomptarget");
1550
1551 addArchSpecificRPath(TC, Args, CmdArgs);
1552
1553 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
1554
1555 return true;
1556}
1557
1558void tools::addOpenMPHostOffloadingArgs(const Compilation &C,
1559 const JobAction &JA,
1560 const llvm::opt::ArgList &Args,
1561 llvm::opt::ArgStringList &CmdArgs) {
1562 if (!JA.isHostOffloading(OKind: Action::OFK_OpenMP))
1563 return;
1564
1565 // For all the host OpenMP offloading compile jobs we need to pass the targets
1566 // information using -fopenmp-targets= option.
1567 constexpr llvm::StringLiteral Targets("--offload-targets=");
1568
1569 SmallVector<StringRef> Triples;
1570 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
1571 std::transform(first: TCRange.first, last: TCRange.second, result: std::back_inserter(x&: Triples),
1572 unary_op: [](auto TC) { return TC.second->getTripleString(); });
1573 CmdArgs.push_back(
1574 Elt: Args.MakeArgString(Str: Twine(Targets) + llvm::join(R&: Triples, Separator: ",")));
1575}
1576
1577static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
1578 ArgStringList &CmdArgs, StringRef Sanitizer,
1579 bool IsShared, bool IsWhole) {
1580 // Wrap any static runtimes that must be forced into executable in
1581 // whole-archive.
1582 if (IsWhole) CmdArgs.push_back(Elt: "--whole-archive");
1583 CmdArgs.push_back(Elt: TC.getCompilerRTArgString(
1584 Args, Component: Sanitizer, Type: IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
1585 if (IsWhole) CmdArgs.push_back(Elt: "--no-whole-archive");
1586
1587 if (IsShared) {
1588 addArchSpecificRPath(TC, Args, CmdArgs);
1589 }
1590}
1591
1592// Tries to use a file with the list of dynamic symbols that need to be exported
1593// from the runtime library. Returns true if the file was found.
1594static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
1595 ArgStringList &CmdArgs,
1596 StringRef Sanitizer) {
1597 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1598
1599 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
1600 // the option, so don't try to pass it.
1601 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd)
1602 return true;
1603 SmallString<128> SanRT(TC.getCompilerRT(Args, Component: Sanitizer));
1604 if (llvm::sys::fs::exists(Path: SanRT + ".syms")) {
1605 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--dynamic-list=" + SanRT + ".syms"));
1606 return true;
1607 }
1608 return false;
1609}
1610
1611void tools::addAsNeededOption(const ToolChain &TC,
1612 const llvm::opt::ArgList &Args,
1613 llvm::opt::ArgStringList &CmdArgs,
1614 bool as_needed) {
1615 assert(!TC.getTriple().isOSAIX() &&
1616 "AIX linker does not support any form of --as-needed option yet.");
1617 bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args);
1618
1619 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
1620 // for the native forms -z ignore/-z record, they are missing in Illumos,
1621 // so always use the native form.
1622 // GNU ld doesn't support -z ignore/-z record, so don't use them even on
1623 // Solaris.
1624 if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) {
1625 CmdArgs.push_back(Elt: "-z");
1626 CmdArgs.push_back(Elt: as_needed ? "ignore" : "record");
1627 } else {
1628 CmdArgs.push_back(Elt: as_needed ? "--as-needed" : "--no-as-needed");
1629 }
1630}
1631
1632void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
1633 const llvm::opt::ArgList &Args,
1634 ArgStringList &CmdArgs) {
1635 // Force linking against the system libraries sanitizers depends on
1636 // (see PR15823 why this is necessary).
1637 addAsNeededOption(TC, Args, CmdArgs, as_needed: false);
1638 // There's no libpthread or librt on RTEMS & Android.
1639 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
1640 !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) {
1641 CmdArgs.push_back(Elt: "-lpthread");
1642 if (!TC.getTriple().isOSOpenBSD() && !TC.getTriple().isOSHaiku())
1643 CmdArgs.push_back(Elt: "-lrt");
1644 }
1645 CmdArgs.push_back(Elt: "-lm");
1646 // There's no libdl on all OSes.
1647 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
1648 !TC.getTriple().isOSOpenBSD() && !TC.getTriple().isOSDragonFly() &&
1649 !TC.getTriple().isOSHaiku() &&
1650 TC.getTriple().getOS() != llvm::Triple::RTEMS)
1651 CmdArgs.push_back(Elt: "-ldl");
1652 // Required for backtrace on some OSes
1653 if (TC.getTriple().isOSFreeBSD() || TC.getTriple().isOSNetBSD() ||
1654 TC.getTriple().isOSOpenBSD() || TC.getTriple().isOSDragonFly())
1655 CmdArgs.push_back(Elt: "-lexecinfo");
1656 if (TC.getTriple().isOSHaiku())
1657 CmdArgs.push_back(Elt: "-lbsd");
1658 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
1659 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
1660 // requirement.
1661 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
1662 !TC.getTriple().isMusl())
1663 CmdArgs.push_back(Elt: "-lresolv");
1664}
1665
1666static void
1667collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1668 SmallVectorImpl<StringRef> &SharedRuntimes,
1669 SmallVectorImpl<StringRef> &StaticRuntimes,
1670 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
1671 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
1672 SmallVectorImpl<StringRef> &RequiredSymbols) {
1673 assert(!TC.getTriple().isOSDarwin() && "it's not used by Darwin");
1674 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(JobArgs: Args);
1675 // Collect shared runtimes.
1676 if (SanArgs.needsSharedRt()) {
1677 if (SanArgs.needsAsanRt()) {
1678 SharedRuntimes.push_back(Elt: "asan");
1679 if (!Args.hasArg(Ids: options::OPT_shared) && !TC.getTriple().isAndroid())
1680 HelperStaticRuntimes.push_back(Elt: "asan-preinit");
1681 }
1682 if (SanArgs.needsMemProfRt()) {
1683 SharedRuntimes.push_back(Elt: "memprof");
1684 if (!Args.hasArg(Ids: options::OPT_shared) && !TC.getTriple().isAndroid())
1685 HelperStaticRuntimes.push_back(Elt: "memprof-preinit");
1686 }
1687 if (SanArgs.needsNsanRt())
1688 SharedRuntimes.push_back(Elt: "nsan");
1689 if (SanArgs.needsUbsanRt()) {
1690 if (SanArgs.requiresMinimalRuntime())
1691 SharedRuntimes.push_back(Elt: "ubsan_minimal");
1692 else
1693 SharedRuntimes.push_back(Elt: "ubsan_standalone");
1694 }
1695 if (SanArgs.needsScudoRt()) {
1696 SharedRuntimes.push_back(Elt: "scudo_standalone");
1697 }
1698 if (SanArgs.needsTsanRt())
1699 SharedRuntimes.push_back(Elt: "tsan");
1700 if (SanArgs.needsTysanRt())
1701 SharedRuntimes.push_back(Elt: "tysan");
1702 if (SanArgs.needsHwasanRt()) {
1703 if (SanArgs.needsHwasanAliasesRt())
1704 SharedRuntimes.push_back(Elt: "hwasan_aliases");
1705 else
1706 SharedRuntimes.push_back(Elt: "hwasan");
1707 if (!Args.hasArg(Ids: options::OPT_shared))
1708 HelperStaticRuntimes.push_back(Elt: "hwasan-preinit");
1709 }
1710 if (SanArgs.needsRtsanRt() && SanArgs.linkRuntimes())
1711 SharedRuntimes.push_back(Elt: "rtsan");
1712 }
1713
1714 // The stats_client library is also statically linked into DSOs.
1715 if (SanArgs.needsStatsRt())
1716 StaticRuntimes.push_back(Elt: "stats_client");
1717
1718 // Always link the static runtime regardless of DSO or executable.
1719 if (SanArgs.needsAsanRt())
1720 HelperStaticRuntimes.push_back(Elt: "asan_static");
1721
1722 // Collect static runtimes.
1723 if (Args.hasArg(Ids: options::OPT_shared)) {
1724 // Don't link static runtimes into DSOs.
1725 return;
1726 }
1727
1728 // Each static runtime that has a DSO counterpart above is excluded below,
1729 // but runtimes that exist only as static are not affected by needsSharedRt.
1730
1731 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) {
1732 StaticRuntimes.push_back(Elt: "asan");
1733 if (SanArgs.linkCXXRuntimes())
1734 StaticRuntimes.push_back(Elt: "asan_cxx");
1735 }
1736
1737 if (!SanArgs.needsSharedRt() && SanArgs.needsRtsanRt() &&
1738 SanArgs.linkRuntimes())
1739 StaticRuntimes.push_back(Elt: "rtsan");
1740
1741 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) {
1742 StaticRuntimes.push_back(Elt: "memprof");
1743 if (SanArgs.linkCXXRuntimes())
1744 StaticRuntimes.push_back(Elt: "memprof_cxx");
1745 }
1746
1747 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) {
1748 if (SanArgs.needsHwasanAliasesRt()) {
1749 StaticRuntimes.push_back(Elt: "hwasan_aliases");
1750 if (SanArgs.linkCXXRuntimes())
1751 StaticRuntimes.push_back(Elt: "hwasan_aliases_cxx");
1752 } else {
1753 StaticRuntimes.push_back(Elt: "hwasan");
1754 if (SanArgs.linkCXXRuntimes())
1755 StaticRuntimes.push_back(Elt: "hwasan_cxx");
1756 }
1757 }
1758 if (SanArgs.needsDfsanRt())
1759 StaticRuntimes.push_back(Elt: "dfsan");
1760 if (SanArgs.needsLsanRt())
1761 StaticRuntimes.push_back(Elt: "lsan");
1762 if (SanArgs.needsMsanRt()) {
1763 StaticRuntimes.push_back(Elt: "msan");
1764 if (SanArgs.linkCXXRuntimes())
1765 StaticRuntimes.push_back(Elt: "msan_cxx");
1766 }
1767 if (!SanArgs.needsSharedRt() && SanArgs.needsNsanRt())
1768 StaticRuntimes.push_back(Elt: "nsan");
1769 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) {
1770 StaticRuntimes.push_back(Elt: "tsan");
1771 if (SanArgs.linkCXXRuntimes())
1772 StaticRuntimes.push_back(Elt: "tsan_cxx");
1773 }
1774 if (!SanArgs.needsSharedRt() && SanArgs.needsTysanRt())
1775 StaticRuntimes.push_back(Elt: "tysan");
1776 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) {
1777 if (SanArgs.requiresMinimalRuntime()) {
1778 StaticRuntimes.push_back(Elt: "ubsan_minimal");
1779 } else {
1780 StaticRuntimes.push_back(Elt: "ubsan_standalone");
1781 }
1782 }
1783 if (SanArgs.needsSafeStackRt()) {
1784 NonWholeStaticRuntimes.push_back(Elt: "safestack");
1785 RequiredSymbols.push_back(Elt: "__safestack_init");
1786 }
1787 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) {
1788 if (SanArgs.needsCfiCrossDsoRt())
1789 StaticRuntimes.push_back(Elt: "cfi");
1790 if (SanArgs.needsCfiCrossDsoDiagRt())
1791 StaticRuntimes.push_back(Elt: "cfi_diag");
1792 }
1793 if (SanArgs.linkCXXRuntimes() && !SanArgs.requiresMinimalRuntime() &&
1794 ((!SanArgs.needsSharedRt() && SanArgs.needsUbsanCXXRt()) ||
1795 SanArgs.needsCfiCrossDsoDiagRt())) {
1796 StaticRuntimes.push_back(Elt: "ubsan_standalone_cxx");
1797 }
1798 if (SanArgs.needsStatsRt()) {
1799 NonWholeStaticRuntimes.push_back(Elt: "stats");
1800 RequiredSymbols.push_back(Elt: "__sanitizer_stats_register");
1801 }
1802 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) {
1803 StaticRuntimes.push_back(Elt: "scudo_standalone");
1804 if (SanArgs.linkCXXRuntimes())
1805 StaticRuntimes.push_back(Elt: "scudo_standalone_cxx");
1806 }
1807 if (SanArgs.needsUbsanLoopDetectRt())
1808 NonWholeStaticRuntimes.push_back(Elt: "ubsan_loop_detect");
1809}
1810
1811// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1812// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
1813bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1814 ArgStringList &CmdArgs) {
1815 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(JobArgs: Args);
1816 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1817 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1818 if (SanArgs.linkRuntimes()) {
1819 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1820 NonWholeStaticRuntimes, HelperStaticRuntimes,
1821 RequiredSymbols);
1822 }
1823
1824 // -u options must be added before the runtime libs that resolve them.
1825 for (auto S : RequiredSymbols) {
1826 CmdArgs.push_back(Elt: "-u");
1827 CmdArgs.push_back(Elt: Args.MakeArgString(Str: S));
1828 }
1829
1830 // Add shared runtimes before adding fuzzer and its dependencies.
1831 for (auto RT : SharedRuntimes)
1832 addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: true, IsWhole: false);
1833
1834 // Inject libfuzzer dependencies.
1835 bool FuzzerNeedsSanitizerDeps = false;
1836 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1837 !Args.hasArg(Ids: options::OPT_shared)) {
1838
1839 addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: "fuzzer", IsShared: false, IsWhole: true);
1840 FuzzerNeedsSanitizerDeps = true;
1841 if (SanArgs.needsFuzzerInterceptors())
1842 addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: "fuzzer_interceptors", IsShared: false,
1843 IsWhole: true);
1844 if (!Args.hasArg(Ids: options::OPT_nostdlibxx)) {
1845 bool OnlyLibstdcxxStatic = Args.hasArg(Ids: options::OPT_static_libstdcxx) &&
1846 !Args.hasArg(Ids: options::OPT_static);
1847 if (OnlyLibstdcxxStatic)
1848 CmdArgs.push_back(Elt: "-Bstatic");
1849 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1850 if (OnlyLibstdcxxStatic)
1851 CmdArgs.push_back(Elt: "-Bdynamic");
1852 }
1853 }
1854
1855 for (auto RT : HelperStaticRuntimes)
1856 addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: false, IsWhole: true);
1857 bool AddExportDynamic = false;
1858 for (auto RT : StaticRuntimes) {
1859 addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: false, IsWhole: true);
1860 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, Sanitizer: RT);
1861 }
1862 for (auto RT : NonWholeStaticRuntimes) {
1863 addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: false, IsWhole: false);
1864 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, Sanitizer: RT);
1865 }
1866 // If there is a static runtime with no dynamic list, force all the symbols
1867 // to be dynamic to be sure we export sanitizer interface functions.
1868 if (AddExportDynamic && !TC.getTriple().isNVPTX())
1869 CmdArgs.push_back(Elt: "--export-dynamic");
1870
1871 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1872 CmdArgs.push_back(Elt: "--export-dynamic-symbol=__cfi_check");
1873
1874 if (SanArgs.hasMemTag()) {
1875 CmdArgs.push_back(Elt: "-z");
1876 CmdArgs.push_back(
1877 Elt: Args.MakeArgString(Str: "memtag-mode=" + SanArgs.getMemtagMode()));
1878
1879 if (SanArgs.hasMemtagHeap()) {
1880 CmdArgs.push_back(Elt: "-z");
1881 CmdArgs.push_back(Elt: "memtag-heap");
1882 }
1883
1884 if (SanArgs.hasMemtagStack()) {
1885 CmdArgs.push_back(Elt: "-z");
1886 CmdArgs.push_back(Elt: "memtag-stack");
1887 }
1888
1889 if (TC.getTriple().isAndroid())
1890 CmdArgs.push_back(Elt: "--android-memtag-note");
1891 }
1892
1893 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty() ||
1894 FuzzerNeedsSanitizerDeps;
1895}
1896
1897bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1898 const XRayArgs &XRay = TC.getXRayArgs(Args);
1899 if (Args.hasArg(Ids: options::OPT_shared)) {
1900 if (XRay.needsXRayDSORt()) {
1901 CmdArgs.push_back(Elt: "--whole-archive");
1902 CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "xray-dso"));
1903 CmdArgs.push_back(Elt: "--no-whole-archive");
1904 return true;
1905 }
1906 } else if (XRay.needsXRayRt()) {
1907 CmdArgs.push_back(Elt: "--whole-archive");
1908 CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "xray"));
1909 for (const auto &Mode : XRay.modeList())
1910 CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: Mode));
1911 CmdArgs.push_back(Elt: "--no-whole-archive");
1912 return true;
1913 }
1914
1915 return false;
1916}
1917
1918void tools::linkXRayRuntimeDeps(const ToolChain &TC,
1919 const llvm::opt::ArgList &Args,
1920 ArgStringList &CmdArgs) {
1921 addAsNeededOption(TC, Args, CmdArgs, as_needed: false);
1922 CmdArgs.push_back(Elt: "-lpthread");
1923 if (!TC.getTriple().isOSOpenBSD())
1924 CmdArgs.push_back(Elt: "-lrt");
1925 CmdArgs.push_back(Elt: "-lm");
1926
1927 if (!TC.getTriple().isOSFreeBSD() &&
1928 !TC.getTriple().isOSNetBSD() &&
1929 !TC.getTriple().isOSOpenBSD())
1930 CmdArgs.push_back(Elt: "-ldl");
1931}
1932
1933bool tools::areOptimizationsEnabled(const ArgList &Args) {
1934 // Find the last -O arg and see if it is non-zero.
1935 if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group))
1936 return !A->getOption().matches(ID: options::OPT_O0);
1937 // Defaults to -O0.
1938 return false;
1939}
1940
1941const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1942 const InputInfo &Input,
1943 const InputInfo &Output) {
1944 auto AddPostfix = [JA](auto &F) {
1945 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1946 F += (Twine("_") + JA.getOffloadingArch().ArchName).str();
1947 F += ".dwo";
1948 };
1949 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsplit_dwarf_EQ))
1950 if (StringRef(A->getValue()) == "single" && Output.isFilename())
1951 return Args.MakeArgString(Str: Output.getFilename());
1952
1953 SmallString<128> T;
1954 if (const Arg *A = Args.getLastArg(Ids: options::OPT_dumpdir)) {
1955 T = A->getValue();
1956 } else {
1957 if (Args.hasArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_o,
1958 Ids: options::OPT__SLASH_Fo) &&
1959 Args.hasArg(Ids: options::OPT_c) && Output.isFilename()) {
1960 // The driver has resolved /Fo<dir>/ into a concrete obj path in Output.
1961 StringRef Obj = Output.getFilename();
1962 T = Obj;
1963 llvm::sys::path::remove_filename(path&: T);
1964 llvm::sys::path::append(path&: T, a: llvm::sys::path::stem(path: Obj));
1965 AddPostfix(T);
1966 return Args.MakeArgString(Str: T);
1967 }
1968 }
1969
1970 T += llvm::sys::path::stem(path: Input.getBaseInput());
1971 AddPostfix(T);
1972 return Args.MakeArgString(Str: T);
1973}
1974
1975void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1976 const JobAction &JA, const ArgList &Args,
1977 const InputInfo &Output, const char *OutFile) {
1978 ArgStringList ExtractArgs;
1979 ExtractArgs.push_back(Elt: "--extract-dwo");
1980
1981 ArgStringList StripArgs;
1982 StripArgs.push_back(Elt: "--strip-dwo");
1983
1984 // Grabbing the output of the earlier compile step.
1985 StripArgs.push_back(Elt: Output.getFilename());
1986 ExtractArgs.push_back(Elt: Output.getFilename());
1987 ExtractArgs.push_back(Elt: OutFile);
1988
1989 const char *Exec =
1990 Args.MakeArgString(Str: TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1991 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1992
1993 // First extract the dwo sections.
1994 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: T,
1995 args: ResponseFileSupport::AtFileCurCP(),
1996 args&: Exec, args&: ExtractArgs, args&: II, args: Output));
1997
1998 // Then remove them from the original .o file.
1999 C.addCommand(Cmd: std::make_unique<Command>(
2000 args: JA, args: T, args: ResponseFileSupport::AtFileCurCP(), args&: Exec, args&: StripArgs, args&: II, args: Output));
2001}
2002
2003// Claim options we don't want to warn if they are unused. We do this for
2004// options that build systems might add but are unused when assembling or only
2005// running the preprocessor for example.
2006void tools::claimNoWarnArgs(const ArgList &Args) {
2007 // Don't warn about unused -f(no-)?lto. This can happen when we're
2008 // preprocessing, precompiling or assembling.
2009 Args.ClaimAllArgs(Id0: options::OPT_flto_EQ);
2010 Args.ClaimAllArgs(Id0: options::OPT_flto);
2011 Args.ClaimAllArgs(Id0: options::OPT_fno_lto);
2012}
2013
2014Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) {
2015 auto *CSPGOGenerateArg = Args.getLastArg(Ids: options::OPT_fcs_profile_generate,
2016 Ids: options::OPT_fcs_profile_generate_EQ,
2017 Ids: options::OPT_fno_profile_generate);
2018 if (CSPGOGenerateArg &&
2019 CSPGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
2020 CSPGOGenerateArg = nullptr;
2021
2022 return CSPGOGenerateArg;
2023}
2024
2025Arg *tools::getLastProfileUseArg(const ArgList &Args) {
2026 auto *ProfileUseArg = Args.getLastArg(
2027 Ids: options::OPT_fprofile_instr_use, Ids: options::OPT_fprofile_instr_use_EQ,
2028 Ids: options::OPT_fprofile_use, Ids: options::OPT_fprofile_use_EQ,
2029 Ids: options::OPT_fno_profile_instr_use);
2030
2031 if (ProfileUseArg &&
2032 ProfileUseArg->getOption().matches(ID: options::OPT_fno_profile_instr_use))
2033 ProfileUseArg = nullptr;
2034
2035 return ProfileUseArg;
2036}
2037
2038Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
2039 auto *ProfileSampleUseArg = Args.getLastArg(
2040 Ids: options::OPT_fprofile_sample_use_EQ, Ids: options::OPT_fno_profile_sample_use);
2041
2042 if (ProfileSampleUseArg && (ProfileSampleUseArg->getOption().matches(
2043 ID: options::OPT_fno_profile_sample_use)))
2044 return nullptr;
2045
2046 return Args.getLastArg(Ids: options::OPT_fprofile_sample_use_EQ);
2047}
2048
2049const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
2050 switch (Model) {
2051 case llvm::Reloc::Static:
2052 return "static";
2053 case llvm::Reloc::PIC_:
2054 return "pic";
2055 case llvm::Reloc::DynamicNoPIC:
2056 return "dynamic-no-pic";
2057 case llvm::Reloc::ROPI:
2058 return "ropi";
2059 case llvm::Reloc::RWPI:
2060 return "rwpi";
2061 case llvm::Reloc::ROPI_RWPI:
2062 return "ropi-rwpi";
2063 }
2064 llvm_unreachable("Unknown Reloc::Model kind");
2065}
2066
2067/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
2068/// smooshes them together with platform defaults, to decide whether
2069/// this compile should be using PIC mode or not. Returns a tuple of
2070/// (RelocationModel, PICLevel, IsPIE).
2071std::tuple<llvm::Reloc::Model, unsigned, bool>
2072tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
2073 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
2074 const llvm::Triple &Triple = ToolChain.getTriple();
2075
2076 bool PIE = ToolChain.isPIEDefault(Args);
2077 bool PIC = PIE || ToolChain.isPICDefault();
2078 // The Darwin/MachO default to use PIC does not apply when using -static.
2079 if (Triple.isOSBinFormatMachO() && Args.hasArg(Ids: options::OPT_static))
2080 PIE = PIC = false;
2081 bool IsPICLevelTwo = PIC;
2082
2083 bool KernelOrKext =
2084 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
2085
2086 // Android-specific defaults for PIC/PIE
2087 if (Triple.isAndroid()) {
2088 switch (Triple.getArch()) {
2089 case llvm::Triple::x86:
2090 case llvm::Triple::x86_64:
2091 PIC = true; // "-fPIC"
2092 IsPICLevelTwo = true;
2093 break;
2094
2095 default:
2096 PIC = true; // "-fpic"
2097 break;
2098 }
2099 }
2100
2101 // OHOS-specific defaults for PIC/PIE
2102 if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64)
2103 PIC = true;
2104
2105 // OpenBSD-specific defaults for PIE
2106 if (Triple.isOSOpenBSD()) {
2107 switch (ToolChain.getArch()) {
2108 case llvm::Triple::arm:
2109 case llvm::Triple::aarch64:
2110 case llvm::Triple::mips64:
2111 case llvm::Triple::mips64el:
2112 case llvm::Triple::x86:
2113 case llvm::Triple::x86_64:
2114 IsPICLevelTwo = false; // "-fpie"
2115 break;
2116
2117 case llvm::Triple::ppc:
2118 case llvm::Triple::sparcv9:
2119 IsPICLevelTwo = true; // "-fPIE"
2120 break;
2121
2122 default:
2123 break;
2124 }
2125 }
2126
2127 // The last argument relating to either PIC or PIE wins, and no
2128 // other argument is used. If the last argument is any flavor of the
2129 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
2130 // option implicitly enables PIC at the same level.
2131 Arg *LastPICArg = Args.getLastArg(Ids: options::OPT_fPIC, Ids: options::OPT_fno_PIC,
2132 Ids: options::OPT_fpic, Ids: options::OPT_fno_pic,
2133 Ids: options::OPT_fPIE, Ids: options::OPT_fno_PIE,
2134 Ids: options::OPT_fpie, Ids: options::OPT_fno_pie);
2135 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
2136 LastPICArg == Args.getLastArg(Ids: options::OPT_fPIC, Ids: options::OPT_fpic,
2137 Ids: options::OPT_fPIE, Ids: options::OPT_fpie)) {
2138 ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2139 << LastPICArg->getSpelling() << Triple.str();
2140 if (Triple.getArch() == llvm::Triple::x86_64)
2141 return std::make_tuple(args: llvm::Reloc::PIC_, args: 2U, args: false);
2142 return std::make_tuple(args: llvm::Reloc::Static, args: 0U, args: false);
2143 }
2144
2145 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
2146 // is forced, then neither PIC nor PIE flags will have no effect.
2147 if (!ToolChain.isPICDefaultForced()) {
2148 if (LastPICArg) {
2149 Option O = LastPICArg->getOption();
2150 if (O.matches(ID: options::OPT_fPIC) || O.matches(ID: options::OPT_fpic) ||
2151 O.matches(ID: options::OPT_fPIE) || O.matches(ID: options::OPT_fpie)) {
2152 PIE = O.matches(ID: options::OPT_fPIE) || O.matches(ID: options::OPT_fpie);
2153 PIC =
2154 PIE || O.matches(ID: options::OPT_fPIC) || O.matches(ID: options::OPT_fpic);
2155 IsPICLevelTwo =
2156 O.matches(ID: options::OPT_fPIE) || O.matches(ID: options::OPT_fPIC);
2157 } else {
2158 PIE = PIC = false;
2159 if (EffectiveTriple.isPS()) {
2160 Arg *ModelArg = Args.getLastArg(Ids: options::OPT_mcmodel_EQ);
2161 StringRef Model = ModelArg ? ModelArg->getValue() : "";
2162 if (Model != "kernel") {
2163 PIC = true;
2164 ToolChain.getDriver().Diag(DiagID: diag::warn_drv_ps_force_pic)
2165 << LastPICArg->getSpelling()
2166 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
2167 }
2168 }
2169 }
2170 }
2171 }
2172
2173 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
2174 // the PIC level would've been set to level 1, force it back to level 2 PIC
2175 // instead.
2176 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
2177 IsPICLevelTwo |= ToolChain.isPICDefault();
2178
2179 // This kernel flags are a trump-card: they will disable PIC/PIE
2180 // generation, independent of the argument order.
2181 if (KernelOrKext &&
2182 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(Major: 6)) &&
2183 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
2184 PIC = PIE = false;
2185
2186 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdynamic_no_pic)) {
2187 // This is a very special mode. It trumps the other modes, almost no one
2188 // uses it, and it isn't even valid on any OS but Darwin.
2189 if (!Triple.isOSDarwin())
2190 ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2191 << A->getSpelling() << Triple.str();
2192
2193 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
2194
2195 // Only a forced PIC mode can cause the actual compile to have PIC defines
2196 // etc., no flags are sufficient. This behavior was selected to closely
2197 // match that of llvm-gcc and Apple GCC before that.
2198 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
2199
2200 return std::make_tuple(args: llvm::Reloc::DynamicNoPIC, args: PIC ? 2U : 0U, args: false);
2201 }
2202
2203 bool EmbeddedPISupported;
2204 switch (Triple.getArch()) {
2205 case llvm::Triple::arm:
2206 case llvm::Triple::armeb:
2207 case llvm::Triple::thumb:
2208 case llvm::Triple::thumbeb:
2209 EmbeddedPISupported = true;
2210 break;
2211 default:
2212 EmbeddedPISupported = false;
2213 break;
2214 }
2215
2216 bool ROPI = false, RWPI = false;
2217 Arg* LastROPIArg = Args.getLastArg(Ids: options::OPT_fropi, Ids: options::OPT_fno_ropi);
2218 if (LastROPIArg && LastROPIArg->getOption().matches(ID: options::OPT_fropi)) {
2219 if (!EmbeddedPISupported)
2220 ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2221 << LastROPIArg->getSpelling() << Triple.str();
2222 ROPI = true;
2223 }
2224 Arg *LastRWPIArg = Args.getLastArg(Ids: options::OPT_frwpi, Ids: options::OPT_fno_rwpi);
2225 if (LastRWPIArg && LastRWPIArg->getOption().matches(ID: options::OPT_frwpi)) {
2226 if (!EmbeddedPISupported)
2227 ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2228 << LastRWPIArg->getSpelling() << Triple.str();
2229 RWPI = true;
2230 }
2231
2232 // ROPI and RWPI are not compatible with PIC or PIE.
2233 if ((ROPI || RWPI) && (PIC || PIE))
2234 ToolChain.getDriver().Diag(DiagID: diag::err_drv_ropi_rwpi_incompatible_with_pic);
2235
2236 if (Triple.isMIPS()) {
2237 StringRef CPUName;
2238 StringRef ABIName;
2239 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
2240 // When targeting the N64 ABI, PIC is the default, except in the case
2241 // when the -mno-abicalls option is used. In that case we exit
2242 // at next check regardless of PIC being set below.
2243 if (ABIName == "n64")
2244 PIC = true;
2245 // When targettng MIPS with -mno-abicalls, it's always static.
2246 if(Args.hasArg(Ids: options::OPT_mno_abicalls))
2247 return std::make_tuple(args: llvm::Reloc::Static, args: 0U, args: false);
2248 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
2249 // does not use PIC level 2 for historical reasons.
2250 IsPICLevelTwo = false;
2251 }
2252
2253 if (PIC)
2254 return std::make_tuple(args: llvm::Reloc::PIC_, args: IsPICLevelTwo ? 2U : 1U, args&: PIE);
2255
2256 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
2257 if (ROPI && RWPI)
2258 RelocM = llvm::Reloc::ROPI_RWPI;
2259 else if (ROPI)
2260 RelocM = llvm::Reloc::ROPI;
2261 else if (RWPI)
2262 RelocM = llvm::Reloc::RWPI;
2263
2264 return std::make_tuple(args&: RelocM, args: 0U, args: false);
2265}
2266
2267bool tools::getStaticPIE(const ArgList &Args, const ToolChain &TC) {
2268 bool HasStaticPIE = Args.hasArg(Ids: options::OPT_static_pie);
2269 if (HasStaticPIE && Args.hasArg(Ids: options::OPT_no_pie)) {
2270 const Driver &D = TC.getDriver();
2271 const llvm::opt::OptTable &Opts = D.getOpts();
2272 StringRef StaticPIEName = Opts.getOptionName(id: options::OPT_static_pie);
2273 StringRef NoPIEName = Opts.getOptionName(id: options::OPT_nopie);
2274 D.Diag(DiagID: diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName;
2275 }
2276 return HasStaticPIE;
2277}
2278
2279// `-falign-functions` indicates that the functions should be aligned to the
2280// backend's preferred alignment.
2281//
2282// `-falign-functions=1` is the same as `-fno-align-functions`.
2283//
2284// The scalar `n` in `-falign-functions=n` must be an integral value between
2285// [0, 65536]. If the value is not a power-of-two, it will be rounded up to
2286// the nearest power-of-two.
2287//
2288// If we return `0`, the frontend will default to the backend's preferred
2289// alignment.
2290//
2291// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
2292// to mean `-falign-functions=16`. GCC defaults to the backend's preferred
2293// alignment. For unaligned functions, we default to the backend's preferred
2294// alignment.
2295unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
2296 const ArgList &Args) {
2297 const Arg *A = Args.getLastArg(Ids: options::OPT_falign_functions,
2298 Ids: options::OPT_falign_functions_EQ,
2299 Ids: options::OPT_fno_align_functions);
2300 if (!A || A->getOption().matches(ID: options::OPT_fno_align_functions))
2301 return 0;
2302
2303 if (A->getOption().matches(ID: options::OPT_falign_functions))
2304 return 0;
2305
2306 unsigned Value = 0;
2307 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
2308 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
2309 << A->getAsString(Args) << A->getValue();
2310 return Value ? llvm::Log2_32_Ceil(Value: std::min(a: Value, b: 65536u)) : Value;
2311}
2312
2313void tools::addDebugInfoKind(
2314 ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
2315 switch (DebugInfoKind) {
2316 case llvm::codegenoptions::DebugDirectivesOnly:
2317 CmdArgs.push_back(Elt: "-debug-info-kind=line-directives-only");
2318 break;
2319 case llvm::codegenoptions::DebugLineTablesOnly:
2320 CmdArgs.push_back(Elt: "-debug-info-kind=line-tables-only");
2321 break;
2322 case llvm::codegenoptions::DebugInfoConstructor:
2323 CmdArgs.push_back(Elt: "-debug-info-kind=constructor");
2324 break;
2325 case llvm::codegenoptions::LimitedDebugInfo:
2326 CmdArgs.push_back(Elt: "-debug-info-kind=limited");
2327 break;
2328 case llvm::codegenoptions::FullDebugInfo:
2329 CmdArgs.push_back(Elt: "-debug-info-kind=standalone");
2330 break;
2331 case llvm::codegenoptions::UnusedTypeInfo:
2332 CmdArgs.push_back(Elt: "-debug-info-kind=unused-types");
2333 break;
2334 default:
2335 break;
2336 }
2337}
2338
2339// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2340// to the corresponding DebugInfoKind.
2341llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) {
2342 assert(A.getOption().matches(options::OPT_gN_Group) &&
2343 "Not a -g option that specifies a debug-info level");
2344 if (A.getOption().matches(ID: options::OPT_g0) ||
2345 A.getOption().matches(ID: options::OPT_ggdb0))
2346 return llvm::codegenoptions::NoDebugInfo;
2347 if (A.getOption().matches(ID: options::OPT_gline_tables_only) ||
2348 A.getOption().matches(ID: options::OPT_ggdb1))
2349 return llvm::codegenoptions::DebugLineTablesOnly;
2350 if (A.getOption().matches(ID: options::OPT_gline_directives_only))
2351 return llvm::codegenoptions::DebugDirectivesOnly;
2352 return llvm::codegenoptions::DebugInfoConstructor;
2353}
2354
2355static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
2356 const ArgList &Args) {
2357 const Arg *A = Args.getLastArg(Ids: options::OPT_fdebug_default_version);
2358
2359 if (!A)
2360 return 0;
2361
2362 unsigned Value = 0;
2363 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 6 ||
2364 Value < 2)
2365 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
2366 << A->getAsString(Args) << A->getValue();
2367 return Value;
2368}
2369
2370unsigned tools::DwarfVersionNum(StringRef ArgValue) {
2371 return llvm::StringSwitch<unsigned>(ArgValue)
2372 .Case(S: "-gdwarf-2", Value: 2)
2373 .Case(S: "-gdwarf-3", Value: 3)
2374 .Case(S: "-gdwarf-4", Value: 4)
2375 .Case(S: "-gdwarf-5", Value: 5)
2376 .Case(S: "-gdwarf-6", Value: 6)
2377 .Default(Value: 0);
2378}
2379
2380const Arg *tools::getDwarfNArg(const ArgList &Args) {
2381 return Args.getLastArg(Ids: options::OPT_gdwarf_2, Ids: options::OPT_gdwarf_3,
2382 Ids: options::OPT_gdwarf_4, Ids: options::OPT_gdwarf_5,
2383 Ids: options::OPT_gdwarf_6, Ids: options::OPT_gdwarf);
2384}
2385
2386unsigned tools::getDwarfVersion(const ToolChain &TC,
2387 const llvm::opt::ArgList &Args) {
2388 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args);
2389 if (const Arg *GDwarfN = getDwarfNArg(Args))
2390 if (int N = DwarfVersionNum(ArgValue: GDwarfN->getSpelling())) {
2391 DwarfVersion = N;
2392 if (DwarfVersion == 5 && TC.getTriple().isOSAIX())
2393 TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2394 << GDwarfN->getSpelling() << TC.getTriple().str();
2395 }
2396 if (DwarfVersion == 0) {
2397 DwarfVersion = TC.GetDefaultDwarfVersion();
2398 assert(DwarfVersion && "toolchain default DWARF version must be nonzero");
2399 }
2400 return DwarfVersion;
2401}
2402
2403DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
2404 const ArgList &Args, Arg *&Arg) {
2405 Arg = Args.getLastArg(Ids: options::OPT_gsplit_dwarf, Ids: options::OPT_gsplit_dwarf_EQ,
2406 Ids: options::OPT_gno_split_dwarf);
2407 if (!Arg || Arg->getOption().matches(ID: options::OPT_gno_split_dwarf))
2408 return DwarfFissionKind::None;
2409
2410 if (Arg->getOption().matches(ID: options::OPT_gsplit_dwarf))
2411 return DwarfFissionKind::Split;
2412
2413 StringRef Value = Arg->getValue();
2414 if (Value == "split")
2415 return DwarfFissionKind::Split;
2416 if (Value == "single")
2417 return DwarfFissionKind::Single;
2418
2419 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2420 << Arg->getSpelling() << Arg->getValue();
2421 return DwarfFissionKind::None;
2422}
2423
2424bool tools::checkDebugInfoOption(const Arg *A, const ArgList &Args,
2425 const Driver &D, const ToolChain &TC) {
2426 assert(A && "Expected non-nullptr argument.");
2427 if (TC.supportsDebugInfoOption(A))
2428 return true;
2429 D.Diag(DiagID: diag::warn_drv_unsupported_debug_info_opt_for_target)
2430 << A->getAsString(Args) << TC.getTripleString();
2431 return false;
2432}
2433
2434void tools::addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC,
2435 const ArgList &Args,
2436 ArgStringList &CmdArgs) {
2437 if (Args.hasFlag(Pos: options::OPT_fdebug_info_for_profiling,
2438 Neg: options::OPT_fno_debug_info_for_profiling, Default: false) &&
2439 checkDebugInfoOption(
2440 A: Args.getLastArg(Ids: options::OPT_fdebug_info_for_profiling), Args, D, TC))
2441 CmdArgs.push_back(Elt: "-fdebug-info-for-profiling");
2442}
2443
2444void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
2445 ArgStringList &CmdArgs) {
2446 llvm::Reloc::Model RelocationModel;
2447 unsigned PICLevel;
2448 bool IsPIE;
2449 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain, Args);
2450
2451 if (RelocationModel != llvm::Reloc::Static)
2452 CmdArgs.push_back(Elt: "-KPIC");
2453}
2454
2455/// Determine whether Objective-C automated reference counting is
2456/// enabled.
2457bool tools::isObjCAutoRefCount(const ArgList &Args) {
2458 return Args.hasFlag(Pos: options::OPT_fobjc_arc, Neg: options::OPT_fno_objc_arc, Default: false);
2459}
2460
2461enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
2462
2463static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
2464 const ArgList &Args) {
2465 if (Args.hasArg(Ids: options::OPT_static_libgcc) ||
2466 Args.hasArg(Ids: options::OPT_static) || Args.hasArg(Ids: options::OPT_static_pie) ||
2467 // The Android NDK only provides libunwind.a, not libunwind.so.
2468 TC.getTriple().isAndroid())
2469 return LibGccType::StaticLibGcc;
2470 if (Args.hasArg(Ids: options::OPT_shared_libgcc))
2471 return LibGccType::SharedLibGcc;
2472 return LibGccType::UnspecifiedLibGcc;
2473}
2474
2475// Gcc adds libgcc arguments in various ways:
2476//
2477// gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
2478// g++ <none>: -lgcc_s -lgcc
2479// gcc shared: -lgcc_s -lgcc
2480// g++ shared: -lgcc_s -lgcc
2481// gcc static: -lgcc -lgcc_eh
2482// g++ static: -lgcc -lgcc_eh
2483// gcc static-pie: -lgcc -lgcc_eh
2484// g++ static-pie: -lgcc -lgcc_eh
2485//
2486// Also, certain targets need additional adjustments.
2487
2488static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
2489 ArgStringList &CmdArgs, const ArgList &Args) {
2490 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
2491 // By default OHOS binaries are linked statically to libunwind.
2492 if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) {
2493 CmdArgs.push_back(Elt: "-l:libunwind.a");
2494 return;
2495 }
2496
2497 // Targets that don't use unwind libraries.
2498 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
2499 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
2500 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
2501 return;
2502
2503 LibGccType LGT = getLibGccType(TC, D, Args);
2504 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
2505 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
2506 !TC.getTriple().isAndroid() &&
2507 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
2508 if (AsNeeded)
2509 addAsNeededOption(TC, Args, CmdArgs, as_needed: true);
2510
2511 switch (UNW) {
2512 case ToolChain::UNW_None:
2513 return;
2514 case ToolChain::UNW_Libgcc: {
2515 if (LGT == LibGccType::StaticLibGcc)
2516 CmdArgs.push_back(Elt: "-lgcc_eh");
2517 else
2518 CmdArgs.push_back(Elt: "-lgcc_s");
2519 break;
2520 }
2521 case ToolChain::UNW_CompilerRT:
2522 if (TC.getTriple().isOSAIX()) {
2523 // AIX only has libunwind as a shared library. So do not pass
2524 // anything in if -static is specified.
2525 if (LGT != LibGccType::StaticLibGcc)
2526 CmdArgs.push_back(Elt: "-lunwind");
2527 } else if (LGT == LibGccType::StaticLibGcc) {
2528 CmdArgs.push_back(Elt: "-l:libunwind.a");
2529 } else if (LGT == LibGccType::SharedLibGcc) {
2530 if (TC.getTriple().isOSCygMing())
2531 CmdArgs.push_back(Elt: "-l:libunwind.dll.a");
2532 else
2533 CmdArgs.push_back(Elt: "-l:libunwind.so");
2534 } else {
2535 // Let the linker choose between libunwind.so and libunwind.a
2536 // depending on what's available, and depending on the -static flag
2537 CmdArgs.push_back(Elt: "-lunwind");
2538 }
2539 break;
2540 }
2541
2542 if (AsNeeded)
2543 addAsNeededOption(TC, Args, CmdArgs, as_needed: false);
2544}
2545
2546static void AddLibgcc(const ToolChain &TC, const Driver &D,
2547 ArgStringList &CmdArgs, const ArgList &Args) {
2548 LibGccType LGT = getLibGccType(TC, D, Args);
2549 if (LGT == LibGccType::StaticLibGcc ||
2550 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
2551 CmdArgs.push_back(Elt: "-lgcc");
2552 AddUnwindLibrary(TC, D, CmdArgs, Args);
2553 if (LGT == LibGccType::SharedLibGcc ||
2554 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
2555 CmdArgs.push_back(Elt: "-lgcc");
2556 // compiler-rt is needed after libgcc for flang on AArch64 for the
2557 // __trampoline_setup symbol
2558 if (D.IsFlangMode() && TC.getArch() == llvm::Triple::aarch64) {
2559 CmdArgs.push_back(Elt: "--as-needed");
2560 CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "builtins"));
2561 CmdArgs.push_back(Elt: "--no-as-needed");
2562 }
2563}
2564
2565void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
2566 ArgStringList &CmdArgs, const ArgList &Args) {
2567 // Make use of compiler-rt if --rtlib option is used
2568 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
2569
2570 switch (RLT) {
2571 case ToolChain::RLT_CompilerRT:
2572 CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "builtins"));
2573 AddUnwindLibrary(TC, D, CmdArgs, Args);
2574 break;
2575 case ToolChain::RLT_Libgcc:
2576 // Make sure libgcc is not used under MSVC environment by default
2577 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
2578 // Issue error diagnostic if libgcc is explicitly specified
2579 // through command line as --rtlib option argument.
2580 Arg *A = Args.getLastArg(Ids: options::OPT_rtlib_EQ);
2581 if (A && A->getValue() != StringRef("platform")) {
2582 TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_rtlib_for_platform)
2583 << A->getValue() << "MSVC";
2584 }
2585 } else
2586 AddLibgcc(TC, D, CmdArgs, Args);
2587 break;
2588 }
2589
2590 // On Android, the unwinder uses dl_iterate_phdr (or one of
2591 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
2592 // statically-linked executables, these functions come from libc.a instead.
2593 if (TC.getTriple().isAndroid() && !Args.hasArg(Ids: options::OPT_static) &&
2594 !Args.hasArg(Ids: options::OPT_static_pie))
2595 CmdArgs.push_back(Elt: "-ldl");
2596}
2597
2598SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
2599 const InputInfo &Output,
2600 const InputInfo &Input,
2601 const Driver &D) {
2602 const Arg *A = Args.getLastArg(Ids: options::OPT_save_stats_EQ);
2603 if (!A && !D.CCPrintInternalStats)
2604 return {};
2605
2606 SmallString<128> StatsFile;
2607 if (A) {
2608 StringRef SaveStats = A->getValue();
2609 if (SaveStats == "obj" && Output.isFilename()) {
2610 StatsFile.assign(RHS: Output.getFilename());
2611 llvm::sys::path::remove_filename(path&: StatsFile);
2612 } else if (SaveStats != "cwd") {
2613 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
2614 return {};
2615 }
2616
2617 StringRef BaseName = llvm::sys::path::filename(path: Input.getBaseInput());
2618 llvm::sys::path::append(path&: StatsFile, a: BaseName);
2619 llvm::sys::path::replace_extension(path&: StatsFile, extension: "stats");
2620 } else {
2621 assert(D.CCPrintInternalStats);
2622 StatsFile.assign(RHS: D.CCPrintInternalStatReportFilename.empty()
2623 ? "-"
2624 : D.CCPrintInternalStatReportFilename);
2625 }
2626 return StatsFile;
2627}
2628
2629void tools::addMultilibFlag(bool Enabled, const StringRef Flag,
2630 Multilib::flags_list &Flags) {
2631 assert(Flag.front() == '-');
2632 if (Enabled) {
2633 Flags.push_back(x: Flag.str());
2634 } else {
2635 Flags.push_back(x: ("!" + Flag.substr(Start: 1)).str());
2636 }
2637}
2638
2639void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
2640 ArgStringList &CmdArgs, bool IsLTO,
2641 const StringRef PluginOptPrefix) {
2642 auto addArg = [&, IsLTO](const Twine &Arg) {
2643 if (IsLTO) {
2644 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
2645 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + Arg));
2646 } else {
2647 CmdArgs.push_back(Elt: "-mllvm");
2648 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
2649 }
2650 };
2651
2652 if (Args.hasArg(Ids: options::OPT_mbranches_within_32B_boundaries)) {
2653 addArg(Twine("-x86-branches-within-32B-boundaries"));
2654 }
2655 if (const Arg *A = Args.getLastArg(Ids: options::OPT_malign_branch_boundary_EQ)) {
2656 StringRef Value = A->getValue();
2657 unsigned Boundary;
2658 if (Value.getAsInteger(Radix: 10, Result&: Boundary) || Boundary < 16 ||
2659 !llvm::isPowerOf2_64(Value: Boundary)) {
2660 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
2661 << Value << A->getOption().getName();
2662 } else {
2663 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
2664 }
2665 }
2666 if (const Arg *A = Args.getLastArg(Ids: options::OPT_malign_branch_EQ)) {
2667 std::string AlignBranch;
2668 for (StringRef T : A->getValues()) {
2669 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
2670 T != "ret" && T != "indirect")
2671 D.Diag(DiagID: diag::err_drv_invalid_malign_branch_EQ)
2672 << T << "fused, jcc, jmp, call, ret, indirect";
2673 if (!AlignBranch.empty())
2674 AlignBranch += '+';
2675 AlignBranch += T;
2676 }
2677 addArg("-x86-align-branch=" + Twine(AlignBranch));
2678 }
2679 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mpad_max_prefix_size_EQ)) {
2680 StringRef Value = A->getValue();
2681 unsigned PrefixSize;
2682 if (Value.getAsInteger(Radix: 10, Result&: PrefixSize)) {
2683 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
2684 << Value << A->getOption().getName();
2685 } else {
2686 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
2687 }
2688 }
2689}
2690
2691/// SDLSearch: Search for Static Device Library
2692/// The search for SDL bitcode files is consistent with how static host
2693/// libraries are discovered. That is, the -l option triggers a search for
2694/// files in a set of directories called the LINKPATH. The host library search
2695/// procedure looks for a specific filename in the LINKPATH. The filename for
2696/// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
2697/// ordered-set of filenames that are searched. We call this ordered-set of
2698/// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
2699/// architecture specific, or generic across all architectures, a naming
2700/// convention and search order is used where the file name embeds the
2701/// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
2702/// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
2703/// device-independent SDLs. To reduce congestion in host library directories,
2704/// the search first looks for files in the “libdevice” subdirectory. SDLs that
2705/// are bc files begin with the prefix “lib”.
2706///
2707/// Machine-code SDLs can also be managed as an archive (*.a file). The
2708/// convention has been to use the prefix “lib”. To avoid confusion with host
2709/// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
2710///
2711static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
2712 llvm::opt::ArgStringList &CC1Args,
2713 const SmallVectorImpl<std::string> &LibraryPaths,
2714 StringRef Lib, StringRef Arch, StringRef Target,
2715 bool isBitCodeSDL) {
2716 SmallVector<std::string, 12> SDLs;
2717
2718 std::string LibDeviceLoc = "/libdevice";
2719 std::string LibBcPrefix = "/libbc-";
2720 std::string LibPrefix = "/lib";
2721
2722 if (isBitCodeSDL) {
2723 // SEARCH-ORDER for Bitcode SDLs:
2724 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
2725 // libbc-<libname>-<arch-name>-<device-type>.a
2726 // libdevice/libbc-<libname>-<arch-name>.a
2727 // libbc-<libname>-<arch-name>.a
2728 // libdevice/libbc-<libname>.a
2729 // libbc-<libname>.a
2730 // libdevice/lib<libname>-<arch-name>-<device-type>.bc
2731 // lib<libname>-<arch-name>-<device-type>.bc
2732 // libdevice/lib<libname>-<arch-name>.bc
2733 // lib<libname>-<arch-name>.bc
2734 // libdevice/lib<libname>.bc
2735 // lib<libname>.bc
2736
2737 for (StringRef Base : {LibBcPrefix, LibPrefix}) {
2738 const auto *Ext = Base.contains(Other: LibBcPrefix) ? ".a" : ".bc";
2739
2740 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2741 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
2742 SDLs.push_back(Elt: Twine(LibDeviceLoc + Base + Suffix + Ext).str());
2743 SDLs.push_back(Elt: Twine(Base + Suffix + Ext).str());
2744 }
2745 }
2746 } else {
2747 // SEARCH-ORDER for Machine-code SDLs:
2748 // libdevice/lib<libname>-<arch-name>-<device-type>.a
2749 // lib<libname>-<arch-name>-<device-type>.a
2750 // libdevice/lib<libname>-<arch-name>.a
2751 // lib<libname>-<arch-name>.a
2752
2753 const auto *Ext = ".a";
2754
2755 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
2756 Twine(Lib + "-" + Arch).str()}) {
2757 SDLs.push_back(Elt: Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
2758 SDLs.push_back(Elt: Twine(LibPrefix + Suffix + Ext).str());
2759 }
2760 }
2761
2762 // The CUDA toolchain does not use a global device llvm-link before the LLVM
2763 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
2764 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
2765 // will link libraries after clang compilation while the LLVM IR is still in
2766 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
2767 // This is a clang -cc1 option that is generated by the clang driver. The
2768 // option value must a full path to an existing file.
2769 bool FoundSDL = false;
2770 for (auto LPath : LibraryPaths) {
2771 for (auto SDL : SDLs) {
2772 auto FullName = Twine(LPath + SDL).str();
2773 if (llvm::sys::fs::exists(Path: FullName)) {
2774 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: FullName));
2775 FoundSDL = true;
2776 break;
2777 }
2778 }
2779 if (FoundSDL)
2780 break;
2781 }
2782 return FoundSDL;
2783}
2784
2785/// Search if a user provided archive file lib<libname>.a exists in any of
2786/// the library paths. If so, add a new command to clang-offload-bundler to
2787/// unbundle this archive and create a temporary device specific archive. Name
2788/// of this SDL is passed to the llvm-link tool.
2789static void GetSDLFromOffloadArchive(
2790 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
2791 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
2792 llvm::opt::ArgStringList &CC1Args,
2793 const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib,
2794 StringRef Arch, StringRef Target, bool isBitCodeSDL) {
2795
2796 // We don't support bitcode archive bundles for nvptx
2797 if (isBitCodeSDL && Arch.contains(Other: "nvptx"))
2798 return;
2799
2800 bool FoundAOB = false;
2801 std::string ArchiveOfBundles;
2802
2803 llvm::Triple Triple(D.getTargetTriple());
2804 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
2805 auto Ext = IsMSVC ? ".lib" : ".a";
2806 if (!Lib.starts_with(Prefix: ":") && !Lib.starts_with(Prefix: "-l")) {
2807 if (llvm::sys::fs::exists(Path: Lib)) {
2808 ArchiveOfBundles = Lib;
2809 FoundAOB = true;
2810 }
2811 } else {
2812 Lib.consume_front(Prefix: "-l");
2813 for (auto LPath : LibraryPaths) {
2814 ArchiveOfBundles.clear();
2815 auto LibFile = (Lib.starts_with(Prefix: ":") ? Lib.drop_front()
2816 : IsMSVC ? Lib + Ext
2817 : "lib" + Lib + Ext)
2818 .str();
2819 for (auto Prefix : {"/libdevice/", "/"}) {
2820 auto AOB = Twine(LPath + Prefix + LibFile).str();
2821 if (llvm::sys::fs::exists(Path: AOB)) {
2822 ArchiveOfBundles = AOB;
2823 FoundAOB = true;
2824 break;
2825 }
2826 }
2827 if (FoundAOB)
2828 break;
2829 }
2830 }
2831
2832 if (!FoundAOB)
2833 return;
2834
2835 llvm::file_magic Magic;
2836 auto EC = llvm::identify_magic(path: ArchiveOfBundles, result&: Magic);
2837 if (EC || Magic != llvm::file_magic::archive)
2838 return;
2839
2840 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
2841 std::string OutputLib =
2842 D.GetTemporaryPath(Prefix: Twine(Prefix + llvm::sys::path::filename(path: Lib) + "-" +
2843 Arch + "-" + Target)
2844 .str(),
2845 Suffix: "a");
2846
2847 C.addTempFile(Name: C.getArgs().MakeArgString(Str: OutputLib));
2848
2849 SmallString<128> DeviceTriple;
2850 DeviceTriple += Action::GetOffloadKindName(Kind: JA.getOffloadingDeviceKind());
2851 DeviceTriple += '-';
2852 std::string NormalizedTriple =
2853 T.getToolChain().getEffectiveTriple().normalize(
2854 Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
2855 DeviceTriple += NormalizedTriple;
2856 if (!Target.empty()) {
2857 DeviceTriple += '-';
2858 DeviceTriple += Target;
2859 }
2860
2861 std::string UnbundleArg("-unbundle");
2862 std::string TypeArg("-type=a");
2863 std::string InputArg("-input=" + ArchiveOfBundles);
2864 std::string OffloadArg("-targets=" + std::string(DeviceTriple));
2865 std::string OutputArg("-output=" + OutputLib);
2866
2867 const char *UBProgram = DriverArgs.MakeArgString(
2868 Str: T.getToolChain().GetProgramPath(Name: "clang-offload-bundler"));
2869
2870 ArgStringList UBArgs;
2871 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: UnbundleArg));
2872 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: TypeArg));
2873 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: InputArg));
2874 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: OffloadArg));
2875 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: OutputArg));
2876
2877 // Add this flag to not exit from clang-offload-bundler if no compatible
2878 // code object is found in heterogenous archive library.
2879 std::string AdditionalArgs("-allow-missing-bundles");
2880 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: AdditionalArgs));
2881
2882 // Add this flag to treat hip and hipv4 offload kinds as compatible with
2883 // openmp offload kind while extracting code objects from a heterogenous
2884 // archive library. Vice versa is also considered compatible.
2885 std::string HipCompatibleArgs("-hip-openmp-compatible");
2886 UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: HipCompatibleArgs));
2887
2888 C.addCommand(Cmd: std::make_unique<Command>(
2889 args: JA, args: T, args: ResponseFileSupport::AtFileCurCP(), args&: UBProgram, args&: UBArgs, args: Inputs,
2890 args: InputInfo(&JA, C.getArgs().MakeArgString(Str: OutputLib))));
2891
2892 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: OutputLib));
2893}
2894
2895// Wrapper function used by driver for adding SDLs during link phase.
2896void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
2897 const JobAction &JA,
2898 const InputInfoList &Inputs,
2899 const llvm::opt::ArgList &DriverArgs,
2900 llvm::opt::ArgStringList &CC1Args,
2901 StringRef Arch, StringRef Target,
2902 bool isBitCodeSDL) {
2903 AddStaticDeviceLibs(C: &C, T: &T, JA: &JA, Inputs: &Inputs, D: C.getDriver(), DriverArgs, CmdArgs&: CC1Args,
2904 Arch, Target, isBitCodeSDL);
2905}
2906
2907// User defined Static Device Libraries(SDLs) can be passed to clang for
2908// offloading GPU compilers. Like static host libraries, the use of a SDL is
2909// specified with the -l command line option. The primary difference between
2910// host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
2911// and SEARCH-ORDER for Machine-code SDLs for the naming convention).
2912// SDLs are of following types:
2913//
2914// * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
2915// For NVPTX, these libraries are post-clang linked following each
2916// compilation. For AMDGPU, these libraries are linked one time
2917// during the application link phase.
2918//
2919// * Machine-code SDLs: They are archive files. For AMDGPU, the process for
2920// machine code SDLs is still in development. But they will be linked
2921// by the LLVM tool lld.
2922//
2923// * Bundled objects that contain both host and device codes: Bundled objects
2924// may also contain library code compiled from source. For NVPTX, the
2925// bundle contains cubin. For AMDGPU, the bundle contains bitcode.
2926//
2927// For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
2928// inclusion of specific SDLs such as math libraries and the OpenMP device
2929// library libomptarget.
2930void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
2931 const JobAction *JA,
2932 const InputInfoList *Inputs, const Driver &D,
2933 const llvm::opt::ArgList &DriverArgs,
2934 llvm::opt::ArgStringList &CC1Args,
2935 StringRef Arch, StringRef Target,
2936 bool isBitCodeSDL) {
2937
2938 SmallVector<std::string, 8> LibraryPaths;
2939 // Add search directories from LIBRARY_PATH env variable
2940 std::optional<std::string> LibPath =
2941 llvm::sys::Process::GetEnv(name: "LIBRARY_PATH");
2942 if (LibPath) {
2943 SmallVector<StringRef, 8> Frags;
2944 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2945 llvm::SplitString(Source: *LibPath, OutFragments&: Frags, Delimiters: EnvPathSeparatorStr);
2946 for (StringRef Path : Frags)
2947 LibraryPaths.emplace_back(Args: Path.trim());
2948 }
2949
2950 // Add directories from user-specified -L options
2951 for (std::string Search_Dir : DriverArgs.getAllArgValues(Id: options::OPT_L))
2952 LibraryPaths.emplace_back(Args&: Search_Dir);
2953
2954 // Add path to lib-debug folders
2955 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(path: D.Dir);
2956 llvm::sys::path::append(path&: DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
2957 LibraryPaths.emplace_back(Args: DefaultLibPath.c_str());
2958
2959 // Build list of Static Device Libraries SDLs specified by -l option
2960 llvm::SmallSet<std::string, 16> SDLNames;
2961 static const StringRef HostOnlyArchives[] = {
2962 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2963 for (auto SDLName : DriverArgs.getAllArgValues(Id: options::OPT_l)) {
2964 if (!llvm::is_contained(Range: HostOnlyArchives, Element: SDLName)) {
2965 SDLNames.insert(V: std::string("-l") + SDLName);
2966 }
2967 }
2968
2969 for (auto Input : DriverArgs.getAllArgValues(Id: options::OPT_INPUT)) {
2970 auto FileName = StringRef(Input);
2971 // Clang treats any unknown file types as archives and passes them to the
2972 // linker. Files with extension 'lib' are classified as TY_Object by clang
2973 // but they are usually archives. It is OK if the file is not really an
2974 // archive since GetSDLFromOffloadArchive will check the magic of the file
2975 // and only unbundle it if it is really an archive.
2976 const StringRef LibFileExt = ".lib";
2977 if (!llvm::sys::path::has_extension(path: FileName) ||
2978 types::lookupTypeForExtension(
2979 Ext: llvm::sys::path::extension(path: FileName).drop_front()) ==
2980 types::TY_INVALID ||
2981 llvm::sys::path::extension(path: FileName) == LibFileExt)
2982 SDLNames.insert(V: Input);
2983 }
2984
2985 // The search stops as soon as an SDL file is found. The driver then provides
2986 // the full filename of the SDL to the llvm-link command. If no SDL is found
2987 // after searching each LINKPATH with SEARCH-ORDER, it is possible that an
2988 // archive file lib<libname>.a exists and may contain bundled object files.
2989 for (auto SDLName : SDLNames) {
2990 // This is the only call to SDLSearch
2991 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, Lib: SDLName, Arch, Target,
2992 isBitCodeSDL)) {
2993 GetSDLFromOffloadArchive(C&: *C, D, T: *T, JA: *JA, Inputs: *Inputs, DriverArgs, CC1Args,
2994 LibraryPaths, Lib: SDLName, Arch, Target,
2995 isBitCodeSDL);
2996 }
2997 }
2998}
2999
3000static llvm::opt::Arg *
3001getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
3002 return Args.getLastArg(Ids: options::OPT_mcode_object_version_EQ);
3003}
3004
3005void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
3006 const llvm::opt::ArgList &Args) {
3007 const unsigned MinCodeObjVer = 4;
3008 const unsigned MaxCodeObjVer = 6;
3009
3010 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
3011 if (CodeObjArg->getOption().getID() ==
3012 options::OPT_mcode_object_version_EQ) {
3013 unsigned CodeObjVer = MaxCodeObjVer;
3014 auto Remnant =
3015 StringRef(CodeObjArg->getValue()).getAsInteger(Radix: 0, Result&: CodeObjVer);
3016 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
3017 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3018 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
3019 }
3020 }
3021}
3022
3023unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
3024 const llvm::opt::ArgList &Args) {
3025 unsigned CodeObjVer = 6; // default
3026 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args))
3027 StringRef(CodeObjArg->getValue()).getAsInteger(Radix: 0, Result&: CodeObjVer);
3028 return CodeObjVer;
3029}
3030
3031bool tools::haveAMDGPUCodeObjectVersionArgument(
3032 const Driver &D, const llvm::opt::ArgList &Args) {
3033 return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
3034}
3035
3036void tools::addMachineOutlinerArgs(const Driver &D,
3037 const llvm::opt::ArgList &Args,
3038 llvm::opt::ArgStringList &CmdArgs,
3039 const llvm::Triple &Triple, bool IsLTO,
3040 const StringRef PluginOptPrefix) {
3041 auto addArg = [&, IsLTO](const Twine &Arg) {
3042 if (IsLTO) {
3043 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!");
3044 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + Arg));
3045 } else {
3046 CmdArgs.push_back(Elt: "-mllvm");
3047 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3048 }
3049 };
3050
3051 if (Arg *A = Args.getLastArg(Ids: options::OPT_moutline,
3052 Ids: options::OPT_mno_outline)) {
3053 if (A->getOption().matches(ID: options::OPT_moutline)) {
3054 // We only support -moutline in AArch64, ARM, RISC-V and X86 targets right
3055 // now. If we're compiling for these, add the proper mllvm flags.
3056 // Otherwise, emit a warning and ignore the flag.
3057 if (Triple.isARM() || Triple.isThumb() || Triple.isAArch64() ||
3058 Triple.isRISCV() || Triple.isX86()) {
3059 addArg(Twine("-enable-machine-outliner"));
3060 } else {
3061 D.Diag(DiagID: diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
3062 }
3063 } else {
3064 if (!IsLTO)
3065 // Disable all outlining behaviour using `nooutline` attribute, in case
3066 // Linker Invocation lacks `-mno-outline`.
3067 CmdArgs.push_back(Elt: "-mno-outline");
3068
3069 // Disable Pass in Pipeline
3070 addArg(Twine("-enable-machine-outliner=never"));
3071 }
3072 }
3073
3074 auto *CodeGenDataGenArg =
3075 Args.getLastArg(Ids: options::OPT_fcodegen_data_generate_EQ);
3076 auto *CodeGenDataUseArg = Args.getLastArg(Ids: options::OPT_fcodegen_data_use_EQ);
3077
3078 // We only allow one of them to be specified.
3079 if (CodeGenDataGenArg && CodeGenDataUseArg)
3080 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3081 << CodeGenDataGenArg->getAsString(Args)
3082 << CodeGenDataUseArg->getAsString(Args);
3083
3084 // For codegen data gen, the output file is passed to the linker
3085 // while a boolean flag is passed to the LLVM backend.
3086 if (CodeGenDataGenArg)
3087 addArg(Twine("-codegen-data-generate"));
3088
3089 // For codegen data use, the input file is passed to the LLVM backend.
3090 if (CodeGenDataUseArg)
3091 addArg(Twine("-codegen-data-use-path=") + CodeGenDataUseArg->getValue());
3092}
3093
3094void tools::addSplitMachineFunctionsArgs(const Driver &D,
3095 const llvm::opt::ArgList &Args,
3096 llvm::opt::ArgStringList &CmdArgs,
3097 const llvm::Triple &Triple) {
3098 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
3099 Ids: options::OPT_fno_split_machine_functions)) {
3100 if (!A->getOption().matches(ID: options::OPT_fno_split_machine_functions)) {
3101 // This codegen pass is only available on x86 and AArch64 ELF targets.
3102 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
3103 A->render(Args, Output&: CmdArgs);
3104 else
3105 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3106 << A->getAsString(Args) << Triple.getTriple();
3107 }
3108 }
3109}
3110
3111void tools::addOpenMPDeviceRTL(const Driver &D,
3112 const llvm::opt::ArgList &DriverArgs,
3113 llvm::opt::ArgStringList &CC1Args,
3114 StringRef BitcodeSuffix,
3115 const llvm::Triple &Triple,
3116 const ToolChain &HostTC) {
3117 SmallVector<StringRef, 8> LibraryPaths;
3118
3119 // Add user defined library paths from LIBRARY_PATH.
3120 std::optional<std::string> LibPath =
3121 llvm::sys::Process::GetEnv(name: "LIBRARY_PATH");
3122 if (LibPath) {
3123 SmallVector<StringRef, 8> Frags;
3124 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
3125 llvm::SplitString(Source: *LibPath, OutFragments&: Frags, Delimiters: EnvPathSeparatorStr);
3126 for (StringRef Path : Frags)
3127 LibraryPaths.emplace_back(Args: Path.trim());
3128 }
3129
3130 // Check all of the standard library search paths used by the compiler.
3131 for (const auto &LibPath : HostTC.getFilePaths())
3132 LibraryPaths.emplace_back(Args: LibPath);
3133
3134 // Check the target specific library path for the triple as well.
3135 SmallString<128> P(D.Dir);
3136 llvm::sys::path::append(path&: P, a: "..", b: "lib", c: Triple.getTriple());
3137 LibraryPaths.emplace_back(Args&: P);
3138
3139 OptSpecifier LibomptargetBCPathOpt =
3140 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
3141 : Triple.isNVPTX() ? options::OPT_libomptarget_nvptx_bc_path_EQ
3142 : options::OPT_libomptarget_spirv_bc_path_EQ;
3143
3144 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu"
3145 : Triple.isNVPTX() ? "nvptx"
3146 : "spirv";
3147 std::string LibOmpTargetName = ("libomptarget-" + ArchPrefix + ".bc").str();
3148
3149 // First check whether user specifies bc library
3150 if (const Arg *A = DriverArgs.getLastArg(Ids: LibomptargetBCPathOpt)) {
3151 SmallString<128> LibOmpTargetFile(A->getValue());
3152 if (llvm::sys::fs::exists(Path: LibOmpTargetFile) &&
3153 llvm::sys::fs::is_directory(Path: LibOmpTargetFile)) {
3154 llvm::sys::path::append(path&: LibOmpTargetFile, a: LibOmpTargetName);
3155 }
3156
3157 if (llvm::sys::fs::exists(Path: LibOmpTargetFile)) {
3158 CC1Args.push_back(Elt: "-mlink-builtin-bitcode");
3159 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: LibOmpTargetFile));
3160 } else {
3161 D.Diag(DiagID: diag::err_drv_omp_offload_target_bcruntime_not_found)
3162 << LibOmpTargetFile;
3163 }
3164 } else {
3165 bool FoundBCLibrary = false;
3166
3167 for (StringRef LibraryPath : LibraryPaths) {
3168 SmallString<128> LibOmpTargetFile(LibraryPath);
3169 llvm::sys::path::append(path&: LibOmpTargetFile, a: LibOmpTargetName);
3170 if (llvm::sys::fs::exists(Path: LibOmpTargetFile)) {
3171 CC1Args.push_back(Elt: "-mlink-builtin-bitcode");
3172 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: LibOmpTargetFile));
3173 FoundBCLibrary = true;
3174 break;
3175 }
3176 }
3177
3178 if (!FoundBCLibrary)
3179 D.Diag(DiagID: diag::err_drv_omp_offload_target_missingbcruntime)
3180 << LibOmpTargetName << ArchPrefix;
3181 }
3182}
3183
3184bool tools::addOpenCLBuiltinsLib(const Driver &D, const llvm::Triple &TT,
3185 const llvm::opt::ArgList &DriverArgs,
3186 llvm::opt::ArgStringList &CC1Args) {
3187
3188 StringRef LibclcNamespec;
3189 const Arg *A = DriverArgs.getLastArg(Ids: options::OPT_libclc_lib_EQ);
3190 if (A) {
3191 // If the namespec is of the form :filename we use it exactly.
3192 LibclcNamespec = A->getValue();
3193 } else {
3194 if (!TT.isAMDGPU() || TT.getEnvironment() != llvm::Triple::LLVM)
3195 return false;
3196
3197 // TODO: Should this accept following -stdlib to override?
3198 if (DriverArgs.hasArg(Ids: options::OPT_no_offloadlib,
3199 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nostdlib))
3200 return false;
3201 }
3202
3203 bool FilenameSearch = LibclcNamespec.consume_front(Prefix: ":");
3204 if (FilenameSearch) {
3205 SmallString<128> LibclcFile(LibclcNamespec);
3206 if (D.getVFS().exists(Path: LibclcFile)) {
3207 CC1Args.push_back(Elt: "-mlink-builtin-bitcode");
3208 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: LibclcFile));
3209 return true;
3210 }
3211 D.Diag(DiagID: diag::err_drv_libclc_not_found) << LibclcFile;
3212 return false;
3213 }
3214
3215 // The OpenCL libraries are stored in <ResourceDir>/lib/<triple>.
3216 SmallString<128> ResourceLibPath(D.ResourceDir);
3217 llvm::sys::path::append(path&: ResourceLibPath, a: "lib");
3218
3219 StringRef CPU;
3220 if (const Arg *CPUArg = DriverArgs.getLastArg(Ids: options::OPT_mcpu_EQ))
3221 CPU = CPUArg->getValue();
3222
3223 // Helper to check for libclc.bc in a specific triple directory.
3224 auto TryTriplePath = [&](StringRef TripleStr) -> bool {
3225 SmallString<128> BasePath(ResourceLibPath);
3226 llvm::sys::path::append(path&: BasePath, a: TripleStr);
3227
3228 // First check for a CPU-specific library in
3229 // <ResourceDir>/lib/<triple>/<CPU>.
3230 // TODO: Factor this into common logic that checks for valid subtargets.
3231 if (!CPU.empty()) {
3232 SmallString<128> CPUPath(BasePath);
3233 llvm::sys::path::append(path&: CPUPath, a: CPU, b: "libclc.bc");
3234 if (D.getVFS().exists(Path: CPUPath)) {
3235 CC1Args.push_back(Elt: "-mlink-builtin-bitcode");
3236 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: CPUPath));
3237 return true;
3238 }
3239 }
3240
3241 // Fall back to the generic library for the triple.
3242 SmallString<128> GenericPath(BasePath);
3243 llvm::sys::path::append(path&: GenericPath, a: "libclc.bc");
3244 if (D.getVFS().exists(Path: GenericPath)) {
3245 CC1Args.push_back(Elt: "-mlink-builtin-bitcode");
3246 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: GenericPath));
3247 return true;
3248 }
3249 return false;
3250 };
3251
3252 // First, try the exact target triple.
3253 if (TryTriplePath(TT.str()))
3254 return true;
3255
3256 llvm::Triple::SubArchType SubArch = TT.getSubArch();
3257 if (TT.isAMDGCN() && SubArch != llvm::Triple::NoSubArch) {
3258 // For AMDGPU with a subarch, try major version and generic fallbacks.
3259 // 1. Specific subarch (e.g., amdgpu9.0a-amd-amdhsa)
3260 // 2. Major subarch (e.g., amdgpu9-amd-amdhsa)
3261 // 3. Generic triple (e.g., amdgpu-amd-amdhsa)
3262 llvm::Triple::SubArchType MajorSubArch =
3263 llvm::AMDGPU::getMajorSubArch(SubArch);
3264 if (MajorSubArch != SubArch) {
3265 llvm::Triple MajorTT(TT);
3266 MajorTT.setArch(Kind: TT.getArch(), SubArch: MajorSubArch);
3267 if (TryTriplePath(MajorTT.str()))
3268 return true;
3269 }
3270
3271 // Try generic amdgpu triple without any subarch.
3272 llvm::Triple NoSubArchTT(TT);
3273 NoSubArchTT.setArch(Kind: TT.getArch(), SubArch: llvm::Triple::NoSubArch);
3274 if (TryTriplePath(NoSubArchTT.str()))
3275 return true;
3276 }
3277
3278 D.Diag(DiagID: diag::err_drv_libclc_not_found) << "libclc.bc";
3279 return false;
3280}
3281
3282void tools::addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC,
3283 const llvm::opt::ArgList &Args,
3284 llvm::opt::ArgStringList &CmdArgs,
3285 const llvm::Triple &Triple) {
3286 if (Arg *A = Args.getLastArg(Ids: options::OPT_moutline_atomics,
3287 Ids: options::OPT_mno_outline_atomics)) {
3288 // Option -moutline-atomics supported for AArch64 target only.
3289 if (!Triple.isAArch64()) {
3290 D.Diag(DiagID: diag::warn_drv_moutline_atomics_unsupported_opt)
3291 << Triple.getArchName() << A->getOption().getName();
3292 } else {
3293 if (A->getOption().matches(ID: options::OPT_moutline_atomics)) {
3294 CmdArgs.push_back(Elt: "-target-feature");
3295 CmdArgs.push_back(Elt: "+outline-atomics");
3296 } else {
3297 CmdArgs.push_back(Elt: "-target-feature");
3298 CmdArgs.push_back(Elt: "-outline-atomics");
3299 }
3300 }
3301 } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) {
3302 CmdArgs.push_back(Elt: "-target-feature");
3303 CmdArgs.push_back(Elt: "+outline-atomics");
3304 }
3305}
3306
3307void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs,
3308 llvm::opt::ArgStringList &CmdArgs) {
3309 if (TCArgs.hasFlag(Pos: options::OPT_offload_compress,
3310 Neg: options::OPT_no_offload_compress, Default: false))
3311 CmdArgs.push_back(Elt: "--compress");
3312 if (TCArgs.hasArg(Ids: options::OPT_v))
3313 CmdArgs.push_back(Elt: "--verbose");
3314 if (auto *Arg = TCArgs.getLastArg(Ids: options::OPT_offload_compression_level_EQ))
3315 CmdArgs.push_back(
3316 Elt: TCArgs.MakeArgString(Str: Twine("--compression-level=") + Arg->getValue()));
3317}
3318
3319void tools::addMCModel(const Driver &D, const llvm::opt::ArgList &Args,
3320 const llvm::Triple &Triple,
3321 const llvm::Reloc::Model &RelocationModel,
3322 llvm::opt::ArgStringList &CmdArgs) {
3323 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcmodel_EQ)) {
3324 StringRef CM = A->getValue();
3325 bool Ok = false;
3326 if (Triple.isOSAIX() && CM == "medium")
3327 CM = "large";
3328 if (Triple.isAArch64(PointerWidth: 64)) {
3329 Ok = CM == "tiny" || CM == "small" || CM == "large";
3330 if (CM == "large" && !Triple.isOSBinFormatMachO() &&
3331 RelocationModel != llvm::Reloc::Static)
3332 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3333 << A->getAsString(Args) << "-fno-pic";
3334 } else if (Triple.isLoongArch()) {
3335 if (CM == "extreme" &&
3336 Args.hasFlagNoClaim(Pos: options::OPT_fplt, Neg: options::OPT_fno_plt, Default: false))
3337 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3338 << A->getAsString(Args) << "-fplt";
3339 Ok = CM == "normal" || CM == "medium" || CM == "extreme";
3340 // Convert to LLVM recognizable names.
3341 if (Ok)
3342 CM = llvm::StringSwitch<StringRef>(CM)
3343 .Case(S: "normal", Value: "small")
3344 .Case(S: "extreme", Value: "large")
3345 .Default(Value: CM);
3346 } else if (Triple.isPPC64() || Triple.isOSAIX()) {
3347 Ok = CM == "small" || CM == "medium" || CM == "large";
3348 } else if (Triple.isRISCV()) {
3349 // Large code model is disallowed to be used with PIC code model.
3350 if (CM == "large" && RelocationModel != llvm::Reloc::Static)
3351 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3352 << A->getAsString(Args) << "-fpic";
3353 if (CM == "medlow")
3354 CM = "small";
3355 else if (CM == "medany")
3356 CM = "medium";
3357 Ok = CM == "small" || CM == "medium" ||
3358 (CM == "large" && Triple.isRISCV64());
3359 } else if (Triple.getArch() == llvm::Triple::x86_64) {
3360 Ok = llvm::is_contained(Set: {"small", "kernel", "medium", "large"}, Element: CM);
3361 } else if (Triple.isNVPTX() || Triple.isAMDGPU() || Triple.isSPIRV()) {
3362 // NVPTX/AMDGPU/SPIRV does not care about the code model and will accept
3363 // whatever works for the host.
3364 Ok = true;
3365 } else if (Triple.isSPARC64()) {
3366 if (CM == "medlow")
3367 CM = "small";
3368 else if (CM == "medmid")
3369 CM = "medium";
3370 else if (CM == "medany")
3371 CM = "large";
3372 Ok = CM == "small" || CM == "medium" || CM == "large";
3373 } else if (Triple.getArch() == llvm::Triple::lanai) {
3374 Ok = llvm::is_contained(Set: {"small", "medium", "large"}, Element: CM);
3375 }
3376 if (Ok) {
3377 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mcmodel=" + CM));
3378 } else {
3379 D.Diag(DiagID: diag::err_drv_unsupported_option_argument_for_target)
3380 << A->getSpelling() << CM << Triple.getTriple();
3381 }
3382 }
3383
3384 if (Triple.getArch() == llvm::Triple::x86_64) {
3385 bool IsMediumCM = false;
3386 bool IsLargeCM = false;
3387 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcmodel_EQ)) {
3388 IsMediumCM = StringRef(A->getValue()) == "medium";
3389 IsLargeCM = StringRef(A->getValue()) == "large";
3390 }
3391 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlarge_data_threshold_EQ)) {
3392 if (!IsMediumCM && !IsLargeCM) {
3393 D.Diag(DiagID: diag::warn_drv_large_data_threshold_invalid_code_model)
3394 << A->getOption().getRenderName();
3395 } else {
3396 A->render(Args, Output&: CmdArgs);
3397 }
3398 } else if (IsMediumCM) {
3399 CmdArgs.push_back(Elt: "-mlarge-data-threshold=65536");
3400 } else if (IsLargeCM) {
3401 CmdArgs.push_back(Elt: "-mlarge-data-threshold=0");
3402 }
3403 }
3404}
3405
3406void tools::handleColorDiagnosticsArgs(const Driver &D, const ArgList &Args,
3407 ArgStringList &CmdArgs) {
3408 // Color diagnostics are parsed by the driver directly from argv and later
3409 // re-parsed to construct this job; claim any possible color diagnostic here
3410 // to avoid warn_drv_unused_argument and diagnose bad
3411 // OPT_fdiagnostics_color_EQ values.
3412 Args.getLastArg(Ids: options::OPT_fcolor_diagnostics,
3413 Ids: options::OPT_fno_color_diagnostics);
3414 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_color_EQ)) {
3415 StringRef Value(A->getValue());
3416 if (Value != "always" && Value != "never" && Value != "auto")
3417 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
3418 << Value << A->getOption().getName();
3419 }
3420
3421 switch (D.getDiags().getDiagnosticOptions().getShowColors()) {
3422 case ShowColorsKind::On:
3423 CmdArgs.push_back(Elt: "-fcolor-diagnostics");
3424 break;
3425 case ShowColorsKind::Off:
3426 CmdArgs.push_back(Elt: "-fno-color-diagnostics");
3427 break;
3428 case ShowColorsKind::Auto:
3429 break;
3430 }
3431}
3432
3433void tools::escapeSpacesAndBackslashes(const char *Arg,
3434 llvm::SmallVectorImpl<char> &Res) {
3435 for (; *Arg; ++Arg) {
3436 switch (*Arg) {
3437 default:
3438 break;
3439 case ' ':
3440 case '\\':
3441 Res.push_back(Elt: '\\');
3442 break;
3443 }
3444 Res.push_back(Elt: *Arg);
3445 }
3446}
3447
3448const char *tools::renderEscapedCommandLine(const ToolChain &TC,
3449 const llvm::opt::ArgList &Args) {
3450 const Driver &D = TC.getDriver();
3451 const char *Exec = D.getDriverProgramPath();
3452
3453 llvm::opt::ArgStringList OriginalArgs;
3454 for (const auto &Arg : Args)
3455 Arg->render(Args, Output&: OriginalArgs);
3456
3457 llvm::SmallString<256> Flags;
3458 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
3459 for (const char *OriginalArg : OriginalArgs) {
3460 llvm::SmallString<128> EscapedArg;
3461 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
3462 Flags += " ";
3463 Flags += EscapedArg;
3464 }
3465
3466 return Args.MakeArgString(Str: Flags);
3467}
3468
3469bool tools::shouldRecordCommandLine(const ToolChain &TC,
3470 const llvm::opt::ArgList &Args,
3471 bool &FRecordCommandLine,
3472 bool &GRecordCommandLine,
3473 bool &DXRecordCommandLine) {
3474 const Driver &D = TC.getDriver();
3475 const llvm::Triple &Triple = TC.getEffectiveTriple();
3476 const std::string &TripleStr = Triple.getTriple();
3477
3478 FRecordCommandLine =
3479 Args.hasFlag(Pos: options::OPT_frecord_command_line,
3480 Neg: options::OPT_fno_record_command_line, Default: false);
3481 GRecordCommandLine =
3482 Args.hasFlag(Pos: options::OPT_grecord_command_line,
3483 Neg: options::OPT_gno_record_command_line, Default: false);
3484 DXRecordCommandLine = Triple.isDXIL() && Args.hasArg(Ids: options::OPT_g_Flag);
3485 if (FRecordCommandLine && !Triple.isOSBinFormatELF() &&
3486 !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
3487 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3488 << Args.getLastArg(Ids: options::OPT_frecord_command_line)->getAsString(Args)
3489 << TripleStr;
3490
3491 return FRecordCommandLine || TC.UseDwarfDebugFlags() || GRecordCommandLine ||
3492 DXRecordCommandLine;
3493}
3494
3495void tools::renderGlobalISelOptions(const Driver &D, const ArgList &Args,
3496 ArgStringList &CmdArgs,
3497 const llvm::Triple &Triple) {
3498 if (Arg *A = Args.getLastArg(Ids: options::OPT_fglobal_isel,
3499 Ids: options::OPT_fno_global_isel)) {
3500 CmdArgs.push_back(Elt: "-mllvm");
3501 if (A->getOption().matches(ID: options::OPT_fglobal_isel)) {
3502 CmdArgs.push_back(Elt: "-global-isel=1");
3503
3504 // GISel is on by default on AArch64 -O0, so don't bother adding
3505 // the fallback remarks for it. Other combinations will add a warning of
3506 // some kind.
3507 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
3508 bool IsOptLevelSupported = false;
3509
3510 Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
3511 if (IsArchSupported) {
3512 if (!A || A->getOption().matches(ID: options::OPT_O0))
3513 IsOptLevelSupported = true;
3514 }
3515 if (!IsArchSupported || !IsOptLevelSupported) {
3516 CmdArgs.push_back(Elt: "-mllvm");
3517 CmdArgs.push_back(Elt: "-global-isel-abort=2");
3518
3519 if (!IsArchSupported)
3520 D.Diag(DiagID: diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
3521 else
3522 D.Diag(DiagID: diag::warn_drv_global_isel_incomplete_opt);
3523 }
3524 } else {
3525 CmdArgs.push_back(Elt: "-global-isel=0");
3526 }
3527 }
3528}
3529
3530void tools::renderCommonIntegerOverflowOptions(const ArgList &Args,
3531 ArgStringList &CmdArgs,
3532 bool IsMSVCCompat) {
3533 bool use_fwrapv = IsMSVCCompat;
3534 bool use_fwrapv_pointer = false;
3535 for (const Arg *A : Args.filtered(
3536 Ids: options::OPT_fstrict_overflow, Ids: options::OPT_fno_strict_overflow,
3537 Ids: options::OPT_fwrapv, Ids: options::OPT_fno_wrapv,
3538 Ids: options::OPT_fwrapv_pointer, Ids: options::OPT_fno_wrapv_pointer)) {
3539 A->claim();
3540 switch (A->getOption().getID()) {
3541 case options::OPT_fstrict_overflow:
3542 use_fwrapv = false;
3543 use_fwrapv_pointer = false;
3544 break;
3545 case options::OPT_fno_strict_overflow:
3546 use_fwrapv = true;
3547 use_fwrapv_pointer = true;
3548 break;
3549 case options::OPT_fwrapv:
3550 use_fwrapv = true;
3551 break;
3552 case options::OPT_fno_wrapv:
3553 use_fwrapv = false;
3554 break;
3555 case options::OPT_fwrapv_pointer:
3556 use_fwrapv_pointer = true;
3557 break;
3558 case options::OPT_fno_wrapv_pointer:
3559 use_fwrapv_pointer = false;
3560 break;
3561 }
3562 }
3563
3564 if (use_fwrapv)
3565 CmdArgs.push_back(Elt: "-fwrapv");
3566 if (!use_fwrapv && IsMSVCCompat)
3567 CmdArgs.push_back(Elt: "-fno-wrapv");
3568 if (use_fwrapv_pointer)
3569 CmdArgs.push_back(Elt: "-fwrapv-pointer");
3570}
3571
3572/// Vectorize at all optimization levels greater than 1 except for -Oz.
3573/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
3574/// enabled.
3575bool tools::shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
3576 if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
3577 if (A->getOption().matches(ID: options::OPT_O4) ||
3578 A->getOption().matches(ID: options::OPT_Ofast))
3579 return true;
3580
3581 if (A->getOption().matches(ID: options::OPT_O0))
3582 return false;
3583
3584 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3585
3586 // Vectorize -Os.
3587 StringRef S(A->getValue());
3588 if (S == "s")
3589 return true;
3590
3591 // Don't vectorize -Oz, unless it's the slp vectorizer.
3592 if (S == "z")
3593 return isSlpVec;
3594
3595 unsigned OptLevel = 0;
3596 if (S.getAsInteger(Radix: 10, Result&: OptLevel))
3597 return false;
3598
3599 return OptLevel > 1;
3600 }
3601
3602 return false;
3603}
3604
3605void tools::handleVectorizeLoopsArgs(const ArgList &Args,
3606 ArgStringList &CmdArgs) {
3607 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, isSlpVec: false);
3608 if (Args.hasFlag(Pos: options::OPT_fvectorize, Neg: options::OPT_fno_vectorize,
3609 Default: EnableVec))
3610 CmdArgs.push_back(Elt: "-vectorize-loops");
3611}
3612
3613void tools::handleVectorizeSLPArgs(const ArgList &Args,
3614 ArgStringList &CmdArgs) {
3615 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, isSlpVec: true);
3616 if (Args.hasFlag(Pos: options::OPT_fslp_vectorize, Neg: options::OPT_fno_slp_vectorize,
3617 Default: EnableSLPVec))
3618 CmdArgs.push_back(Elt: "-vectorize-slp");
3619}
3620
3621void tools::handleInterchangeLoopsArgs(const ArgList &Args,
3622 ArgStringList &CmdArgs) {
3623 if (Args.hasFlag(Pos: options::OPT_floop_interchange,
3624 Neg: options::OPT_fno_loop_interchange, Default: false))
3625 CmdArgs.push_back(Elt: "-floop-interchange");
3626}
3627
3628std::string tools::complexRangeKindToStr(LangOptions::ComplexRangeKind Range) {
3629 switch (Range) {
3630 case LangOptions::ComplexRangeKind::CX_Full:
3631 return "full";
3632 break;
3633 case LangOptions::ComplexRangeKind::CX_Basic:
3634 return "basic";
3635 break;
3636 case LangOptions::ComplexRangeKind::CX_Improved:
3637 return "improved";
3638 break;
3639 case LangOptions::ComplexRangeKind::CX_Promoted:
3640 return "promoted";
3641 break;
3642 case LangOptions::ComplexRangeKind::CX_None:
3643 return "none";
3644 break;
3645 }
3646 llvm_unreachable("Fully covered switch above");
3647}
3648
3649std::string
3650tools::renderComplexRangeOption(LangOptionsBase::ComplexRangeKind Range) {
3651 std::string ComplexRangeStr = complexRangeKindToStr(Range);
3652 if (!ComplexRangeStr.empty())
3653 return "-complex-range=" + ComplexRangeStr;
3654 return ComplexRangeStr;
3655}
3656
3657static void emitComplexRangeDiag(const Driver &D, StringRef LastOpt,
3658 LangOptions::ComplexRangeKind Range,
3659 StringRef NewOpt,
3660 LangOptions::ComplexRangeKind NewRange) {
3661 // Do not emit a warning if NewOpt overrides LastOpt in the following cases.
3662 //
3663 // | LastOpt | NewOpt |
3664 // |-----------------------|-----------------------|
3665 // | -fcx-limited-range | -fno-cx-limited-range |
3666 // | -fno-cx-limited-range | -fcx-limited-range |
3667 // | -fcx-fortran-rules | -fno-cx-fortran-rules |
3668 // | -fno-cx-fortran-rules | -fcx-fortran-rules |
3669 // | -ffast-math | -fno-fast-math |
3670 // | -ffp-model= | -ffast-math |
3671 // | -ffp-model= | -fno-fast-math |
3672 // | -ffp-model= | -ffp-model= |
3673 // | -fcomplex-arithmetic= | -fcomplex-arithmetic= |
3674 if (LastOpt == NewOpt || NewOpt.empty() || LastOpt.empty() ||
3675 (LastOpt == "-fcx-limited-range" && NewOpt == "-fno-cx-limited-range") ||
3676 (LastOpt == "-fno-cx-limited-range" && NewOpt == "-fcx-limited-range") ||
3677 (LastOpt == "-fcx-fortran-rules" && NewOpt == "-fno-cx-fortran-rules") ||
3678 (LastOpt == "-fno-cx-fortran-rules" && NewOpt == "-fcx-fortran-rules") ||
3679 (LastOpt == "-ffast-math" && NewOpt == "-fno-fast-math") ||
3680 (LastOpt.starts_with(Prefix: "-ffp-model=") && NewOpt == "-ffast-math") ||
3681 (LastOpt.starts_with(Prefix: "-ffp-model=") && NewOpt == "-fno-fast-math") ||
3682 (LastOpt.starts_with(Prefix: "-ffp-model=") &&
3683 NewOpt.starts_with(Prefix: "-ffp-model=")) ||
3684 (LastOpt.starts_with(Prefix: "-fcomplex-arithmetic=") &&
3685 NewOpt.starts_with(Prefix: "-fcomplex-arithmetic=")))
3686 return;
3687
3688 D.Diag(DiagID: clang::diag::warn_drv_overriding_complex_range)
3689 << LastOpt << NewOpt << complexRangeKindToStr(Range)
3690 << complexRangeKindToStr(Range: NewRange);
3691}
3692
3693void tools::setComplexRange(const Driver &D, StringRef NewOpt,
3694 LangOptions::ComplexRangeKind NewRange,
3695 StringRef &LastOpt,
3696 LangOptions::ComplexRangeKind &Range) {
3697 // Warn if user overrides the previously set complex number
3698 // multiplication/division option.
3699 if (Range != LangOptions::ComplexRangeKind::CX_None && Range != NewRange)
3700 emitComplexRangeDiag(D, LastOpt, Range, NewOpt, NewRange);
3701 LastOpt = NewOpt;
3702 Range = NewRange;
3703}
3704
3705void tools::constructLLVMLinkCommand(Compilation &C, const Tool &T,
3706 const JobAction &JA,
3707 const InputInfoList &JobInputs,
3708 const ArgStringList &LinkerInputs,
3709 const InputInfo &Output,
3710 const llvm::opt::ArgList &Args,
3711 const char *OutputFilename) {
3712 // Construct llvm-link command.
3713 // The output from llvm-link is a bitcode file.
3714
3715 assert(!LinkerInputs.empty() && !JobInputs.empty() &&
3716 "Must have at least one input.");
3717
3718 ArgStringList LlvmLinkArgs(
3719 {"-o", OutputFilename ? OutputFilename : Output.getFilename()});
3720
3721 LlvmLinkArgs.append(RHS: LinkerInputs);
3722
3723 const ToolChain &TC = T.getToolChain();
3724 const char *LlvmLink = Args.MakeArgString(Str: TC.GetProgramPath(Name: "llvm-link"));
3725 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: T, args: ResponseFileSupport::None(),
3726 args&: LlvmLink, args&: LlvmLinkArgs, args: JobInputs,
3727 args: Output));
3728}
3729