Bug Summary

File:build/source/clang/lib/Driver/ToolChains/CommonArgs.cpp
Warning:line 2199, column 7
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CommonArgs.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -I tools/clang/lib/Driver -I /build/source/clang/lib/Driver -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1670066131 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-12-03-132955-15984-1 -x c++ /build/source/clang/lib/Driver/ToolChains/CommonArgs.cpp
1//===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "CommonArgs.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/CSKY.h"
13#include "Arch/LoongArch.h"
14#include "Arch/M68k.h"
15#include "Arch/Mips.h"
16#include "Arch/PPC.h"
17#include "Arch/RISCV.h"
18#include "Arch/Sparc.h"
19#include "Arch/SystemZ.h"
20#include "Arch/VE.h"
21#include "Arch/X86.h"
22#include "HIPAMD.h"
23#include "Hexagon.h"
24#include "MSP430.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/ObjCRuntime.h"
28#include "clang/Basic/Version.h"
29#include "clang/Config/config.h"
30#include "clang/Driver/Action.h"
31#include "clang/Driver/Compilation.h"
32#include "clang/Driver/Driver.h"
33#include "clang/Driver/DriverDiagnostic.h"
34#include "clang/Driver/InputInfo.h"
35#include "clang/Driver/Job.h"
36#include "clang/Driver/Options.h"
37#include "clang/Driver/SanitizerArgs.h"
38#include "clang/Driver/ToolChain.h"
39#include "clang/Driver/Util.h"
40#include "clang/Driver/XRayArgs.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/SmallSet.h"
43#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/ADT/StringSwitch.h"
46#include "llvm/ADT/Twine.h"
47#include "llvm/BinaryFormat/Magic.h"
48#include "llvm/Config/llvm-config.h"
49#include "llvm/Option/Arg.h"
50#include "llvm/Option/ArgList.h"
51#include "llvm/Option/Option.h"
52#include "llvm/Support/CodeGen.h"
53#include "llvm/Support/Compression.h"
54#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/FileSystem.h"
57#include "llvm/Support/Host.h"
58#include "llvm/Support/Path.h"
59#include "llvm/Support/Process.h"
60#include "llvm/Support/Program.h"
61#include "llvm/Support/ScopedPrinter.h"
62#include "llvm/Support/TargetParser.h"
63#include "llvm/Support/Threading.h"
64#include "llvm/Support/VirtualFileSystem.h"
65#include "llvm/Support/YAMLParser.h"
66
67using namespace clang::driver;
68using namespace clang::driver::tools;
69using namespace clang;
70using namespace llvm::opt;
71
72static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs,
73 const StringRef PluginOptPrefix) {
74 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
75 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
76 "-pass-remarks=" + A->getValue()));
77
78 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
79 CmdArgs.push_back(Args.MakeArgString(
80 Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue()));
81
82 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
83 CmdArgs.push_back(Args.MakeArgString(
84 Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue()));
85}
86
87static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
88 const llvm::Triple &Triple,
89 const InputInfo &Input,
90 const InputInfo &Output,
91 const StringRef PluginOptPrefix) {
92 StringRef Format = "yaml";
93 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
94 Format = A->getValue();
95
96 SmallString<128> F;
97 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
98 if (A)
99 F = A->getValue();
100 else if (Output.isFilename())
101 F = Output.getFilename();
102
103 assert(!F.empty() && "Cannot determine remarks output name.")(static_cast <bool> (!F.empty() && "Cannot determine remarks output name."
) ? void (0) : __assert_fail ("!F.empty() && \"Cannot determine remarks output name.\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 103, __extension__
__PRETTY_FUNCTION__))
;
104 // Append "opt.ld.<format>" to the end of the file name.
105 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
106 "opt-remarks-filename=" + F +
107 ".opt.ld." + Format));
108
109 if (const Arg *A =
110 Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
111 CmdArgs.push_back(Args.MakeArgString(
112 Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue()));
113
114 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
115 "opt-remarks-format=" + Format.data()));
116}
117
118static void renderRemarksHotnessOptions(const ArgList &Args,
119 ArgStringList &CmdArgs,
120 const StringRef PluginOptPrefix) {
121 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
122 options::OPT_fno_diagnostics_show_hotness, false))
123 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
124 "opt-remarks-with-hotness"));
125
126 if (const Arg *A =
127 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
128 CmdArgs.push_back(
129 Args.MakeArgString(Twine(PluginOptPrefix) +
130 "opt-remarks-hotness-threshold=" + A->getValue()));
131}
132
133void tools::addPathIfExists(const Driver &D, const Twine &Path,
134 ToolChain::path_list &Paths) {
135 if (D.getVFS().exists(Path))
136 Paths.push_back(Path.str());
137}
138
139void tools::handleTargetFeaturesGroup(const ArgList &Args,
140 std::vector<StringRef> &Features,
141 OptSpecifier Group) {
142 for (const Arg *A : Args.filtered(Group)) {
143 StringRef Name = A->getOption().getName();
144 A->claim();
145
146 // Skip over "-m".
147 assert(Name.startswith("m") && "Invalid feature name.")(static_cast <bool> (Name.startswith("m") && "Invalid feature name."
) ? void (0) : __assert_fail ("Name.startswith(\"m\") && \"Invalid feature name.\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 147, __extension__
__PRETTY_FUNCTION__))
;
148 Name = Name.substr(1);
149
150 bool IsNegative = Name.startswith("no-");
151 if (IsNegative)
152 Name = Name.substr(3);
153 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
154 }
155}
156
157SmallVector<StringRef>
158tools::unifyTargetFeatures(ArrayRef<StringRef> Features) {
159 // Only add a feature if it hasn't been seen before starting from the end.
160 SmallVector<StringRef> UnifiedFeatures;
161 llvm::DenseSet<StringRef> UsedFeatures;
162 for (StringRef Feature : llvm::reverse(Features)) {
163 if (UsedFeatures.insert(Feature.drop_front()).second)
164 UnifiedFeatures.insert(UnifiedFeatures.begin(), Feature);
165 }
166
167 return UnifiedFeatures;
168}
169
170void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
171 const char *ArgName, const char *EnvVar) {
172 const char *DirList = ::getenv(EnvVar);
173 bool CombinedArg = false;
174
175 if (!DirList)
176 return; // Nothing to do.
177
178 StringRef Name(ArgName);
179 if (Name.equals("-I") || Name.equals("-L") || Name.empty())
180 CombinedArg = true;
181
182 StringRef Dirs(DirList);
183 if (Dirs.empty()) // Empty string should not add '.'.
184 return;
185
186 StringRef::size_type Delim;
187 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
188 if (Delim == 0) { // Leading colon.
189 if (CombinedArg) {
190 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
191 } else {
192 CmdArgs.push_back(ArgName);
193 CmdArgs.push_back(".");
194 }
195 } else {
196 if (CombinedArg) {
197 CmdArgs.push_back(
198 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
199 } else {
200 CmdArgs.push_back(ArgName);
201 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
202 }
203 }
204 Dirs = Dirs.substr(Delim + 1);
205 }
206
207 if (Dirs.empty()) { // Trailing colon.
208 if (CombinedArg) {
209 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
210 } else {
211 CmdArgs.push_back(ArgName);
212 CmdArgs.push_back(".");
213 }
214 } else { // Add the last path.
215 if (CombinedArg) {
216 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
217 } else {
218 CmdArgs.push_back(ArgName);
219 CmdArgs.push_back(Args.MakeArgString(Dirs));
220 }
221 }
222}
223
224void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
225 const ArgList &Args, ArgStringList &CmdArgs,
226 const JobAction &JA) {
227 const Driver &D = TC.getDriver();
228
229 // Add extra linker input arguments which are not treated as inputs
230 // (constructed via -Xarch_).
231 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
232
233 // LIBRARY_PATH are included before user inputs and only supported on native
234 // toolchains.
235 if (!TC.isCrossCompiling())
236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
237
238 for (const auto &II : Inputs) {
239 // If the current tool chain refers to an OpenMP offloading host, we
240 // should ignore inputs that refer to OpenMP offloading devices -
241 // they will be embedded according to a proper linker script.
242 if (auto *IA = II.getAction())
243 if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
244 IA->isDeviceOffloading(Action::OFK_OpenMP)))
245 continue;
246
247 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
248 // Don't try to pass LLVM inputs unless we have native support.
249 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
250
251 // Add filenames immediately.
252 if (II.isFilename()) {
253 CmdArgs.push_back(II.getFilename());
254 continue;
255 }
256
257 // In some error cases, the input could be Nothing; skip those.
258 if (II.isNothing())
259 continue;
260
261 // Otherwise, this is a linker input argument.
262 const Arg &A = II.getInputArg();
263
264 // Handle reserved library options.
265 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
266 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
267 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
268 TC.AddCCKextLibArgs(Args, CmdArgs);
269 else if (A.getOption().matches(options::OPT_z)) {
270 // Pass -z prefix for gcc linker compatibility.
271 A.claim();
272 A.render(Args, CmdArgs);
273 } else if (A.getOption().matches(options::OPT_b)) {
274 const llvm::Triple &T = TC.getTriple();
275 if (!T.isOSAIX()) {
276 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
277 << A.getSpelling() << T.str();
278 }
279 // Pass -b prefix for AIX linker.
280 A.claim();
281 A.render(Args, CmdArgs);
282 } else {
283 A.renderAsInput(Args, CmdArgs);
284 }
285 }
286}
287
288void tools::addLinkerCompressDebugSectionsOption(
289 const ToolChain &TC, const llvm::opt::ArgList &Args,
290 llvm::opt::ArgStringList &CmdArgs) {
291 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
292 // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
293 // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
294 // is not translated since ld --compress-debug-sections option requires an
295 // argument.
296 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
297 StringRef V = A->getValue();
298 if (V == "none" || V == "zlib" || V == "zstd")
299 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
300 else
301 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
302 << A->getSpelling() << V;
303 }
304}
305
306void tools::AddTargetFeature(const ArgList &Args,
307 std::vector<StringRef> &Features,
308 OptSpecifier OnOpt, OptSpecifier OffOpt,
309 StringRef FeatureName) {
310 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
311 if (A->getOption().matches(OnOpt))
312 Features.push_back(Args.MakeArgString("+" + FeatureName));
313 else
314 Features.push_back(Args.MakeArgString("-" + FeatureName));
315 }
316}
317
318/// Get the (LLVM) name of the AMDGPU gpu we are targeting.
319static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
320 const ArgList &Args) {
321 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
322 auto GPUName = getProcessorFromTargetID(T, A->getValue());
323 return llvm::StringSwitch<std::string>(GPUName)
324 .Cases("rv630", "rv635", "r600")
325 .Cases("rv610", "rv620", "rs780", "rs880")
326 .Case("rv740", "rv770")
327 .Case("palm", "cedar")
328 .Cases("sumo", "sumo2", "sumo")
329 .Case("hemlock", "cypress")
330 .Case("aruba", "cayman")
331 .Default(GPUName.str());
332 }
333 return "";
334}
335
336static std::string getLanaiTargetCPU(const ArgList &Args) {
337 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
338 return A->getValue();
339 }
340 return "";
341}
342
343/// Get the (LLVM) name of the WebAssembly cpu we are targeting.
344static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
345 // If we have -mcpu=, use that.
346 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
347 StringRef CPU = A->getValue();
348
349#ifdef __wasm__
350 // Handle "native" by examining the host. "native" isn't meaningful when
351 // cross compiling, so only support this when the host is also WebAssembly.
352 if (CPU == "native")
353 return llvm::sys::getHostCPUName();
354#endif
355
356 return CPU;
357 }
358
359 return "generic";
360}
361
362std::string tools::getCPUName(const Driver &D, const ArgList &Args,
363 const llvm::Triple &T, bool FromAs) {
364 Arg *A;
365
366 switch (T.getArch()) {
367 default:
368 return "";
369
370 case llvm::Triple::aarch64:
371 case llvm::Triple::aarch64_32:
372 case llvm::Triple::aarch64_be:
373 return aarch64::getAArch64TargetCPU(Args, T, A);
374
375 case llvm::Triple::arm:
376 case llvm::Triple::armeb:
377 case llvm::Triple::thumb:
378 case llvm::Triple::thumbeb: {
379 StringRef MArch, MCPU;
380 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
381 return arm::getARMTargetCPU(MCPU, MArch, T);
382 }
383
384 case llvm::Triple::avr:
385 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
386 return A->getValue();
387 return "";
388
389 case llvm::Triple::m68k:
390 return m68k::getM68kTargetCPU(Args);
391
392 case llvm::Triple::mips:
393 case llvm::Triple::mipsel:
394 case llvm::Triple::mips64:
395 case llvm::Triple::mips64el: {
396 StringRef CPUName;
397 StringRef ABIName;
398 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
399 return std::string(CPUName);
400 }
401
402 case llvm::Triple::nvptx:
403 case llvm::Triple::nvptx64:
404 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
405 return A->getValue();
406 return "";
407
408 case llvm::Triple::ppc:
409 case llvm::Triple::ppcle:
410 case llvm::Triple::ppc64:
411 case llvm::Triple::ppc64le: {
412 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
413 // LLVM may default to generating code for the native CPU,
414 // but, like gcc, we default to a more generic option for
415 // each architecture. (except on AIX)
416 if (!TargetCPUName.empty())
417 return TargetCPUName;
418
419 if (T.isOSAIX())
420 TargetCPUName = "pwr7";
421 else if (T.getArch() == llvm::Triple::ppc64le)
422 TargetCPUName = "ppc64le";
423 else if (T.getArch() == llvm::Triple::ppc64)
424 TargetCPUName = "ppc64";
425 else
426 TargetCPUName = "ppc";
427
428 return TargetCPUName;
429 }
430 case llvm::Triple::csky:
431 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
432 return A->getValue();
433 else if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
434 return A->getValue();
435 else
436 return "ck810";
437 case llvm::Triple::riscv32:
438 case llvm::Triple::riscv64:
439 return riscv::getRISCVTargetCPU(Args, T);
440
441 case llvm::Triple::bpfel:
442 case llvm::Triple::bpfeb:
443 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
444 return A->getValue();
445 return "";
446
447 case llvm::Triple::sparc:
448 case llvm::Triple::sparcel:
449 case llvm::Triple::sparcv9:
450 return sparc::getSparcTargetCPU(D, Args, T);
451
452 case llvm::Triple::x86:
453 case llvm::Triple::x86_64:
454 return x86::getX86TargetCPU(D, Args, T);
455
456 case llvm::Triple::hexagon:
457 return "hexagon" +
458 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
459
460 case llvm::Triple::lanai:
461 return getLanaiTargetCPU(Args);
462
463 case llvm::Triple::systemz:
464 return systemz::getSystemZTargetCPU(Args);
465
466 case llvm::Triple::r600:
467 case llvm::Triple::amdgcn:
468 return getAMDGPUTargetGPU(T, Args);
469
470 case llvm::Triple::wasm32:
471 case llvm::Triple::wasm64:
472 return std::string(getWebAssemblyTargetCPU(Args));
473 }
474}
475
476static void getWebAssemblyTargetFeatures(const ArgList &Args,
477 std::vector<StringRef> &Features) {
478 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
479}
480
481void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
482 const ArgList &Args, ArgStringList &CmdArgs,
483 bool ForAS, bool IsAux) {
484 std::vector<StringRef> Features;
485 switch (Triple.getArch()) {
486 default:
487 break;
488 case llvm::Triple::mips:
489 case llvm::Triple::mipsel:
490 case llvm::Triple::mips64:
491 case llvm::Triple::mips64el:
492 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
493 break;
494 case llvm::Triple::arm:
495 case llvm::Triple::armeb:
496 case llvm::Triple::thumb:
497 case llvm::Triple::thumbeb:
498 arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS);
499 break;
500 case llvm::Triple::ppc:
501 case llvm::Triple::ppcle:
502 case llvm::Triple::ppc64:
503 case llvm::Triple::ppc64le:
504 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
505 break;
506 case llvm::Triple::riscv32:
507 case llvm::Triple::riscv64:
508 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
509 break;
510 case llvm::Triple::systemz:
511 systemz::getSystemZTargetFeatures(D, Args, Features);
512 break;
513 case llvm::Triple::aarch64:
514 case llvm::Triple::aarch64_32:
515 case llvm::Triple::aarch64_be:
516 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
517 break;
518 case llvm::Triple::x86:
519 case llvm::Triple::x86_64:
520 x86::getX86TargetFeatures(D, Triple, Args, Features);
521 break;
522 case llvm::Triple::hexagon:
523 hexagon::getHexagonTargetFeatures(D, Args, Features);
524 break;
525 case llvm::Triple::wasm32:
526 case llvm::Triple::wasm64:
527 getWebAssemblyTargetFeatures(Args, Features);
528 break;
529 case llvm::Triple::sparc:
530 case llvm::Triple::sparcel:
531 case llvm::Triple::sparcv9:
532 sparc::getSparcTargetFeatures(D, Args, Features);
533 break;
534 case llvm::Triple::r600:
535 case llvm::Triple::amdgcn:
536 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
537 break;
538 case llvm::Triple::nvptx:
539 case llvm::Triple::nvptx64:
540 NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features);
541 break;
542 case llvm::Triple::m68k:
543 m68k::getM68kTargetFeatures(D, Triple, Args, Features);
544 break;
545 case llvm::Triple::msp430:
546 msp430::getMSP430TargetFeatures(D, Args, Features);
547 break;
548 case llvm::Triple::ve:
549 ve::getVETargetFeatures(D, Args, Features);
550 break;
551 case llvm::Triple::csky:
552 csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features);
553 break;
554 case llvm::Triple::loongarch32:
555 case llvm::Triple::loongarch64:
556 loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features);
557 break;
558 }
559
560 for (auto Feature : unifyTargetFeatures(Features)) {
561 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
562 CmdArgs.push_back(Feature.data());
563 }
564}
565
566llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
567 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
568 if (!LtoJobsArg)
569 return {};
570 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
571 D.Diag(diag::err_drv_invalid_int_value)
572 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
573 return LtoJobsArg->getValue();
574}
575
576// CloudABI and PS4/PS5 use -ffunction-sections and -fdata-sections by default.
577bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
578 return Triple.getOS() == llvm::Triple::CloudABI || Triple.isPS();
579}
580
581void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
582 ArgStringList &CmdArgs, const InputInfo &Output,
583 const InputInfo &Input, bool IsThinLTO) {
584 const bool IsOSAIX = ToolChain.getTriple().isOSAIX();
585 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
586 const Driver &D = ToolChain.getDriver();
587 if (llvm::sys::path::filename(Linker) != "ld.lld" &&
588 llvm::sys::path::stem(Linker) != "ld.lld") {
589 // Tell the linker to load the plugin. This has to come before
590 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
591 // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
592 const char *PluginPrefix = IsOSAIX ? "-bplugin:" : "";
593 const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold";
594
595 if (!IsOSAIX)
596 CmdArgs.push_back("-plugin");
597
598#if defined(_WIN32)
599 const char *Suffix = ".dll";
600#elif defined(__APPLE__)
601 const char *Suffix = ".dylib";
602#else
603 const char *Suffix = ".so";
604#endif
605
606 SmallString<1024> Plugin;
607 llvm::sys::path::native(Twine(D.Dir) +
608 "/../" CLANG_INSTALL_LIBDIR_BASENAME"lib" +
609 PluginName + Suffix,
610 Plugin);
611 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin));
612 }
613
614 const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
615 const char *ExtraDash = IsOSAIX ? "-" : "";
616
617 // Note, this solution is far from perfect, better to encode it into IR
618 // metadata, but this may not be worth it, since it looks like aranges is on
619 // the way out.
620 if (Args.hasArg(options::OPT_gdwarf_aranges)) {
621 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
622 "-generate-arange-section"));
623 }
624
625 // Try to pass driver level flags relevant to LTO code generation down to
626 // the plugin.
627
628 // Handle flags for selecting CPU variants.
629 std::string CPU = getCPUName(D, Args, ToolChain.getTriple());
630 if (!CPU.empty())
631 CmdArgs.push_back(
632 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU));
633
634 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
635 // The optimization level matches
636 // CompilerInvocation.cpp:getOptimizationLevel().
637 StringRef OOpt;
638 if (A->getOption().matches(options::OPT_O4) ||
639 A->getOption().matches(options::OPT_Ofast))
640 OOpt = "3";
641 else if (A->getOption().matches(options::OPT_O)) {
642 OOpt = A->getValue();
643 if (OOpt == "g")
644 OOpt = "1";
645 else if (OOpt == "s" || OOpt == "z")
646 OOpt = "2";
647 } else if (A->getOption().matches(options::OPT_O0))
648 OOpt = "0";
649 if (!OOpt.empty())
650 CmdArgs.push_back(
651 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
652 }
653
654 if (Args.hasArg(options::OPT_gsplit_dwarf))
655 CmdArgs.push_back(Args.MakeArgString(
656 Twine(PluginOptPrefix) + "dwo_dir=" + Output.getFilename() + "_dwo"));
657
658 if (IsThinLTO)
659 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + "thinlto"));
660
661 StringRef Parallelism = getLTOParallelism(Args, D);
662 if (!Parallelism.empty())
663 CmdArgs.push_back(
664 Args.MakeArgString(Twine(PluginOptPrefix) + "jobs=" + Parallelism));
665
666 // If an explicit debugger tuning argument appeared, pass it along.
667 if (Arg *A =
668 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
669 if (A->getOption().matches(options::OPT_glldb))
670 CmdArgs.push_back(
671 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=lldb"));
672 else if (A->getOption().matches(options::OPT_gsce))
673 CmdArgs.push_back(
674 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=sce"));
675 else if (A->getOption().matches(options::OPT_gdbx))
676 CmdArgs.push_back(
677 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=dbx"));
678 else
679 CmdArgs.push_back(
680 Args.MakeArgString(Twine(PluginOptPrefix) + "-debugger-tune=gdb"));
681 }
682
683 if (IsOSAIX) {
684 // On AIX, clang assumes strict-dwarf is true if any debug option is
685 // specified, unless it is told explicitly not to assume so.
686 Arg *A = Args.getLastArg(options::OPT_g_Group);
687 bool EnableDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
688 !A->getOption().matches(options::OPT_ggdb0);
689 if (EnableDebugInfo && Args.hasFlag(options::OPT_gstrict_dwarf,
690 options::OPT_gno_strict_dwarf, true))
691 CmdArgs.push_back(
692 Args.MakeArgString(Twine(PluginOptPrefix) + "-strict-dwarf=true"));
693
694 if (Args.getLastArg(options::OPT_mabi_EQ_vec_extabi))
695 CmdArgs.push_back(
696 Args.MakeArgString(Twine(PluginOptPrefix) + "-vec-extabi"));
697 }
698
699 bool UseSeparateSections =
700 isUseSeparateSections(ToolChain.getEffectiveTriple());
701
702 if (Args.hasFlag(options::OPT_ffunction_sections,
703 options::OPT_fno_function_sections, UseSeparateSections))
704 CmdArgs.push_back(
705 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=1"));
706 else if (Args.hasArg(options::OPT_fno_function_sections))
707 CmdArgs.push_back(
708 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0"));
709
710 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
711 UseSeparateSections))
712 CmdArgs.push_back(
713 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1"));
714 else if (Args.hasArg(options::OPT_fno_data_sections))
715 CmdArgs.push_back(
716 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0"));
717
718 // Pass an option to enable split machine functions.
719 if (auto *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
720 options::OPT_fno_split_machine_functions)) {
721 if (A->getOption().matches(options::OPT_fsplit_machine_functions))
722 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
723 "-split-machine-functions"));
724 }
725
726 if (Arg *A = getLastProfileSampleUseArg(Args)) {
727 StringRef FName = A->getValue();
728 if (!llvm::sys::fs::exists(FName))
729 D.Diag(diag::err_drv_no_such_file) << FName;
730 else
731 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
732 "sample-profile=" + FName));
733 }
734
735 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
736 options::OPT_fcs_profile_generate_EQ,
737 options::OPT_fno_profile_generate);
738 if (CSPGOGenerateArg &&
739 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
740 CSPGOGenerateArg = nullptr;
741
742 auto *ProfileUseArg = getLastProfileUseArg(Args);
743
744 if (CSPGOGenerateArg) {
745 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
746 "cs-profile-generate"));
747 if (CSPGOGenerateArg->getOption().matches(
748 options::OPT_fcs_profile_generate_EQ)) {
749 SmallString<128> Path(CSPGOGenerateArg->getValue());
750 llvm::sys::path::append(Path, "default_%m.profraw");
751 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
752 "cs-profile-path=" + Path));
753 } else
754 CmdArgs.push_back(
755 Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
756 "cs-profile-path=default_%m.profraw"));
757 } else if (ProfileUseArg) {
758 SmallString<128> Path(
759 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
760 if (Path.empty() || llvm::sys::fs::is_directory(Path))
761 llvm::sys::path::append(Path, "default.profdata");
762 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash +
763 "cs-profile-path=" + Path));
764 }
765
766 // This controls whether or not we perform JustMyCode instrumentation.
767 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
768 if (ToolChain.getEffectiveTriple().isOSBinFormatELF())
769 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) +
770 "-enable-jmc-instrument"));
771 else
772 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
773 }
774
775 // Setup statistics file output.
776 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
777 if (!StatsFile.empty())
778 CmdArgs.push_back(
779 Args.MakeArgString(Twine(PluginOptPrefix) + "stats-file=" + StatsFile));
780
781 // Setup crash diagnostics dir.
782 if (Arg *A = Args.getLastArg(options::OPT_fcrash_diagnostics_dir))
783 CmdArgs.push_back(Args.MakeArgString(
784 Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue()));
785
786 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix);
787
788 // Handle remark diagnostics on screen options: '-Rpass-*'.
789 renderRpassOptions(Args, CmdArgs, PluginOptPrefix);
790
791 // Handle serialized remarks options: '-fsave-optimization-record'
792 // and '-foptimization-record-*'.
793 if (willEmitRemarks(Args))
794 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
795 Output, PluginOptPrefix);
796
797 // Handle remarks hotness/threshold related options.
798 renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix);
799
800 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
801 /*IsLTO=*/true, PluginOptPrefix);
802}
803
804void tools::addOpenMPRuntimeSpecificRPath(const ToolChain &TC,
805 const ArgList &Args,
806 ArgStringList &CmdArgs) {
807
808 if (Args.hasFlag(options::OPT_fopenmp_implicit_rpath,
809 options::OPT_fno_openmp_implicit_rpath, true)) {
810 // Default to clang lib / lib64 folder, i.e. the same location as device
811 // runtime
812 SmallString<256> DefaultLibPath =
813 llvm::sys::path::parent_path(TC.getDriver().Dir);
814 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME"lib");
815 CmdArgs.push_back("-rpath");
816 CmdArgs.push_back(Args.MakeArgString(DefaultLibPath));
817 }
818}
819
820void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
821 const ArgList &Args,
822 ArgStringList &CmdArgs) {
823 // Default to clang lib / lib64 folder, i.e. the same location as device
824 // runtime.
825 SmallString<256> DefaultLibPath =
826 llvm::sys::path::parent_path(TC.getDriver().Dir);
827 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME"lib");
828 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
829}
830
831void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
832 ArgStringList &CmdArgs) {
833 // Enable -frtlib-add-rpath by default for the case of VE.
834 const bool IsVE = TC.getTriple().isVE();
835 bool DefaultValue = IsVE;
836 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
837 options::OPT_fno_rtlib_add_rpath, DefaultValue))
838 return;
839
840 std::string CandidateRPath = TC.getArchSpecificLibPath();
841 if (TC.getVFS().exists(CandidateRPath)) {
842 CmdArgs.push_back("-rpath");
843 CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
844 }
845}
846
847bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
848 const ArgList &Args, bool ForceStaticHostRuntime,
849 bool IsOffloadingHost, bool GompNeedsRT) {
850 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
851 options::OPT_fno_openmp, false))
852 return false;
853
854 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
855
856 if (RTKind == Driver::OMPRT_Unknown)
857 // Already diagnosed.
858 return false;
859
860 if (ForceStaticHostRuntime)
861 CmdArgs.push_back("-Bstatic");
862
863 switch (RTKind) {
864 case Driver::OMPRT_OMP:
865 CmdArgs.push_back("-lomp");
866 break;
867 case Driver::OMPRT_GOMP:
868 CmdArgs.push_back("-lgomp");
869 break;
870 case Driver::OMPRT_IOMP5:
871 CmdArgs.push_back("-liomp5");
872 break;
873 case Driver::OMPRT_Unknown:
874 break;
875 }
876
877 if (ForceStaticHostRuntime)
878 CmdArgs.push_back("-Bdynamic");
879
880 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
881 CmdArgs.push_back("-lrt");
882
883 if (IsOffloadingHost)
884 CmdArgs.push_back("-lomptarget");
885
886 if (IsOffloadingHost && TC.getDriver().isUsingLTO(/* IsOffload */ true) &&
887 !Args.hasArg(options::OPT_nogpulib))
888 CmdArgs.push_back("-lomptarget.devicertl");
889
890 addArchSpecificRPath(TC, Args, CmdArgs);
891
892 if (RTKind == Driver::OMPRT_OMP)
893 addOpenMPRuntimeSpecificRPath(TC, Args, CmdArgs);
894 addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
895
896 return true;
897}
898
899void tools::addFortranRuntimeLibs(const ToolChain &TC,
900 llvm::opt::ArgStringList &CmdArgs) {
901 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
902 CmdArgs.push_back("Fortran_main.lib");
903 CmdArgs.push_back("FortranRuntime.lib");
904 CmdArgs.push_back("FortranDecimal.lib");
905 } else {
906 CmdArgs.push_back("-lFortran_main");
907 CmdArgs.push_back("-lFortranRuntime");
908 CmdArgs.push_back("-lFortranDecimal");
909 }
910}
911
912void tools::addFortranRuntimeLibraryPath(const ToolChain &TC,
913 const llvm::opt::ArgList &Args,
914 ArgStringList &CmdArgs) {
915 // NOTE: Generating executables by Flang is considered an "experimental"
916 // feature and hence this is guarded with a command line option.
917 // TODO: Make this work unconditionally once Flang is mature enough.
918 if (!Args.hasArg(options::OPT_flang_experimental_exec))
919 return;
920
921 // Default to the <driver-path>/../lib directory. This works fine on the
922 // platforms that we have tested so far. We will probably have to re-fine
923 // this in the future. In particular, on some platforms, we may need to use
924 // lib64 instead of lib.
925 SmallString<256> DefaultLibPath =
926 llvm::sys::path::parent_path(TC.getDriver().Dir);
927 llvm::sys::path::append(DefaultLibPath, "lib");
928 if (TC.getTriple().isKnownWindowsMSVCEnvironment())
929 CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
930 else
931 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
932}
933
934static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
935 ArgStringList &CmdArgs, StringRef Sanitizer,
936 bool IsShared, bool IsWhole) {
937 // Wrap any static runtimes that must be forced into executable in
938 // whole-archive.
939 if (IsWhole) CmdArgs.push_back("--whole-archive");
940 CmdArgs.push_back(TC.getCompilerRTArgString(
941 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
942 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
943
944 if (IsShared) {
945 addArchSpecificRPath(TC, Args, CmdArgs);
946 }
947}
948
949// Tries to use a file with the list of dynamic symbols that need to be exported
950// from the runtime library. Returns true if the file was found.
951static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
952 ArgStringList &CmdArgs,
953 StringRef Sanitizer) {
954 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
955 // the option, so don't try to pass it.
956 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
957 return true;
958 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
959 if (llvm::sys::fs::exists(SanRT + ".syms")) {
960 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
961 return true;
962 }
963 return false;
964}
965
966const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) {
967 assert(!TC.getTriple().isOSAIX() &&(static_cast <bool> (!TC.getTriple().isOSAIX() &&
"AIX linker does not support any form of --as-needed option yet."
) ? void (0) : __assert_fail ("!TC.getTriple().isOSAIX() && \"AIX linker does not support any form of --as-needed option yet.\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 968, __extension__
__PRETTY_FUNCTION__))
968 "AIX linker does not support any form of --as-needed option yet.")(static_cast <bool> (!TC.getTriple().isOSAIX() &&
"AIX linker does not support any form of --as-needed option yet."
) ? void (0) : __assert_fail ("!TC.getTriple().isOSAIX() && \"AIX linker does not support any form of --as-needed option yet.\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 968, __extension__
__PRETTY_FUNCTION__))
;
969
970 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
971 // for the native forms -z ignore/-z record, they are missing in Illumos,
972 // so always use the native form.
973 if (TC.getTriple().isOSSolaris())
974 return as_needed ? "-zignore" : "-zrecord";
975 else
976 return as_needed ? "--as-needed" : "--no-as-needed";
977}
978
979void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
980 ArgStringList &CmdArgs) {
981 // Force linking against the system libraries sanitizers depends on
982 // (see PR15823 why this is necessary).
983 CmdArgs.push_back(getAsNeededOption(TC, false));
984 // There's no libpthread or librt on RTEMS & Android.
985 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
986 !TC.getTriple().isAndroid()) {
987 CmdArgs.push_back("-lpthread");
988 if (!TC.getTriple().isOSOpenBSD())
989 CmdArgs.push_back("-lrt");
990 }
991 CmdArgs.push_back("-lm");
992 // There's no libdl on all OSes.
993 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
994 !TC.getTriple().isOSOpenBSD() &&
995 TC.getTriple().getOS() != llvm::Triple::RTEMS)
996 CmdArgs.push_back("-ldl");
997 // Required for backtrace on some OSes
998 if (TC.getTriple().isOSFreeBSD() ||
999 TC.getTriple().isOSNetBSD() ||
1000 TC.getTriple().isOSOpenBSD())
1001 CmdArgs.push_back("-lexecinfo");
1002 // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl
1003 // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv
1004 // requirement.
1005 if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() &&
1006 !TC.getTriple().isMusl())
1007 CmdArgs.push_back("-lresolv");
1008}
1009
1010static void
1011collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1012 SmallVectorImpl<StringRef> &SharedRuntimes,
1013 SmallVectorImpl<StringRef> &StaticRuntimes,
1014 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
1015 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
1016 SmallVectorImpl<StringRef> &RequiredSymbols) {
1017 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1018 // Collect shared runtimes.
1019 if (SanArgs.needsSharedRt()) {
1020 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
1021 SharedRuntimes.push_back("asan");
1022 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1023 HelperStaticRuntimes.push_back("asan-preinit");
1024 }
1025 if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
1026 SharedRuntimes.push_back("memprof");
1027 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
1028 HelperStaticRuntimes.push_back("memprof-preinit");
1029 }
1030 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
1031 if (SanArgs.requiresMinimalRuntime())
1032 SharedRuntimes.push_back("ubsan_minimal");
1033 else
1034 SharedRuntimes.push_back("ubsan_standalone");
1035 }
1036 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
1037 SharedRuntimes.push_back("scudo_standalone");
1038 }
1039 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
1040 SharedRuntimes.push_back("tsan");
1041 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
1042 if (SanArgs.needsHwasanAliasesRt())
1043 SharedRuntimes.push_back("hwasan_aliases");
1044 else
1045 SharedRuntimes.push_back("hwasan");
1046 if (!Args.hasArg(options::OPT_shared))
1047 HelperStaticRuntimes.push_back("hwasan-preinit");
1048 }
1049 }
1050
1051 // The stats_client library is also statically linked into DSOs.
1052 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
1053 StaticRuntimes.push_back("stats_client");
1054
1055 // Always link the static runtime regardless of DSO or executable.
1056 if (SanArgs.needsAsanRt())
1057 HelperStaticRuntimes.push_back("asan_static");
1058
1059 // Collect static runtimes.
1060 if (Args.hasArg(options::OPT_shared)) {
1061 // Don't link static runtimes into DSOs.
1062 return;
1063 }
1064
1065 // Each static runtime that has a DSO counterpart above is excluded below,
1066 // but runtimes that exist only as static are not affected by needsSharedRt.
1067
1068 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
1069 StaticRuntimes.push_back("asan");
1070 if (SanArgs.linkCXXRuntimes())
1071 StaticRuntimes.push_back("asan_cxx");
1072 }
1073
1074 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
1075 SanArgs.linkRuntimes()) {
1076 StaticRuntimes.push_back("memprof");
1077 if (SanArgs.linkCXXRuntimes())
1078 StaticRuntimes.push_back("memprof_cxx");
1079 }
1080
1081 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
1082 if (SanArgs.needsHwasanAliasesRt()) {
1083 StaticRuntimes.push_back("hwasan_aliases");
1084 if (SanArgs.linkCXXRuntimes())
1085 StaticRuntimes.push_back("hwasan_aliases_cxx");
1086 } else {
1087 StaticRuntimes.push_back("hwasan");
1088 if (SanArgs.linkCXXRuntimes())
1089 StaticRuntimes.push_back("hwasan_cxx");
1090 }
1091 }
1092 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
1093 StaticRuntimes.push_back("dfsan");
1094 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
1095 StaticRuntimes.push_back("lsan");
1096 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
1097 StaticRuntimes.push_back("msan");
1098 if (SanArgs.linkCXXRuntimes())
1099 StaticRuntimes.push_back("msan_cxx");
1100 }
1101 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
1102 SanArgs.linkRuntimes()) {
1103 StaticRuntimes.push_back("tsan");
1104 if (SanArgs.linkCXXRuntimes())
1105 StaticRuntimes.push_back("tsan_cxx");
1106 }
1107 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
1108 if (SanArgs.requiresMinimalRuntime()) {
1109 StaticRuntimes.push_back("ubsan_minimal");
1110 } else {
1111 StaticRuntimes.push_back("ubsan_standalone");
1112 if (SanArgs.linkCXXRuntimes())
1113 StaticRuntimes.push_back("ubsan_standalone_cxx");
1114 }
1115 }
1116 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
1117 NonWholeStaticRuntimes.push_back("safestack");
1118 RequiredSymbols.push_back("__safestack_init");
1119 }
1120 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
1121 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
1122 StaticRuntimes.push_back("cfi");
1123 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
1124 StaticRuntimes.push_back("cfi_diag");
1125 if (SanArgs.linkCXXRuntimes())
1126 StaticRuntimes.push_back("ubsan_standalone_cxx");
1127 }
1128 }
1129 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
1130 NonWholeStaticRuntimes.push_back("stats");
1131 RequiredSymbols.push_back("__sanitizer_stats_register");
1132 }
1133 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
1134 StaticRuntimes.push_back("scudo_standalone");
1135 if (SanArgs.linkCXXRuntimes())
1136 StaticRuntimes.push_back("scudo_standalone_cxx");
1137 }
1138}
1139
1140// Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
1141// C runtime, etc). Returns true if sanitizer system deps need to be linked in.
1142bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
1143 ArgStringList &CmdArgs) {
1144 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
1145 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
1146 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
1147 NonWholeStaticRuntimes, HelperStaticRuntimes,
1148 RequiredSymbols);
1149
1150 const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
1151 // Inject libfuzzer dependencies.
1152 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
1153 !Args.hasArg(options::OPT_shared)) {
1154
1155 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
1156 if (SanArgs.needsFuzzerInterceptors())
1157 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
1158 true);
1159 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
1160 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
1161 !Args.hasArg(options::OPT_static);
1162 if (OnlyLibstdcxxStatic)
1163 CmdArgs.push_back("-Bstatic");
1164 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
1165 if (OnlyLibstdcxxStatic)
1166 CmdArgs.push_back("-Bdynamic");
1167 }
1168 }
1169
1170 for (auto RT : SharedRuntimes)
1171 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
1172 for (auto RT : HelperStaticRuntimes)
1173 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1174 bool AddExportDynamic = false;
1175 for (auto RT : StaticRuntimes) {
1176 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
1177 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1178 }
1179 for (auto RT : NonWholeStaticRuntimes) {
1180 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
1181 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
1182 }
1183 for (auto S : RequiredSymbols) {
1184 CmdArgs.push_back("-u");
1185 CmdArgs.push_back(Args.MakeArgString(S));
1186 }
1187 // If there is a static runtime with no dynamic list, force all the symbols
1188 // to be dynamic to be sure we export sanitizer interface functions.
1189 if (AddExportDynamic)
1190 CmdArgs.push_back("--export-dynamic");
1191
1192 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
1193 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
1194
1195 if (SanArgs.hasMemTag()) {
1196 if (!TC.getTriple().isAndroid()) {
1197 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1198 << "-fsanitize=memtag*" << TC.getTriple().str();
1199 }
1200 CmdArgs.push_back(
1201 Args.MakeArgString("--android-memtag-mode=" + SanArgs.getMemtagMode()));
1202 if (SanArgs.hasMemtagHeap())
1203 CmdArgs.push_back("--android-memtag-heap");
1204 if (SanArgs.hasMemtagStack())
1205 CmdArgs.push_back("--android-memtag-stack");
1206 }
1207
1208 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
1209}
1210
1211bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
1212 if (Args.hasArg(options::OPT_shared))
1213 return false;
1214
1215 if (TC.getXRayArgs().needsXRayRt()) {
1216 CmdArgs.push_back("-whole-archive");
1217 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
1218 for (const auto &Mode : TC.getXRayArgs().modeList())
1219 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
1220 CmdArgs.push_back("-no-whole-archive");
1221 return true;
1222 }
1223
1224 return false;
1225}
1226
1227void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
1228 CmdArgs.push_back(getAsNeededOption(TC, false));
1229 CmdArgs.push_back("-lpthread");
1230 if (!TC.getTriple().isOSOpenBSD())
1231 CmdArgs.push_back("-lrt");
1232 CmdArgs.push_back("-lm");
1233
1234 if (!TC.getTriple().isOSFreeBSD() &&
1235 !TC.getTriple().isOSNetBSD() &&
1236 !TC.getTriple().isOSOpenBSD())
1237 CmdArgs.push_back("-ldl");
1238}
1239
1240bool tools::areOptimizationsEnabled(const ArgList &Args) {
1241 // Find the last -O arg and see if it is non-zero.
1242 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1243 return !A->getOption().matches(options::OPT_O0);
1244 // Defaults to -O0.
1245 return false;
1246}
1247
1248const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1249 const InputInfo &Input,
1250 const InputInfo &Output) {
1251 auto AddPostfix = [JA](auto &F) {
1252 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1253 F += (Twine("_") + JA.getOffloadingArch()).str();
1254 F += ".dwo";
1255 };
1256 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1257 if (StringRef(A->getValue()) == "single")
1258 return Args.MakeArgString(Output.getFilename());
1259
1260 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1261 if (FinalOutput && Args.hasArg(options::OPT_c)) {
1262 SmallString<128> T(FinalOutput->getValue());
1263 llvm::sys::path::remove_filename(T);
1264 llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1265 AddPostfix(T);
1266 return Args.MakeArgString(T);
1267 } else {
1268 // Use the compilation dir.
1269 Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1270 options::OPT_fdebug_compilation_dir_EQ);
1271 SmallString<128> T(A ? A->getValue() : "");
1272 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1273 AddPostfix(F);
1274 T += F;
1275 return Args.MakeArgString(T);
1276 }
1277}
1278
1279void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1280 const JobAction &JA, const ArgList &Args,
1281 const InputInfo &Output, const char *OutFile) {
1282 ArgStringList ExtractArgs;
1283 ExtractArgs.push_back("--extract-dwo");
1284
1285 ArgStringList StripArgs;
1286 StripArgs.push_back("--strip-dwo");
1287
1288 // Grabbing the output of the earlier compile step.
1289 StripArgs.push_back(Output.getFilename());
1290 ExtractArgs.push_back(Output.getFilename());
1291 ExtractArgs.push_back(OutFile);
1292
1293 const char *Exec =
1294 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY"objcopy"));
1295 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1296
1297 // First extract the dwo sections.
1298 C.addCommand(std::make_unique<Command>(JA, T,
1299 ResponseFileSupport::AtFileCurCP(),
1300 Exec, ExtractArgs, II, Output));
1301
1302 // Then remove them from the original .o file.
1303 C.addCommand(std::make_unique<Command>(
1304 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1305}
1306
1307// Claim options we don't want to warn if they are unused. We do this for
1308// options that build systems might add but are unused when assembling or only
1309// running the preprocessor for example.
1310void tools::claimNoWarnArgs(const ArgList &Args) {
1311 // Don't warn about unused -f(no-)?lto. This can happen when we're
1312 // preprocessing, precompiling or assembling.
1313 Args.ClaimAllArgs(options::OPT_flto_EQ);
1314 Args.ClaimAllArgs(options::OPT_flto);
1315 Args.ClaimAllArgs(options::OPT_fno_lto);
1316}
1317
1318Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1319 auto *ProfileUseArg = Args.getLastArg(
1320 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1321 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1322 options::OPT_fno_profile_instr_use);
1323
1324 if (ProfileUseArg &&
1325 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1326 ProfileUseArg = nullptr;
1327
1328 return ProfileUseArg;
1329}
1330
1331Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1332 auto *ProfileSampleUseArg = Args.getLastArg(
1333 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1334 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1335 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1336
1337 if (ProfileSampleUseArg &&
1338 (ProfileSampleUseArg->getOption().matches(
1339 options::OPT_fno_profile_sample_use) ||
1340 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1341 return nullptr;
1342
1343 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1344 options::OPT_fauto_profile_EQ);
1345}
1346
1347const char *tools::RelocationModelName(llvm::Reloc::Model Model) {
1348 switch (Model) {
1349 case llvm::Reloc::Static:
1350 return "static";
1351 case llvm::Reloc::PIC_:
1352 return "pic";
1353 case llvm::Reloc::DynamicNoPIC:
1354 return "dynamic-no-pic";
1355 case llvm::Reloc::ROPI:
1356 return "ropi";
1357 case llvm::Reloc::RWPI:
1358 return "rwpi";
1359 case llvm::Reloc::ROPI_RWPI:
1360 return "ropi-rwpi";
1361 }
1362 llvm_unreachable("Unknown Reloc::Model kind")::llvm::llvm_unreachable_internal("Unknown Reloc::Model kind"
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 1362)
;
1363}
1364
1365/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
1366/// smooshes them together with platform defaults, to decide whether
1367/// this compile should be using PIC mode or not. Returns a tuple of
1368/// (RelocationModel, PICLevel, IsPIE).
1369std::tuple<llvm::Reloc::Model, unsigned, bool>
1370tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1371 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1372 const llvm::Triple &Triple = ToolChain.getTriple();
1373
1374 bool PIE = ToolChain.isPIEDefault(Args);
1375 bool PIC = PIE || ToolChain.isPICDefault();
1376 // The Darwin/MachO default to use PIC does not apply when using -static.
1377 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1378 PIE = PIC = false;
1379 bool IsPICLevelTwo = PIC;
1380
1381 bool KernelOrKext =
1382 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1383
1384 // Android-specific defaults for PIC/PIE
1385 if (Triple.isAndroid()) {
1386 switch (Triple.getArch()) {
1387 case llvm::Triple::arm:
1388 case llvm::Triple::armeb:
1389 case llvm::Triple::thumb:
1390 case llvm::Triple::thumbeb:
1391 case llvm::Triple::aarch64:
1392 case llvm::Triple::mips:
1393 case llvm::Triple::mipsel:
1394 case llvm::Triple::mips64:
1395 case llvm::Triple::mips64el:
1396 PIC = true; // "-fpic"
1397 break;
1398
1399 case llvm::Triple::x86:
1400 case llvm::Triple::x86_64:
1401 PIC = true; // "-fPIC"
1402 IsPICLevelTwo = true;
1403 break;
1404
1405 default:
1406 break;
1407 }
1408 }
1409
1410 // OpenBSD-specific defaults for PIE
1411 if (Triple.isOSOpenBSD()) {
1412 switch (ToolChain.getArch()) {
1413 case llvm::Triple::arm:
1414 case llvm::Triple::aarch64:
1415 case llvm::Triple::mips64:
1416 case llvm::Triple::mips64el:
1417 case llvm::Triple::x86:
1418 case llvm::Triple::x86_64:
1419 IsPICLevelTwo = false; // "-fpie"
1420 break;
1421
1422 case llvm::Triple::ppc:
1423 case llvm::Triple::sparcv9:
1424 IsPICLevelTwo = true; // "-fPIE"
1425 break;
1426
1427 default:
1428 break;
1429 }
1430 }
1431
1432 // AMDGPU-specific defaults for PIC.
1433 if (Triple.getArch() == llvm::Triple::amdgcn)
1434 PIC = true;
1435
1436 // The last argument relating to either PIC or PIE wins, and no
1437 // other argument is used. If the last argument is any flavor of the
1438 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1439 // option implicitly enables PIC at the same level.
1440 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1441 options::OPT_fpic, options::OPT_fno_pic,
1442 options::OPT_fPIE, options::OPT_fno_PIE,
1443 options::OPT_fpie, options::OPT_fno_pie);
1444 if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
1445 LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1446 options::OPT_fPIE, options::OPT_fpie)) {
1447 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1448 << LastPICArg->getSpelling() << Triple.str();
1449 if (Triple.getArch() == llvm::Triple::x86_64)
1450 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1451 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1452 }
1453
1454 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1455 // is forced, then neither PIC nor PIE flags will have no effect.
1456 if (!ToolChain.isPICDefaultForced()) {
1457 if (LastPICArg) {
1458 Option O = LastPICArg->getOption();
1459 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1460 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1461 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1462 PIC =
1463 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1464 IsPICLevelTwo =
1465 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1466 } else {
1467 PIE = PIC = false;
1468 if (EffectiveTriple.isPS()) {
1469 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1470 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1471 if (Model != "kernel") {
1472 PIC = true;
1473 ToolChain.getDriver().Diag(diag::warn_drv_ps_force_pic)
1474 << LastPICArg->getSpelling()
1475 << (EffectiveTriple.isPS4() ? "PS4" : "PS5");
1476 }
1477 }
1478 }
1479 }
1480 }
1481
1482 // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but
1483 // the PIC level would've been set to level 1, force it back to level 2 PIC
1484 // instead.
1485 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS()))
1486 IsPICLevelTwo |= ToolChain.isPICDefault();
1487
1488 // This kernel flags are a trump-card: they will disable PIC/PIE
1489 // generation, independent of the argument order.
1490 if (KernelOrKext &&
1491 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1492 !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit()))
1493 PIC = PIE = false;
1494
1495 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1496 // This is a very special mode. It trumps the other modes, almost no one
1497 // uses it, and it isn't even valid on any OS but Darwin.
1498 if (!Triple.isOSDarwin())
1499 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1500 << A->getSpelling() << Triple.str();
1501
1502 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1503
1504 // Only a forced PIC mode can cause the actual compile to have PIC defines
1505 // etc., no flags are sufficient. This behavior was selected to closely
1506 // match that of llvm-gcc and Apple GCC before that.
1507 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1508
1509 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1510 }
1511
1512 bool EmbeddedPISupported;
1513 switch (Triple.getArch()) {
1514 case llvm::Triple::arm:
1515 case llvm::Triple::armeb:
1516 case llvm::Triple::thumb:
1517 case llvm::Triple::thumbeb:
1518 EmbeddedPISupported = true;
1519 break;
1520 default:
1521 EmbeddedPISupported = false;
1522 break;
1523 }
1524
1525 bool ROPI = false, RWPI = false;
1526 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1527 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1528 if (!EmbeddedPISupported)
1529 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1530 << LastROPIArg->getSpelling() << Triple.str();
1531 ROPI = true;
1532 }
1533 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1534 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1535 if (!EmbeddedPISupported)
1536 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1537 << LastRWPIArg->getSpelling() << Triple.str();
1538 RWPI = true;
1539 }
1540
1541 // ROPI and RWPI are not compatible with PIC or PIE.
1542 if ((ROPI || RWPI) && (PIC || PIE))
1543 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1544
1545 if (Triple.isMIPS()) {
1546 StringRef CPUName;
1547 StringRef ABIName;
1548 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1549 // When targeting the N64 ABI, PIC is the default, except in the case
1550 // when the -mno-abicalls option is used. In that case we exit
1551 // at next check regardless of PIC being set below.
1552 if (ABIName == "n64")
1553 PIC = true;
1554 // When targettng MIPS with -mno-abicalls, it's always static.
1555 if(Args.hasArg(options::OPT_mno_abicalls))
1556 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1557 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1558 // does not use PIC level 2 for historical reasons.
1559 IsPICLevelTwo = false;
1560 }
1561
1562 if (PIC)
1563 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1564
1565 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1566 if (ROPI && RWPI)
1567 RelocM = llvm::Reloc::ROPI_RWPI;
1568 else if (ROPI)
1569 RelocM = llvm::Reloc::ROPI;
1570 else if (RWPI)
1571 RelocM = llvm::Reloc::RWPI;
1572
1573 return std::make_tuple(RelocM, 0U, false);
1574}
1575
1576// `-falign-functions` indicates that the functions should be aligned to a
1577// 16-byte boundary.
1578//
1579// `-falign-functions=1` is the same as `-fno-align-functions`.
1580//
1581// The scalar `n` in `-falign-functions=n` must be an integral value between
1582// [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1583// the nearest power-of-two.
1584//
1585// If we return `0`, the frontend will default to the backend's preferred
1586// alignment.
1587//
1588// NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1589// to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1590// alignment. For unaligned functions, we default to the backend's preferred
1591// alignment.
1592unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1593 const ArgList &Args) {
1594 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1595 options::OPT_falign_functions_EQ,
1596 options::OPT_fno_align_functions);
1597 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1598 return 0;
1599
1600 if (A->getOption().matches(options::OPT_falign_functions))
1601 return 0;
1602
1603 unsigned Value = 0;
1604 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1605 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1606 << A->getAsString(Args) << A->getValue();
1607 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1608}
1609
1610static unsigned ParseDebugDefaultVersion(const ToolChain &TC,
1611 const ArgList &Args) {
1612 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1613
1614 if (!A)
1615 return 0;
1616
1617 unsigned Value = 0;
1618 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1619 Value < 2)
1620 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1621 << A->getAsString(Args) << A->getValue();
1622 return Value;
1623}
1624
1625unsigned tools::DwarfVersionNum(StringRef ArgValue) {
1626 return llvm::StringSwitch<unsigned>(ArgValue)
1627 .Case("-gdwarf-2", 2)
1628 .Case("-gdwarf-3", 3)
1629 .Case("-gdwarf-4", 4)
1630 .Case("-gdwarf-5", 5)
1631 .Default(0);
1632}
1633
1634const Arg *tools::getDwarfNArg(const ArgList &Args) {
1635 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
1636 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
1637 options::OPT_gdwarf);
1638}
1639
1640unsigned tools::getDwarfVersion(const ToolChain &TC,
1641 const llvm::opt::ArgList &Args) {
1642 unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args);
1643 if (const Arg *GDwarfN = getDwarfNArg(Args))
1644 if (int N = DwarfVersionNum(GDwarfN->getSpelling()))
1645 DwarfVersion = N;
1646 if (DwarfVersion == 0) {
1647 DwarfVersion = TC.GetDefaultDwarfVersion();
1648 assert(DwarfVersion && "toolchain default DWARF version must be nonzero")(static_cast <bool> (DwarfVersion && "toolchain default DWARF version must be nonzero"
) ? void (0) : __assert_fail ("DwarfVersion && \"toolchain default DWARF version must be nonzero\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 1648, __extension__
__PRETTY_FUNCTION__))
;
1649 }
1650 return DwarfVersion;
1651}
1652
1653void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1654 ArgStringList &CmdArgs) {
1655 llvm::Reloc::Model RelocationModel;
1656 unsigned PICLevel;
1657 bool IsPIE;
1658 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1659
1660 if (RelocationModel != llvm::Reloc::Static)
1661 CmdArgs.push_back("-KPIC");
1662}
1663
1664/// Determine whether Objective-C automated reference counting is
1665/// enabled.
1666bool tools::isObjCAutoRefCount(const ArgList &Args) {
1667 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1668}
1669
1670enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1671
1672static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1673 const ArgList &Args) {
1674 if (Args.hasArg(options::OPT_static_libgcc) ||
1675 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie) ||
1676 // The Android NDK only provides libunwind.a, not libunwind.so.
1677 TC.getTriple().isAndroid())
1678 return LibGccType::StaticLibGcc;
1679 if (Args.hasArg(options::OPT_shared_libgcc))
1680 return LibGccType::SharedLibGcc;
1681 return LibGccType::UnspecifiedLibGcc;
1682}
1683
1684// Gcc adds libgcc arguments in various ways:
1685//
1686// gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1687// g++ <none>: -lgcc_s -lgcc
1688// gcc shared: -lgcc_s -lgcc
1689// g++ shared: -lgcc_s -lgcc
1690// gcc static: -lgcc -lgcc_eh
1691// g++ static: -lgcc -lgcc_eh
1692// gcc static-pie: -lgcc -lgcc_eh
1693// g++ static-pie: -lgcc -lgcc_eh
1694//
1695// Also, certain targets need additional adjustments.
1696
1697static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1698 ArgStringList &CmdArgs, const ArgList &Args) {
1699 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1700 // Targets that don't use unwind libraries.
1701 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1702 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
1703 TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
1704 return;
1705
1706 LibGccType LGT = getLibGccType(TC, D, Args);
1707 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1708 (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) &&
1709 !TC.getTriple().isAndroid() &&
1710 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
1711 if (AsNeeded)
1712 CmdArgs.push_back(getAsNeededOption(TC, true));
1713
1714 switch (UNW) {
1715 case ToolChain::UNW_None:
1716 return;
1717 case ToolChain::UNW_Libgcc: {
1718 if (LGT == LibGccType::StaticLibGcc)
1719 CmdArgs.push_back("-lgcc_eh");
1720 else
1721 CmdArgs.push_back("-lgcc_s");
1722 break;
1723 }
1724 case ToolChain::UNW_CompilerRT:
1725 if (TC.getTriple().isOSAIX()) {
1726 // AIX only has libunwind as a shared library. So do not pass
1727 // anything in if -static is specified.
1728 if (LGT != LibGccType::StaticLibGcc)
1729 CmdArgs.push_back("-lunwind");
1730 } else if (LGT == LibGccType::StaticLibGcc) {
1731 CmdArgs.push_back("-l:libunwind.a");
1732 } else if (LGT == LibGccType::SharedLibGcc) {
1733 if (TC.getTriple().isOSCygMing())
1734 CmdArgs.push_back("-l:libunwind.dll.a");
1735 else
1736 CmdArgs.push_back("-l:libunwind.so");
1737 } else {
1738 // Let the linker choose between libunwind.so and libunwind.a
1739 // depending on what's available, and depending on the -static flag
1740 CmdArgs.push_back("-lunwind");
1741 }
1742 break;
1743 }
1744
1745 if (AsNeeded)
1746 CmdArgs.push_back(getAsNeededOption(TC, false));
1747}
1748
1749static void AddLibgcc(const ToolChain &TC, const Driver &D,
1750 ArgStringList &CmdArgs, const ArgList &Args) {
1751 LibGccType LGT = getLibGccType(TC, D, Args);
1752 if (LGT == LibGccType::StaticLibGcc ||
1753 (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX()))
1754 CmdArgs.push_back("-lgcc");
1755 AddUnwindLibrary(TC, D, CmdArgs, Args);
1756 if (LGT == LibGccType::SharedLibGcc ||
1757 (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX()))
1758 CmdArgs.push_back("-lgcc");
1759}
1760
1761void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1762 ArgStringList &CmdArgs, const ArgList &Args) {
1763 // Make use of compiler-rt if --rtlib option is used
1764 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1765
1766 switch (RLT) {
1767 case ToolChain::RLT_CompilerRT:
1768 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1769 AddUnwindLibrary(TC, D, CmdArgs, Args);
1770 break;
1771 case ToolChain::RLT_Libgcc:
1772 // Make sure libgcc is not used under MSVC environment by default
1773 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1774 // Issue error diagnostic if libgcc is explicitly specified
1775 // through command line as --rtlib option argument.
1776 Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
1777 if (A && A->getValue() != StringRef("platform")) {
1778 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1779 << A->getValue() << "MSVC";
1780 }
1781 } else
1782 AddLibgcc(TC, D, CmdArgs, Args);
1783 break;
1784 }
1785
1786 // On Android, the unwinder uses dl_iterate_phdr (or one of
1787 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1788 // statically-linked executables, these functions come from libc.a instead.
1789 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1790 !Args.hasArg(options::OPT_static_pie))
1791 CmdArgs.push_back("-ldl");
1792}
1793
1794SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1795 const InputInfo &Output,
1796 const InputInfo &Input,
1797 const Driver &D) {
1798 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1799 if (!A)
1800 return {};
1801
1802 StringRef SaveStats = A->getValue();
1803 SmallString<128> StatsFile;
1804 if (SaveStats == "obj" && Output.isFilename()) {
1805 StatsFile.assign(Output.getFilename());
1806 llvm::sys::path::remove_filename(StatsFile);
1807 } else if (SaveStats != "cwd") {
1808 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1809 return {};
1810 }
1811
1812 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1813 llvm::sys::path::append(StatsFile, BaseName);
1814 llvm::sys::path::replace_extension(StatsFile, "stats");
1815 return StatsFile;
1816}
1817
1818void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1819 Multilib::flags_list &Flags) {
1820 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1821}
1822
1823void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1824 ArgStringList &CmdArgs, bool IsLTO,
1825 const StringRef PluginOptPrefix) {
1826 auto addArg = [&, IsLTO](const Twine &Arg) {
1827 if (IsLTO) {
1828 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!")(static_cast <bool> (!PluginOptPrefix.empty() &&
"Cannot have empty PluginOptPrefix!") ? void (0) : __assert_fail
("!PluginOptPrefix.empty() && \"Cannot have empty PluginOptPrefix!\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 1828, __extension__
__PRETTY_FUNCTION__))
;
1829 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
1830 } else {
1831 CmdArgs.push_back("-mllvm");
1832 CmdArgs.push_back(Args.MakeArgString(Arg));
1833 }
1834 };
1835
1836 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1837 addArg(Twine("-x86-branches-within-32B-boundaries"));
1838 }
1839 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1840 StringRef Value = A->getValue();
1841 unsigned Boundary;
1842 if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1843 !llvm::isPowerOf2_64(Boundary)) {
1844 D.Diag(diag::err_drv_invalid_argument_to_option)
1845 << Value << A->getOption().getName();
1846 } else {
1847 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1848 }
1849 }
1850 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1851 std::string AlignBranch;
1852 for (StringRef T : A->getValues()) {
1853 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1854 T != "ret" && T != "indirect")
1855 D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1856 << T << "fused, jcc, jmp, call, ret, indirect";
1857 if (!AlignBranch.empty())
1858 AlignBranch += '+';
1859 AlignBranch += T;
1860 }
1861 addArg("-x86-align-branch=" + Twine(AlignBranch));
1862 }
1863 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1864 StringRef Value = A->getValue();
1865 unsigned PrefixSize;
1866 if (Value.getAsInteger(10, PrefixSize)) {
1867 D.Diag(diag::err_drv_invalid_argument_to_option)
1868 << Value << A->getOption().getName();
1869 } else {
1870 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1871 }
1872 }
1873}
1874
1875/// SDLSearch: Search for Static Device Library
1876/// The search for SDL bitcode files is consistent with how static host
1877/// libraries are discovered. That is, the -l option triggers a search for
1878/// files in a set of directories called the LINKPATH. The host library search
1879/// procedure looks for a specific filename in the LINKPATH. The filename for
1880/// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
1881/// ordered-set of filenames that are searched. We call this ordered-set of
1882/// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
1883/// architecture specific, or generic across all architectures, a naming
1884/// convention and search order is used where the file name embeds the
1885/// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
1886/// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
1887/// device-independent SDLs. To reduce congestion in host library directories,
1888/// the search first looks for files in the “libdevice” subdirectory. SDLs that
1889/// are bc files begin with the prefix “lib”.
1890///
1891/// Machine-code SDLs can also be managed as an archive (*.a file). The
1892/// convention has been to use the prefix “lib”. To avoid confusion with host
1893/// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
1894///
1895bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
1896 llvm::opt::ArgStringList &CC1Args,
1897 SmallVector<std::string, 8> LibraryPaths, std::string Lib,
1898 StringRef Arch, StringRef Target, bool isBitCodeSDL,
1899 bool postClangLink) {
1900 SmallVector<std::string, 12> SDLs;
1901
1902 std::string LibDeviceLoc = "/libdevice";
1903 std::string LibBcPrefix = "/libbc-";
1904 std::string LibPrefix = "/lib";
1905
1906 if (isBitCodeSDL) {
1907 // SEARCH-ORDER for Bitcode SDLs:
1908 // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
1909 // libbc-<libname>-<arch-name>-<device-type>.a
1910 // libdevice/libbc-<libname>-<arch-name>.a
1911 // libbc-<libname>-<arch-name>.a
1912 // libdevice/libbc-<libname>.a
1913 // libbc-<libname>.a
1914 // libdevice/lib<libname>-<arch-name>-<device-type>.bc
1915 // lib<libname>-<arch-name>-<device-type>.bc
1916 // libdevice/lib<libname>-<arch-name>.bc
1917 // lib<libname>-<arch-name>.bc
1918 // libdevice/lib<libname>.bc
1919 // lib<libname>.bc
1920
1921 for (StringRef Base : {LibBcPrefix, LibPrefix}) {
1922 const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
1923
1924 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1925 Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
1926 SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
1927 SDLs.push_back(Twine(Base + Suffix + Ext).str());
1928 }
1929 }
1930 } else {
1931 // SEARCH-ORDER for Machine-code SDLs:
1932 // libdevice/lib<libname>-<arch-name>-<device-type>.a
1933 // lib<libname>-<arch-name>-<device-type>.a
1934 // libdevice/lib<libname>-<arch-name>.a
1935 // lib<libname>-<arch-name>.a
1936
1937 const auto *Ext = ".a";
1938
1939 for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
1940 Twine(Lib + "-" + Arch).str()}) {
1941 SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
1942 SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
1943 }
1944 }
1945
1946 // The CUDA toolchain does not use a global device llvm-link before the LLVM
1947 // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
1948 // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
1949 // will link libraries after clang compilation while the LLVM IR is still in
1950 // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
1951 // This is a clang -cc1 option that is generated by the clang driver. The
1952 // option value must a full path to an existing file.
1953 bool FoundSDL = false;
1954 for (auto LPath : LibraryPaths) {
1955 for (auto SDL : SDLs) {
1956 auto FullName = Twine(LPath + SDL).str();
1957 if (llvm::sys::fs::exists(FullName)) {
1958 if (postClangLink)
1959 CC1Args.push_back("-mlink-builtin-bitcode");
1960 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
1961 FoundSDL = true;
1962 break;
1963 }
1964 }
1965 if (FoundSDL)
1966 break;
1967 }
1968 return FoundSDL;
1969}
1970
1971/// Search if a user provided archive file lib<libname>.a exists in any of
1972/// the library paths. If so, add a new command to clang-offload-bundler to
1973/// unbundle this archive and create a temporary device specific archive. Name
1974/// of this SDL is passed to the llvm-link (for amdgcn) or to the
1975/// clang-nvlink-wrapper (for nvptx) commands by the driver.
1976bool tools::GetSDLFromOffloadArchive(
1977 Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
1978 const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
1979 llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths,
1980 StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
1981 bool postClangLink) {
1982
1983 // We don't support bitcode archive bundles for nvptx
1984 if (isBitCodeSDL && Arch.contains("nvptx"))
1985 return false;
1986
1987 bool FoundAOB = false;
1988 std::string ArchiveOfBundles;
1989
1990 llvm::Triple Triple(D.getTargetTriple());
1991 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
1992 auto Ext = IsMSVC ? ".lib" : ".a";
1993 if (!Lib.startswith(":") && !Lib.startswith("-l")) {
1994 if (llvm::sys::fs::exists(Lib)) {
1995 ArchiveOfBundles = Lib;
1996 FoundAOB = true;
1997 }
1998 } else {
1999 if (Lib.startswith("-l"))
2000 Lib = Lib.drop_front(2);
2001 for (auto LPath : LibraryPaths) {
2002 ArchiveOfBundles.clear();
2003 SmallVector<std::string, 2> AOBFileNames;
2004 auto LibFile =
2005 (Lib.startswith(":") ? Lib.drop_front()
2006 : IsMSVC ? Lib + Ext : "lib" + Lib + Ext)
2007 .str();
2008 for (auto Prefix : {"/libdevice/", "/"}) {
2009 auto AOB = Twine(LPath + Prefix + LibFile).str();
2010 if (llvm::sys::fs::exists(AOB)) {
2011 ArchiveOfBundles = AOB;
2012 FoundAOB = true;
2013 break;
2014 }
2015 }
2016 if (FoundAOB)
2017 break;
2018 }
2019 }
2020
2021 if (!FoundAOB)
2022 return false;
2023
2024 llvm::file_magic Magic;
2025 auto EC = llvm::identify_magic(ArchiveOfBundles, Magic);
2026 if (EC || Magic != llvm::file_magic::archive)
2027 return false;
2028
2029 StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
2030 std::string OutputLib =
2031 D.GetTemporaryPath(Twine(Prefix + llvm::sys::path::filename(Lib) + "-" +
2032 Arch + "-" + Target)
2033 .str(),
2034 "a");
2035
2036 C.addTempFile(C.getArgs().MakeArgString(OutputLib));
2037
2038 ArgStringList CmdArgs;
2039 SmallString<128> DeviceTriple;
2040 DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
2041 DeviceTriple += '-';
2042 std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
2043 DeviceTriple += NormalizedTriple;
2044 if (!Target.empty()) {
2045 DeviceTriple += '-';
2046 DeviceTriple += Target;
2047 }
2048
2049 std::string UnbundleArg("-unbundle");
2050 std::string TypeArg("-type=a");
2051 std::string InputArg("-input=" + ArchiveOfBundles);
2052 std::string OffloadArg("-targets=" + std::string(DeviceTriple));
2053 std::string OutputArg("-output=" + OutputLib);
2054
2055 const char *UBProgram = DriverArgs.MakeArgString(
2056 T.getToolChain().GetProgramPath("clang-offload-bundler"));
2057
2058 ArgStringList UBArgs;
2059 UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
2060 UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
2061 UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
2062 UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
2063 UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
2064
2065 // Add this flag to not exit from clang-offload-bundler if no compatible
2066 // code object is found in heterogenous archive library.
2067 std::string AdditionalArgs("-allow-missing-bundles");
2068 UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
2069
2070 // Add this flag to treat hip and hipv4 offload kinds as compatible with
2071 // openmp offload kind while extracting code objects from a heterogenous
2072 // archive library. Vice versa is also considered compatible.
2073 std::string HipCompatibleArgs("-hip-openmp-compatible");
2074 UBArgs.push_back(C.getArgs().MakeArgString(HipCompatibleArgs));
2075
2076 C.addCommand(std::make_unique<Command>(
2077 JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
2078 InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
2079 if (postClangLink)
2080 CC1Args.push_back("-mlink-builtin-bitcode");
2081
2082 CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
2083
2084 return true;
2085}
2086
2087// Wrapper function used by driver for adding SDLs during link phase.
2088void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
2089 const JobAction &JA,
2090 const InputInfoList &Inputs,
2091 const llvm::opt::ArgList &DriverArgs,
2092 llvm::opt::ArgStringList &CC1Args,
2093 StringRef Arch, StringRef Target,
2094 bool isBitCodeSDL, bool postClangLink) {
2095 AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
2096 Arch, Target, isBitCodeSDL, postClangLink);
2097}
2098
2099// Wrapper function used for post clang linking of bitcode SDLS for nvptx by
2100// the CUDA toolchain.
2101void tools::AddStaticDeviceLibsPostLinking(const Driver &D,
2102 const llvm::opt::ArgList &DriverArgs,
2103 llvm::opt::ArgStringList &CC1Args,
2104 StringRef Arch, StringRef Target,
2105 bool isBitCodeSDL, bool postClangLink) {
2106 AddStaticDeviceLibs(nullptr, nullptr, nullptr, nullptr, D, DriverArgs,
1
Passing null pointer value via 1st parameter 'C'
2
Calling 'AddStaticDeviceLibs'
2107 CC1Args, Arch, Target, isBitCodeSDL, postClangLink);
2108}
2109
2110// User defined Static Device Libraries(SDLs) can be passed to clang for
2111// offloading GPU compilers. Like static host libraries, the use of a SDL is
2112// specified with the -l command line option. The primary difference between
2113// host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
2114// and SEARCH-ORDER for Machine-code SDLs for the naming convention).
2115// SDLs are of following types:
2116//
2117// * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
2118// For NVPTX, these libraries are post-clang linked following each
2119// compilation. For AMDGPU, these libraries are linked one time
2120// during the application link phase.
2121//
2122// * Machine-code SDLs: They are archive files. For NVPTX, the archive members
2123// contain cubin for Nvidia GPUs and are linked one time during the
2124// link phase by the CUDA SDK linker called nvlink. For AMDGPU, the
2125// process for machine code SDLs is still in development. But they
2126// will be linked by the LLVM tool lld.
2127//
2128// * Bundled objects that contain both host and device codes: Bundled objects
2129// may also contain library code compiled from source. For NVPTX, the
2130// bundle contains cubin. For AMDGPU, the bundle contains bitcode.
2131//
2132// For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
2133// inclusion of specific SDLs such as math libraries and the OpenMP device
2134// library libomptarget.
2135void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
2136 const JobAction *JA,
2137 const InputInfoList *Inputs, const Driver &D,
2138 const llvm::opt::ArgList &DriverArgs,
2139 llvm::opt::ArgStringList &CC1Args,
2140 StringRef Arch, StringRef Target,
2141 bool isBitCodeSDL, bool postClangLink) {
2142
2143 SmallVector<std::string, 8> LibraryPaths;
2144 // Add search directories from LIBRARY_PATH env variable
2145 llvm::Optional<std::string> LibPath =
2146 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2147 if (LibPath) {
3
Assuming the condition is false
4
Taking false branch
2148 SmallVector<StringRef, 8> Frags;
2149 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2150 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2151 for (StringRef Path : Frags)
2152 LibraryPaths.emplace_back(Path.trim());
2153 }
2154
2155 // Add directories from user-specified -L options
2156 for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
2157 LibraryPaths.emplace_back(Search_Dir);
2158
2159 // Add path to lib-debug folders
2160 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2161 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME"lib");
2162 LibraryPaths.emplace_back(DefaultLibPath.c_str());
2163
2164 // Build list of Static Device Libraries SDLs specified by -l option
2165 llvm::SmallSet<std::string, 16> SDLNames;
2166 static const StringRef HostOnlyArchives[] = {
2167 "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
2168 for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
2169 if (!HostOnlyArchives->contains(SDLName)) {
2170 SDLNames.insert(std::string("-l") + SDLName);
2171 }
2172 }
2173
2174 for (auto Input : DriverArgs.getAllArgValues(options::OPT_INPUT)) {
2175 auto FileName = StringRef(Input);
2176 // Clang treats any unknown file types as archives and passes them to the
2177 // linker. Files with extension 'lib' are classified as TY_Object by clang
2178 // but they are usually archives. It is OK if the file is not really an
2179 // archive since GetSDLFromOffloadArchive will check the magic of the file
2180 // and only unbundle it if it is really an archive.
2181 const StringRef LibFileExt = ".lib";
2182 if (!llvm::sys::path::has_extension(FileName) ||
2183 types::lookupTypeForExtension(
2184 llvm::sys::path::extension(FileName).drop_front()) ==
2185 types::TY_INVALID ||
2186 llvm::sys::path::extension(FileName) == LibFileExt)
2187 SDLNames.insert(Input);
2188 }
2189
2190 // The search stops as soon as an SDL file is found. The driver then provides
2191 // the full filename of the SDL to the llvm-link or clang-nvlink-wrapper
2192 // command. If no SDL is found after searching each LINKPATH with
2193 // SEARCH-ORDER, it is possible that an archive file lib<libname>.a exists
2194 // and may contain bundled object files.
2195 for (auto SDLName : SDLNames) {
2196 // This is the only call to SDLSearch
2197 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
5
Assuming the condition is true
6
Taking true branch
2198 isBitCodeSDL, postClangLink)) {
2199 GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
7
Forming reference to null pointer
2200 LibraryPaths, SDLName, Arch, Target,
2201 isBitCodeSDL, postClangLink);
2202 }
2203 }
2204}
2205
2206static llvm::opt::Arg *
2207getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
2208 // The last of -mcode-object-v3, -mno-code-object-v3 and
2209 // -mcode-object-version=<version> wins.
2210 return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
2211 options::OPT_mno_code_object_v3_legacy,
2212 options::OPT_mcode_object_version_EQ);
2213}
2214
2215void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
2216 const llvm::opt::ArgList &Args) {
2217 const unsigned MinCodeObjVer = 2;
2218 const unsigned MaxCodeObjVer = 5;
2219
2220 // Emit warnings for legacy options even if they are overridden.
2221 if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
2222 D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
2223 << "-mcode-object-version=2";
2224
2225 if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
2226 D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
2227 << "-mcode-object-version=3";
2228
2229 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2230 if (CodeObjArg->getOption().getID() ==
2231 options::OPT_mcode_object_version_EQ) {
2232 unsigned CodeObjVer = MaxCodeObjVer;
2233 auto Remnant =
2234 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2235 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
2236 D.Diag(diag::err_drv_invalid_int_value)
2237 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
2238 }
2239 }
2240}
2241
2242unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
2243 const llvm::opt::ArgList &Args) {
2244 unsigned CodeObjVer = 4; // default
2245 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
2246 if (CodeObjArg->getOption().getID() ==
2247 options::OPT_mno_code_object_v3_legacy) {
2248 CodeObjVer = 2;
2249 } else if (CodeObjArg->getOption().getID() ==
2250 options::OPT_mcode_object_v3_legacy) {
2251 CodeObjVer = 3;
2252 } else {
2253 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
2254 }
2255 }
2256 return CodeObjVer;
2257}
2258
2259bool tools::haveAMDGPUCodeObjectVersionArgument(
2260 const Driver &D, const llvm::opt::ArgList &Args) {
2261 return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
2262}
2263
2264void tools::addMachineOutlinerArgs(const Driver &D,
2265 const llvm::opt::ArgList &Args,
2266 llvm::opt::ArgStringList &CmdArgs,
2267 const llvm::Triple &Triple, bool IsLTO,
2268 const StringRef PluginOptPrefix) {
2269 auto addArg = [&, IsLTO](const Twine &Arg) {
2270 if (IsLTO) {
2271 assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!")(static_cast <bool> (!PluginOptPrefix.empty() &&
"Cannot have empty PluginOptPrefix!") ? void (0) : __assert_fail
("!PluginOptPrefix.empty() && \"Cannot have empty PluginOptPrefix!\""
, "clang/lib/Driver/ToolChains/CommonArgs.cpp", 2271, __extension__
__PRETTY_FUNCTION__))
;
2272 CmdArgs.push_back(Args.MakeArgString(Twine(PluginOptPrefix) + Arg));
2273 } else {
2274 CmdArgs.push_back("-mllvm");
2275 CmdArgs.push_back(Args.MakeArgString(Arg));
2276 }
2277 };
2278
2279 if (Arg *A = Args.getLastArg(options::OPT_moutline,
2280 options::OPT_mno_outline)) {
2281 if (A->getOption().matches(options::OPT_moutline)) {
2282 // We only support -moutline in AArch64 and ARM targets right now. If
2283 // we're not compiling for these, emit a warning and ignore the flag.
2284 // Otherwise, add the proper mllvm flags.
2285 if (!(Triple.isARM() || Triple.isThumb() ||
2286 Triple.getArch() == llvm::Triple::aarch64 ||
2287 Triple.getArch() == llvm::Triple::aarch64_32)) {
2288 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
2289 } else {
2290 addArg(Twine("-enable-machine-outliner"));
2291 }
2292 } else {
2293 // Disable all outlining behaviour.
2294 addArg(Twine("-enable-machine-outliner=never"));
2295 }
2296 }
2297}
2298
2299void tools::addOpenMPDeviceRTL(const Driver &D,
2300 const llvm::opt::ArgList &DriverArgs,
2301 llvm::opt::ArgStringList &CC1Args,
2302 StringRef BitcodeSuffix,
2303 const llvm::Triple &Triple) {
2304 SmallVector<StringRef, 8> LibraryPaths;
2305
2306 // Add path to clang lib / lib64 folder.
2307 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
2308 llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME"lib");
2309 LibraryPaths.emplace_back(DefaultLibPath.c_str());
2310
2311 // Add user defined library paths from LIBRARY_PATH.
2312 llvm::Optional<std::string> LibPath =
2313 llvm::sys::Process::GetEnv("LIBRARY_PATH");
2314 if (LibPath) {
2315 SmallVector<StringRef, 8> Frags;
2316 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
2317 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
2318 for (StringRef Path : Frags)
2319 LibraryPaths.emplace_back(Path.trim());
2320 }
2321
2322 OptSpecifier LibomptargetBCPathOpt =
2323 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ
2324 : options::OPT_libomptarget_nvptx_bc_path_EQ;
2325
2326 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" : "nvptx";
2327 std::string LibOmpTargetName =
2328 ("libomptarget-" + ArchPrefix + "-" + BitcodeSuffix + ".bc").str();
2329
2330 // First check whether user specifies bc library
2331 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
2332 SmallString<128> LibOmpTargetFile(A->getValue());
2333 if (llvm::sys::fs::exists(LibOmpTargetFile) &&
2334 llvm::sys::fs::is_directory(LibOmpTargetFile)) {
2335 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2336 }
2337
2338 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2339 CC1Args.push_back("-mlink-builtin-bitcode");
2340 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2341 } else {
2342 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
2343 << LibOmpTargetFile;
2344 }
2345 } else {
2346 bool FoundBCLibrary = false;
2347
2348 for (StringRef LibraryPath : LibraryPaths) {
2349 SmallString<128> LibOmpTargetFile(LibraryPath);
2350 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
2351 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
2352 CC1Args.push_back("-mlink-builtin-bitcode");
2353 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
2354 FoundBCLibrary = true;
2355 break;
2356 }
2357 }
2358
2359 if (!FoundBCLibrary)
2360 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
2361 << LibOmpTargetName << ArchPrefix;
2362 }
2363}
2364void tools::addHIPRuntimeLibArgs(const ToolChain &TC,
2365 const llvm::opt::ArgList &Args,
2366 llvm::opt::ArgStringList &CmdArgs) {
2367 if (Args.hasArg(options::OPT_hip_link) &&
2368 !Args.hasArg(options::OPT_nostdlib) &&
2369 !Args.hasArg(options::OPT_no_hip_rt)) {
2370 TC.AddHIPRuntimeLibArgs(Args, CmdArgs);
2371 } else {
2372 // Claim "no HIP libraries" arguments if any
2373 for (auto *Arg : Args.filtered(options::OPT_no_hip_rt)) {
2374 Arg->claim();
2375 }
2376 }
2377}