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