Bug Summary

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