clang  19.0.0git
ToolChain.cpp
Go to the documentation of this file.
1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
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 
11 #include "ToolChains/Arch/ARM.h"
12 #include "ToolChains/Clang.h"
13 #include "ToolChains/CommonArgs.h"
14 #include "ToolChains/Flang.h"
17 #include "clang/Basic/Sanitizers.h"
18 #include "clang/Config/config.h"
19 #include "clang/Driver/Action.h"
20 #include "clang/Driver/Driver.h"
22 #include "clang/Driver/InputInfo.h"
23 #include "clang/Driver/Job.h"
24 #include "clang/Driver/Options.h"
26 #include "clang/Driver/XRayArgs.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/MC/MCTargetOptions.h"
34 #include "llvm/MC/TargetRegistry.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/OptTable.h"
38 #include "llvm/Option/Option.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/FileUtilities.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/VersionTuple.h"
45 #include "llvm/Support/VirtualFileSystem.h"
46 #include "llvm/TargetParser/AArch64TargetParser.h"
47 #include "llvm/TargetParser/TargetParser.h"
48 #include "llvm/TargetParser/Triple.h"
49 #include <cassert>
50 #include <cstddef>
51 #include <cstring>
52 #include <string>
53 
54 using namespace clang;
55 using namespace driver;
56 using namespace tools;
57 using namespace llvm;
58 using namespace llvm::opt;
59 
60 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
61  return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
62  options::OPT_fno_rtti, options::OPT_frtti);
63 }
64 
65 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
66  const llvm::Triple &Triple,
67  const Arg *CachedRTTIArg) {
68  // Explicit rtti/no-rtti args
69  if (CachedRTTIArg) {
70  if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
71  return ToolChain::RM_Enabled;
72  else
74  }
75 
76  // -frtti is default, except for the PS4/PS5 and DriverKit.
77  bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
79 }
80 
82  if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
83  true)) {
84  return ToolChain::EM_Enabled;
85  }
87 }
88 
89 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
90  const ArgList &Args)
91  : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
92  CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)),
93  CachedExceptionsMode(CalculateExceptionsMode(Args)) {
94  auto addIfExists = [this](path_list &List, const std::string &Path) {
95  if (getVFS().exists(Path))
96  List.push_back(Path);
97  };
98 
99  if (std::optional<std::string> Path = getRuntimePath())
100  getLibraryPaths().push_back(*Path);
101  if (std::optional<std::string> Path = getStdlibPath())
102  getFilePaths().push_back(*Path);
103  for (const auto &Path : getArchSpecificLibPaths())
104  addIfExists(getFilePaths(), Path);
105 }
106 
108 ToolChain::executeToolChainProgram(StringRef Executable) const {
109  llvm::SmallString<64> OutputFile;
110  llvm::sys::fs::createTemporaryFile("toolchain-program", "txt", OutputFile);
111  llvm::FileRemover OutputRemover(OutputFile.c_str());
112  std::optional<llvm::StringRef> Redirects[] = {
113  {""},
114  OutputFile.str(),
115  {""},
116  };
117 
118  std::string ErrorMessage;
119  if (llvm::sys::ExecuteAndWait(Executable, {}, {}, Redirects,
120  /* SecondsToWait */ 0,
121  /*MemoryLimit*/ 0, &ErrorMessage))
122  return llvm::createStringError(std::error_code(),
123  Executable + ": " + ErrorMessage);
124 
125  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf =
126  llvm::MemoryBuffer::getFile(OutputFile.c_str());
127  if (!OutputBuf)
128  return llvm::createStringError(OutputBuf.getError(),
129  "Failed to read stdout of " + Executable +
130  ": " + OutputBuf.getError().message());
131  return std::move(*OutputBuf);
132 }
133 
134 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
135  Triple.setEnvironment(Env);
136  if (EffectiveTriple != llvm::Triple())
137  EffectiveTriple.setEnvironment(Env);
138 }
139 
140 ToolChain::~ToolChain() = default;
141 
142 llvm::vfs::FileSystem &ToolChain::getVFS() const {
143  return getDriver().getVFS();
144 }
145 
147  return Args.hasFlag(options::OPT_fintegrated_as,
148  options::OPT_fno_integrated_as,
150 }
151 
153  assert(
156  "(Non-)integrated backend set incorrectly!");
157 
158  bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
159  options::OPT_fno_integrated_objemitter,
161 
162  // Diagnose when integrated-objemitter options are not supported by this
163  // toolchain.
164  unsigned DiagID;
165  if ((IBackend && !IsIntegratedBackendSupported()) ||
166  (!IBackend && !IsNonIntegratedBackendSupported()))
167  DiagID = clang::diag::err_drv_unsupported_opt_for_target;
168  else
169  DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
170  Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
172  D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
173  A = Args.getLastArg(options::OPT_fintegrated_objemitter);
174  if (A && !IsIntegratedBackendSupported())
175  D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
176 
177  return IBackend;
178 }
179 
181  return ENABLE_X86_RELAX_RELOCATIONS;
182 }
183 
185  return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
186 }
187 
188 static void getAArch64MultilibFlags(const Driver &D,
189  const llvm::Triple &Triple,
190  const llvm::opt::ArgList &Args,
191  Multilib::flags_list &Result) {
192  std::vector<StringRef> Features;
193  tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, false);
194  const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
195  llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
196  UnifiedFeatures.end());
197  std::vector<std::string> MArch;
198  for (const auto &Ext : AArch64::Extensions)
199  if (FeatureSet.contains(Ext.Feature))
200  MArch.push_back(Ext.Name.str());
201  for (const auto &Ext : AArch64::Extensions)
202  if (FeatureSet.contains(Ext.NegFeature))
203  MArch.push_back(("no" + Ext.Name).str());
204  StringRef ArchName;
205  for (const auto &ArchInfo : AArch64::ArchInfos)
206  if (FeatureSet.contains(ArchInfo->ArchFeature))
207  ArchName = ArchInfo->Name;
208  assert(!ArchName.empty() && "at least one architecture should be found");
209  MArch.insert(MArch.begin(), ("-march=" + ArchName).str());
210  Result.push_back(llvm::join(MArch, "+"));
211 }
212 
213 static void getARMMultilibFlags(const Driver &D,
214  const llvm::Triple &Triple,
215  const llvm::opt::ArgList &Args,
216  Multilib::flags_list &Result) {
217  std::vector<StringRef> Features;
218  llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures(
219  D, Triple, Args, Features, false /*ForAs*/, true /*ForMultilib*/);
220  const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
221  llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
222  UnifiedFeatures.end());
223  std::vector<std::string> MArch;
224  for (const auto &Ext : ARM::ARCHExtNames)
225  if (FeatureSet.contains(Ext.Feature))
226  MArch.push_back(Ext.Name.str());
227  for (const auto &Ext : ARM::ARCHExtNames)
228  if (FeatureSet.contains(Ext.NegFeature))
229  MArch.push_back(("no" + Ext.Name).str());
230  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
231  Result.push_back(llvm::join(MArch, "+"));
232 
233  switch (FPUKind) {
234 #define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION) \
235  case llvm::ARM::KIND: \
236  Result.push_back("-mfpu=" NAME); \
237  break;
238 #include "llvm/TargetParser/ARMTargetParser.def"
239  default:
240  llvm_unreachable("Invalid FPUKind");
241  }
242 
243  switch (arm::getARMFloatABI(D, Triple, Args)) {
244  case arm::FloatABI::Soft:
245  Result.push_back("-mfloat-abi=soft");
246  break;
247  case arm::FloatABI::SoftFP:
248  Result.push_back("-mfloat-abi=softfp");
249  break;
250  case arm::FloatABI::Hard:
251  Result.push_back("-mfloat-abi=hard");
252  break;
253  case arm::FloatABI::Invalid:
254  llvm_unreachable("Invalid float ABI");
255  }
256 }
257 
259 ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
260  using namespace clang::driver::options;
261 
262  std::vector<std::string> Result;
263  const llvm::Triple Triple(ComputeEffectiveClangTriple(Args));
264  Result.push_back("--target=" + Triple.str());
265 
266  switch (Triple.getArch()) {
267  case llvm::Triple::aarch64:
268  case llvm::Triple::aarch64_32:
269  case llvm::Triple::aarch64_be:
270  getAArch64MultilibFlags(D, Triple, Args, Result);
271  break;
272  case llvm::Triple::arm:
273  case llvm::Triple::armeb:
274  case llvm::Triple::thumb:
275  case llvm::Triple::thumbeb:
276  getARMMultilibFlags(D, Triple, Args, Result);
277  break;
278  default:
279  break;
280  }
281 
282  // Include fno-exceptions and fno-rtti
283  // to improve multilib selection
284  if (getRTTIMode() == ToolChain::RTTIMode::RM_Disabled)
285  Result.push_back("-fno-rtti");
286  else
287  Result.push_back("-frtti");
288 
289  if (getExceptionsMode() == ToolChain::ExceptionsMode::EM_Disabled)
290  Result.push_back("-fno-exceptions");
291  else
292  Result.push_back("-fexceptions");
293 
294  // Sort and remove duplicates.
295  std::sort(Result.begin(), Result.end());
296  Result.erase(std::unique(Result.begin(), Result.end()), Result.end());
297  return Result;
298 }
299 
301 ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const {
302  SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked);
303  SanitizerArgsChecked = true;
304  return SanArgs;
305 }
306 
308  if (!XRayArguments)
309  XRayArguments.reset(new XRayArgs(*this, Args));
310  return *XRayArguments;
311 }
312 
313 namespace {
314 
315 struct DriverSuffix {
316  const char *Suffix;
317  const char *ModeFlag;
318 };
319 
320 } // namespace
321 
322 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
323  // A list of known driver suffixes. Suffixes are compared against the
324  // program name in order. If there is a match, the frontend type is updated as
325  // necessary by applying the ModeFlag.
326  static const DriverSuffix DriverSuffixes[] = {
327  {"clang", nullptr},
328  {"clang++", "--driver-mode=g++"},
329  {"clang-c++", "--driver-mode=g++"},
330  {"clang-cc", nullptr},
331  {"clang-cpp", "--driver-mode=cpp"},
332  {"clang-g++", "--driver-mode=g++"},
333  {"clang-gcc", nullptr},
334  {"clang-cl", "--driver-mode=cl"},
335  {"cc", nullptr},
336  {"cpp", "--driver-mode=cpp"},
337  {"cl", "--driver-mode=cl"},
338  {"++", "--driver-mode=g++"},
339  {"flang", "--driver-mode=flang"},
340  {"clang-dxc", "--driver-mode=dxc"},
341  };
342 
343  for (const auto &DS : DriverSuffixes) {
344  StringRef Suffix(DS.Suffix);
345  if (ProgName.ends_with(Suffix)) {
346  Pos = ProgName.size() - Suffix.size();
347  return &DS;
348  }
349  }
350  return nullptr;
351 }
352 
353 /// Normalize the program name from argv[0] by stripping the file extension if
354 /// present and lower-casing the string on Windows.
355 static std::string normalizeProgramName(llvm::StringRef Argv0) {
356  std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
357  if (is_style_windows(llvm::sys::path::Style::native)) {
358  // Transform to lowercase for case insensitive file systems.
359  std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
360  ::tolower);
361  }
362  return ProgName;
363 }
364 
365 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
366  // Try to infer frontend type and default target from the program name by
367  // comparing it against DriverSuffixes in order.
368 
369  // If there is a match, the function tries to identify a target as prefix.
370  // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
371  // prefix "x86_64-linux". If such a target prefix is found, it may be
372  // added via -target as implicit first argument.
373  const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
374 
375  if (!DS && ProgName.ends_with(".exe")) {
376  // Try again after stripping the executable suffix:
377  // clang++.exe -> clang++
378  ProgName = ProgName.drop_back(StringRef(".exe").size());
379  DS = FindDriverSuffix(ProgName, Pos);
380  }
381 
382  if (!DS) {
383  // Try again after stripping any trailing version number:
384  // clang++3.5 -> clang++
385  ProgName = ProgName.rtrim("0123456789.");
386  DS = FindDriverSuffix(ProgName, Pos);
387  }
388 
389  if (!DS) {
390  // Try again after stripping trailing -component.
391  // clang++-tot -> clang++
392  ProgName = ProgName.slice(0, ProgName.rfind('-'));
393  DS = FindDriverSuffix(ProgName, Pos);
394  }
395  return DS;
396 }
397 
400  std::string ProgName = normalizeProgramName(PN);
401  size_t SuffixPos;
402  const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
403  if (!DS)
404  return {};
405  size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
406 
407  size_t LastComponent = ProgName.rfind('-', SuffixPos);
408  if (LastComponent == std::string::npos)
409  return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
410  std::string ModeSuffix = ProgName.substr(LastComponent + 1,
411  SuffixEnd - LastComponent - 1);
412 
413  // Infer target from the prefix.
414  StringRef Prefix(ProgName);
415  Prefix = Prefix.slice(0, LastComponent);
416  std::string IgnoredError;
417  bool IsRegistered =
418  llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
419  return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
420  IsRegistered};
421 }
422 
424  // In universal driver terms, the arch name accepted by -arch isn't exactly
425  // the same as the ones that appear in the triple. Roughly speaking, this is
426  // an inverse of the darwin::getArchTypeForDarwinArchName() function.
427  switch (Triple.getArch()) {
428  case llvm::Triple::aarch64: {
429  if (getTriple().isArm64e())
430  return "arm64e";
431  return "arm64";
432  }
433  case llvm::Triple::aarch64_32:
434  return "arm64_32";
435  case llvm::Triple::ppc:
436  return "ppc";
437  case llvm::Triple::ppcle:
438  return "ppcle";
439  case llvm::Triple::ppc64:
440  return "ppc64";
441  case llvm::Triple::ppc64le:
442  return "ppc64le";
443  default:
444  return Triple.getArchName();
445  }
446 }
447 
448 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
449  return Input.getFilename();
450 }
451 
453 ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
454  return UnwindTableLevel::None;
455 }
456 
457 Tool *ToolChain::getClang() const {
458  if (!Clang)
459  Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
460  return Clang.get();
461 }
462 
463 Tool *ToolChain::getFlang() const {
464  if (!Flang)
465  Flang.reset(new tools::Flang(*this));
466  return Flang.get();
467 }
468 
470  return new tools::ClangAs(*this);
471 }
472 
474  llvm_unreachable("Linking is not supported by this toolchain");
475 }
476 
478  llvm_unreachable("Backend Compilation is not supported by this toolchain");
479 }
480 
482  llvm_unreachable("Creating static lib is not supported by this toolchain");
483 }
484 
485 Tool *ToolChain::getAssemble() const {
486  if (!Assemble)
487  Assemble.reset(buildAssembler());
488  return Assemble.get();
489 }
490 
491 Tool *ToolChain::getClangAs() const {
492  if (!Assemble)
493  Assemble.reset(new tools::ClangAs(*this));
494  return Assemble.get();
495 }
496 
497 Tool *ToolChain::getLink() const {
498  if (!Link)
499  Link.reset(buildLinker());
500  return Link.get();
501 }
502 
503 Tool *ToolChain::getStaticLibTool() const {
504  if (!StaticLibTool)
505  StaticLibTool.reset(buildStaticLibTool());
506  return StaticLibTool.get();
507 }
508 
509 Tool *ToolChain::getIfsMerge() const {
510  if (!IfsMerge)
511  IfsMerge.reset(new tools::ifstool::Merger(*this));
512  return IfsMerge.get();
513 }
514 
515 Tool *ToolChain::getOffloadBundler() const {
516  if (!OffloadBundler)
517  OffloadBundler.reset(new tools::OffloadBundler(*this));
518  return OffloadBundler.get();
519 }
520 
521 Tool *ToolChain::getOffloadWrapper() const {
522  if (!OffloadWrapper)
523  OffloadWrapper.reset(new tools::OffloadWrapper(*this));
524  return OffloadWrapper.get();
525 }
526 
527 Tool *ToolChain::getOffloadPackager() const {
528  if (!OffloadPackager)
529  OffloadPackager.reset(new tools::OffloadPackager(*this));
530  return OffloadPackager.get();
531 }
532 
533 Tool *ToolChain::getOffloadDeps() const {
534  if (!OffloadDeps)
535  OffloadDeps.reset(new tools::OffloadDeps(*this));
536  return OffloadDeps.get();
537 }
538 
539 Tool *ToolChain::getSPIRVTranslator() const {
540  if (!SPIRVTranslator)
541  SPIRVTranslator.reset(new tools::SPIRVTranslator(*this));
542  return SPIRVTranslator.get();
543 }
544 
545 Tool *ToolChain::getSYCLPostLink() const {
546  if (!SYCLPostLink)
547  SYCLPostLink.reset(new tools::SYCLPostLink(*this));
548  return SYCLPostLink.get();
549 }
550 
551 Tool *ToolChain::getBackendCompiler() const {
552  if (!BackendCompiler)
553  BackendCompiler.reset(buildBackendCompiler());
554  return BackendCompiler.get();
555 }
556 
557 Tool *ToolChain::getAppendFooter() const {
558  if (!AppendFooter)
559  AppendFooter.reset(new tools::AppendFooter(*this));
560  return AppendFooter.get();
561 }
562 
563 Tool *ToolChain::getTableTform() const {
564  if (!FileTableTform)
565  FileTableTform.reset(new tools::FileTableTform(*this));
566  return FileTableTform.get();
567 }
568 
569 Tool *ToolChain::getSpirvToIrWrapper() const {
570  if (!SpirvToIrWrapper)
571  SpirvToIrWrapper.reset(new tools::SpirvToIrWrapper(*this));
572  return SpirvToIrWrapper.get();
573 }
574 
575 Tool *ToolChain::getLinkerWrapper() const {
576  if (!LinkerWrapper)
577  LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
578  return LinkerWrapper.get();
579 }
580 
582  switch (AC) {
584  return getAssemble();
585 
587  return getIfsMerge();
588 
590  return getLink();
591 
593  return getStaticLibTool();
594 
595  case Action::InputClass:
603  llvm_unreachable("Invalid tool kind.");
604 
613  return getClang();
614 
617  return getOffloadBundler();
618 
620  return getOffloadWrapper();
622  return getOffloadPackager();
623 
625  return getOffloadDeps();
626 
628  return getSPIRVTranslator();
629 
631  return getSYCLPostLink();
632 
634  return getBackendCompiler();
635 
637  return getAppendFooter();
638 
640  return getTableTform();
641 
643  return getSpirvToIrWrapper();
644 
646  return getLinkerWrapper();
647  }
648 
649  llvm_unreachable("Invalid tool kind.");
650 }
651 
652 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
653  const ArgList &Args) {
654  const llvm::Triple &Triple = TC.getTriple();
655  bool IsWindows = Triple.isOSWindows();
656 
657  if (TC.isBareMetal())
658  return Triple.getArchName();
659 
660  if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
661  return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
662  ? "armhf"
663  : "arm";
664 
665  // For historic reasons, Android library is using i686 instead of i386.
666  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
667  return "i686";
668 
669  if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
670  return "x32";
671 
672  return llvm::Triple::getArchTypeName(TC.getArch());
673 }
674 
675 StringRef ToolChain::getOSLibName() const {
676  if (Triple.isOSDarwin())
677  return "darwin";
678 
679  switch (Triple.getOS()) {
680  case llvm::Triple::FreeBSD:
681  return "freebsd";
682  case llvm::Triple::NetBSD:
683  return "netbsd";
684  case llvm::Triple::OpenBSD:
685  return "openbsd";
686  case llvm::Triple::Solaris:
687  return "sunos";
688  case llvm::Triple::AIX:
689  return "aix";
690  default:
691  return getOS();
692  }
693 }
694 
695 std::string ToolChain::getCompilerRTPath() const {
696  SmallString<128> Path(getDriver().ResourceDir);
697  if (isBareMetal()) {
698  llvm::sys::path::append(Path, "lib", getOSLibName());
699  if (!SelectedMultilibs.empty()) {
700  Path += SelectedMultilibs.back().gccSuffix();
701  }
702  } else if (Triple.isOSUnknown()) {
703  llvm::sys::path::append(Path, "lib");
704  } else {
705  llvm::sys::path::append(Path, "lib", getOSLibName());
706  }
707  return std::string(Path);
708 }
709 
710 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
711  StringRef Component,
712  FileType Type) const {
713  std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
714  return llvm::sys::path::filename(CRTAbsolutePath).str();
715 }
716 
717 std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
718  StringRef Component,
719  FileType Type,
720  bool AddArch) const {
721  const llvm::Triple &TT = getTriple();
722  bool IsITANMSVCWindows =
723  TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
724 
725  const char *Prefix =
726  IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
727  const char *Suffix;
728  switch (Type) {
730  Suffix = IsITANMSVCWindows ? ".obj" : ".o";
731  break;
733  Suffix = IsITANMSVCWindows ? ".lib" : ".a";
734  break;
736  Suffix = TT.isOSWindows()
737  ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
738  : ".so";
739  break;
740  }
741 
742  std::string ArchAndEnv;
743  if (AddArch) {
744  StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
745  const char *Env = TT.isAndroid() ? "-android" : "";
746  ArchAndEnv = ("-" + Arch + Env).str();
747  }
748  return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
749 }
750 
751 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
752  FileType Type) const {
753  // Check for runtime files in the new layout without the architecture first.
754  std::string CRTBasename =
755  buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
756  SmallString<128> Path;
757  for (const auto &LibPath : getLibraryPaths()) {
758  SmallString<128> P(LibPath);
759  llvm::sys::path::append(P, CRTBasename);
760  if (getVFS().exists(P))
761  return std::string(P);
762  if (Path.empty())
763  Path = P;
764  }
765  if (getTriple().isOSAIX())
766  Path.clear();
767 
768  // Check the filename for the old layout if the new one does not exist.
769  CRTBasename =
770  buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
772  llvm::sys::path::append(OldPath, CRTBasename);
773  if (Path.empty() || getVFS().exists(OldPath))
774  return std::string(OldPath);
775 
776  // If none is found, use a file name from the new layout, which may get
777  // printed in an error message, aiding users in knowing what Clang is
778  // looking for.
779  return std::string(Path);
780 }
781 
782 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
783  StringRef Component,
784  FileType Type) const {
785  return Args.MakeArgString(getCompilerRT(Args, Component, Type));
786 }
787 
788 // Android target triples contain a target version. If we don't have libraries
789 // for the exact target version, we should fall back to the next newest version
790 // or a versionless path, if any.
791 std::optional<std::string>
792 ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
793  llvm::Triple TripleWithoutLevel(getTriple());
794  TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
795  const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
796  unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
797  unsigned BestVersion = 0;
798 
799  SmallString<32> TripleDir;
800  bool UsingUnversionedDir = false;
801  std::error_code EC;
802  for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
803  !EC && LI != LE; LI = LI.increment(EC)) {
804  StringRef DirName = llvm::sys::path::filename(LI->path());
805  StringRef DirNameSuffix = DirName;
806  if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
807  if (DirNameSuffix.empty() && TripleDir.empty()) {
808  TripleDir = DirName;
809  UsingUnversionedDir = true;
810  } else {
811  unsigned Version;
812  if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
813  Version < TripleVersion) {
814  BestVersion = Version;
815  TripleDir = DirName;
816  UsingUnversionedDir = false;
817  }
818  }
819  }
820  }
821 
822  if (TripleDir.empty())
823  return {};
824 
825  SmallString<128> P(BaseDir);
826  llvm::sys::path::append(P, TripleDir);
827  if (UsingUnversionedDir)
828  D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
829  return std::string(P);
830 }
831 
832 std::optional<std::string>
833 ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
834  auto getPathForTriple =
835  [&](const llvm::Triple &Triple) -> std::optional<std::string> {
836  SmallString<128> P(BaseDir);
837  llvm::sys::path::append(P, Triple.str());
838  if (getVFS().exists(P))
839  return std::string(P);
840  return {};
841  };
842 
843  if (auto Path = getPathForTriple(getTriple()))
844  return *Path;
845 
846  // When building with per target runtime directories, various ways of naming
847  // the Arm architecture may have been normalised to simply "arm".
848  // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
849  // Since an armv8l system can use libraries built for earlier architecture
850  // versions assuming endian and float ABI match.
851  //
852  // Original triple: armv8l-unknown-linux-gnueabihf
853  // Runtime triple: arm-unknown-linux-gnueabihf
854  //
855  // We do not do this for armeb (big endian) because doing so could make us
856  // select little endian libraries. In addition, all known armeb triples only
857  // use the "armeb" architecture name.
858  //
859  // M profile Arm is bare metal and we know they will not be using the per
860  // target runtime directory layout.
861  if (getTriple().getArch() == Triple::arm && !getTriple().isArmMClass()) {
862  llvm::Triple ArmTriple = getTriple();
863  ArmTriple.setArch(Triple::arm);
864  if (auto Path = getPathForTriple(ArmTriple))
865  return *Path;
866  }
867 
868  if (getTriple().isAndroid())
869  return getFallbackAndroidTargetPath(BaseDir);
870 
871  return {};
872 }
873 
874 std::optional<std::string> ToolChain::getRuntimePath() const {
876  llvm::sys::path::append(P, "lib");
877  if (auto Ret = getTargetSubDirPath(P))
878  return Ret;
879  // Darwin does not use per-target runtime directory.
880  if (Triple.isOSDarwin())
881  return {};
882  llvm::sys::path::append(P, Triple.str());
883  return std::string(P);
884 }
885 
886 std::optional<std::string> ToolChain::getStdlibPath() const {
888  llvm::sys::path::append(P, "..", "lib");
889  return getTargetSubDirPath(P);
890 }
891 
893  path_list Paths;
894 
895  auto AddPath = [&](const ArrayRef<StringRef> &SS) {
896  SmallString<128> Path(getDriver().ResourceDir);
897  llvm::sys::path::append(Path, "lib");
898  for (auto &S : SS)
899  llvm::sys::path::append(Path, S);
900  Paths.push_back(std::string(Path));
901  };
902 
903  AddPath({getTriple().str()});
904  AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
905  return Paths;
906 }
907 
908 bool ToolChain::needsProfileRT(const ArgList &Args) {
909  if (Args.hasArg(options::OPT_noprofilelib))
910  return false;
911 
912  return Args.hasArg(options::OPT_fprofile_generate) ||
913  Args.hasArg(options::OPT_fprofile_generate_EQ) ||
914  Args.hasArg(options::OPT_fcs_profile_generate) ||
915  Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
916  Args.hasArg(options::OPT_fprofile_instr_generate) ||
917  Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
918  Args.hasArg(options::OPT_fcreate_profile) ||
919  Args.hasArg(options::OPT_forder_file_instrumentation);
920 }
921 
922 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
923  return Args.hasArg(options::OPT_coverage) ||
924  Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
925  false);
926 }
927 
929  if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
930  if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
931  Action::ActionClass AC = JA.getKind();
932  if (AC == Action::AssembleJobClass && useIntegratedAs() &&
933  !getTriple().isOSAIX())
934  return getClangAs();
935  return getTool(AC);
936 }
937 
938 std::string ToolChain::GetFilePath(const char *Name) const {
939  return D.GetFilePath(Name, *this);
940 }
941 
942 std::string ToolChain::GetProgramPath(const char *Name) const {
943  return D.GetProgramPath(Name, *this);
944 }
945 
946 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
947  if (LinkerIsLLD)
948  *LinkerIsLLD = false;
949 
950  // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
951  // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
952  const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
953  StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
954 
955  // --ld-path= takes precedence over -fuse-ld= and specifies the executable
956  // name. -B, COMPILER_PATH and PATH and consulted if the value does not
957  // contain a path component separator.
958  // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
959  // that --ld-path= points to is lld.
960  if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
961  std::string Path(A->getValue());
962  if (!Path.empty()) {
963  if (llvm::sys::path::parent_path(Path).empty())
964  Path = GetProgramPath(A->getValue());
965  if (llvm::sys::fs::can_execute(Path)) {
966  if (LinkerIsLLD)
967  *LinkerIsLLD = UseLinker == "lld";
968  return std::string(Path);
969  }
970  }
971  getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
973  }
974  // If we're passed -fuse-ld= with no argument, or with the argument ld,
975  // then use whatever the default system linker is.
976  if (UseLinker.empty() || UseLinker == "ld") {
977  const char *DefaultLinker = getDefaultLinker();
978  if (llvm::sys::path::is_absolute(DefaultLinker))
979  return std::string(DefaultLinker);
980  else
981  return GetProgramPath(DefaultLinker);
982  }
983 
984  // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
985  // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
986  // to a relative path is surprising. This is more complex due to priorities
987  // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
988  if (UseLinker.contains('/'))
989  getDriver().Diag(diag::warn_drv_fuse_ld_path);
990 
991  if (llvm::sys::path::is_absolute(UseLinker)) {
992  // If we're passed what looks like an absolute path, don't attempt to
993  // second-guess that.
994  if (llvm::sys::fs::can_execute(UseLinker))
995  return std::string(UseLinker);
996  } else {
997  llvm::SmallString<8> LinkerName;
998  if (Triple.isOSDarwin())
999  LinkerName.append("ld64.");
1000  else
1001  LinkerName.append("ld.");
1002  LinkerName.append(UseLinker);
1003 
1004  std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
1005  if (llvm::sys::fs::can_execute(LinkerPath)) {
1006  if (LinkerIsLLD)
1007  *LinkerIsLLD = UseLinker == "lld";
1008  return LinkerPath;
1009  }
1010  }
1011 
1012  if (A)
1013  getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1014 
1015  return GetProgramPath(getDefaultLinker());
1016 }
1017 
1018 std::string ToolChain::GetStaticLibToolPath() const {
1019  // TODO: Add support for static lib archiving on Windows
1020  if (Triple.isOSDarwin())
1021  return GetProgramPath("libtool");
1022  return GetProgramPath("llvm-ar");
1023 }
1024 
1027 
1028  // Flang always runs the preprocessor and has no notion of "preprocessed
1029  // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
1030  // them differently.
1031  if (D.IsFlangMode() && id == types::TY_PP_Fortran)
1032  id = types::TY_Fortran;
1033 
1034  return id;
1035 }
1036 
1038  return false;
1039 }
1040 
1042  llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
1043  switch (HostTriple.getArch()) {
1044  // The A32/T32/T16 instruction sets are not separate architectures in this
1045  // context.
1046  case llvm::Triple::arm:
1047  case llvm::Triple::armeb:
1048  case llvm::Triple::thumb:
1049  case llvm::Triple::thumbeb:
1050  return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
1051  getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
1052  default:
1053  return HostTriple.getArch() != getArch();
1054  }
1055 }
1056 
1058  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
1059  VersionTuple());
1060 }
1061 
1062 llvm::ExceptionHandling
1063 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
1065 }
1066 
1067 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
1068  if (Model == "single") {
1069  // FIXME: 'single' is only supported on ARM and WebAssembly so far.
1070  return Triple.getArch() == llvm::Triple::arm ||
1071  Triple.getArch() == llvm::Triple::armeb ||
1072  Triple.getArch() == llvm::Triple::thumb ||
1073  Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
1074  } else if (Model == "posix")
1075  return true;
1076 
1077  return false;
1078 }
1079 
1080 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
1081  types::ID InputType) const {
1082  switch (getTriple().getArch()) {
1083  default:
1084  return getTripleString();
1085 
1086  case llvm::Triple::x86_64: {
1087  llvm::Triple Triple = getTriple();
1088  if (!Triple.isOSBinFormatMachO())
1089  return getTripleString();
1090 
1091  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1092  // x86_64h goes in the triple. Other -march options just use the
1093  // vanilla triple we already have.
1094  StringRef MArch = A->getValue();
1095  if (MArch == "x86_64h")
1096  Triple.setArchName(MArch);
1097  }
1098  return Triple.getTriple();
1099  }
1100  case llvm::Triple::aarch64: {
1101  llvm::Triple Triple = getTriple();
1102  if (!Triple.isOSBinFormatMachO())
1103  return getTripleString();
1104 
1105  if (Triple.isArm64e())
1106  return getTripleString();
1107 
1108  // FIXME: older versions of ld64 expect the "arm64" component in the actual
1109  // triple string and query it to determine whether an LTO file can be
1110  // handled. Remove this when we don't care any more.
1111  Triple.setArchName("arm64");
1112  return Triple.getTriple();
1113  }
1114  case llvm::Triple::aarch64_32:
1115  return getTripleString();
1116  case llvm::Triple::arm:
1117  case llvm::Triple::armeb:
1118  case llvm::Triple::thumb:
1119  case llvm::Triple::thumbeb: {
1120  llvm::Triple Triple = getTriple();
1121  tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1122  tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
1123  return Triple.getTriple();
1124  }
1125  }
1126 }
1127 
1128 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1129  types::ID InputType) const {
1130  return ComputeLLVMTriple(Args, InputType);
1131 }
1132 
1133 std::string ToolChain::computeSysRoot() const {
1134  return D.SysRoot;
1135 }
1136 
1137 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1138  ArgStringList &CC1Args) const {
1139  // Each toolchain should provide the appropriate include flags.
1140 }
1141 
1143  const ArgList &DriverArgs, ArgStringList &CC1Args,
1144  Action::OffloadKind DeviceOffloadKind) const {}
1145 
1146 void ToolChain::addClangCC1ASTargetOptions(const ArgList &Args,
1147  ArgStringList &CC1ASArgs) const {}
1148 
1149 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1150 
1151 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1152  llvm::opt::ArgStringList &CmdArgs) const {
1153  if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1154  return;
1155 
1156  CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1157 }
1158 
1160  const ArgList &Args) const {
1161  if (runtimeLibType)
1162  return *runtimeLibType;
1163 
1164  const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1165  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1166 
1167  // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1168  if (LibName == "compiler-rt")
1169  runtimeLibType = ToolChain::RLT_CompilerRT;
1170  else if (LibName == "libgcc")
1171  runtimeLibType = ToolChain::RLT_Libgcc;
1172  else if (LibName == "platform")
1173  runtimeLibType = GetDefaultRuntimeLibType();
1174  else {
1175  if (A)
1176  getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1177  << A->getAsString(Args);
1178 
1179  runtimeLibType = GetDefaultRuntimeLibType();
1180  }
1181 
1182  return *runtimeLibType;
1183 }
1184 
1186  const ArgList &Args) const {
1187  if (unwindLibType)
1188  return *unwindLibType;
1189 
1190  const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1191  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1192 
1193  if (LibName == "none")
1194  unwindLibType = ToolChain::UNW_None;
1195  else if (LibName == "platform" || LibName == "") {
1196  ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
1197  if (RtLibType == ToolChain::RLT_CompilerRT) {
1198  if (getTriple().isAndroid() || getTriple().isOSAIX())
1199  unwindLibType = ToolChain::UNW_CompilerRT;
1200  else
1201  unwindLibType = ToolChain::UNW_None;
1202  } else if (RtLibType == ToolChain::RLT_Libgcc)
1203  unwindLibType = ToolChain::UNW_Libgcc;
1204  } else if (LibName == "libunwind") {
1205  if (GetRuntimeLibType(Args) == RLT_Libgcc)
1206  getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1207  unwindLibType = ToolChain::UNW_CompilerRT;
1208  } else if (LibName == "libgcc")
1209  unwindLibType = ToolChain::UNW_Libgcc;
1210  else {
1211  if (A)
1212  getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1213  << A->getAsString(Args);
1214 
1215  unwindLibType = GetDefaultUnwindLibType();
1216  }
1217 
1218  return *unwindLibType;
1219 }
1220 
1222  if (cxxStdlibType)
1223  return *cxxStdlibType;
1224 
1225  const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1226  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1227 
1228  // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1229  if (LibName == "libc++")
1230  cxxStdlibType = ToolChain::CST_Libcxx;
1231  else if (LibName == "libstdc++")
1232  cxxStdlibType = ToolChain::CST_Libstdcxx;
1233  else if (LibName == "platform")
1234  cxxStdlibType = GetDefaultCXXStdlibType();
1235  else {
1236  if (A)
1237  getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1238  << A->getAsString(Args);
1239 
1240  cxxStdlibType = GetDefaultCXXStdlibType();
1241  }
1242 
1243  return *cxxStdlibType;
1244 }
1245 
1246 /// Utility function to add a system include directory to CC1 arguments.
1247 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1248  ArgStringList &CC1Args,
1249  const Twine &Path) {
1250  CC1Args.push_back("-internal-isystem");
1251  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1252 }
1253 
1254 /// Utility function to add a system include directory with extern "C"
1255 /// semantics to CC1 arguments.
1256 ///
1257 /// Note that this should be used rarely, and only for directories that
1258 /// historically and for legacy reasons are treated as having implicit extern
1259 /// "C" semantics. These semantics are *ignored* by and large today, but its
1260 /// important to preserve the preprocessor changes resulting from the
1261 /// classification.
1262 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1263  ArgStringList &CC1Args,
1264  const Twine &Path) {
1265  CC1Args.push_back("-internal-externc-isystem");
1266  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1267 }
1268 
1269 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1270  ArgStringList &CC1Args,
1271  const Twine &Path) {
1272  if (llvm::sys::fs::exists(Path))
1273  addExternCSystemInclude(DriverArgs, CC1Args, Path);
1274 }
1275 
1276 /// Utility function to add a list of system include directories to CC1.
1277 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1278  ArgStringList &CC1Args,
1279  ArrayRef<StringRef> Paths) {
1280  for (const auto &Path : Paths) {
1281  CC1Args.push_back("-internal-isystem");
1282  CC1Args.push_back(DriverArgs.MakeArgString(Path));
1283  }
1284 }
1285 
1286 /*static*/ std::string ToolChain::concat(StringRef Path, const Twine &A,
1287  const Twine &B, const Twine &C,
1288  const Twine &D) {
1289  SmallString<128> Result(Path);
1290  llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1291  return std::string(Result);
1292 }
1293 
1294 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1295  std::error_code EC;
1296  int MaxVersion = 0;
1297  std::string MaxVersionString;
1298  SmallString<128> Path(IncludePath);
1299  llvm::sys::path::append(Path, "c++");
1300  for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1301  !EC && LI != LE; LI = LI.increment(EC)) {
1302  StringRef VersionText = llvm::sys::path::filename(LI->path());
1303  int Version;
1304  if (VersionText[0] == 'v' &&
1305  !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
1306  if (Version > MaxVersion) {
1307  MaxVersion = Version;
1308  MaxVersionString = std::string(VersionText);
1309  }
1310  }
1311  }
1312  if (!MaxVersion)
1313  return "";
1314  return MaxVersionString;
1315 }
1316 
1317 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1318  ArgStringList &CC1Args) const {
1319  // Header search paths should be handled by each of the subclasses.
1320  // Historically, they have not been, and instead have been handled inside of
1321  // the CC1-layer frontend. As the logic is hoisted out, this generic function
1322  // will slowly stop being called.
1323  //
1324  // While it is being called, replicate a bit of a hack to propagate the
1325  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1326  // header search paths with it. Once all systems are overriding this
1327  // function, the CC1 flag and this line can be removed.
1328  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1329 }
1330 
1332  const llvm::opt::ArgList &DriverArgs,
1333  llvm::opt::ArgStringList &CC1Args) const {
1334  DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1335  // This intentionally only looks at -nostdinc++, and not -nostdinc or
1336  // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1337  // setups with non-standard search logic for the C++ headers, while still
1338  // allowing users of the toolchain to bring their own C++ headers. Such a
1339  // toolchain likely also has non-standard search logic for the C headers and
1340  // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1341  // still work in that case and only be suppressed by an explicit -nostdinc++
1342  // in a project using the toolchain.
1343  if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1344  for (const auto &P :
1345  DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1346  addSystemInclude(DriverArgs, CC1Args, P);
1347 }
1348 
1349 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1350  return getDriver().CCCIsCXX() &&
1351  !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1352  options::OPT_nostdlibxx);
1353 }
1354 
1355 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1356  ArgStringList &CmdArgs) const {
1357  assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1358  "should not have called this");
1360 
1361  switch (Type) {
1362  case ToolChain::CST_Libcxx:
1363  CmdArgs.push_back("-lc++");
1364  if (Args.hasArg(options::OPT_fexperimental_library))
1365  CmdArgs.push_back("-lc++experimental");
1366  break;
1367 
1369  CmdArgs.push_back("-lstdc++");
1370  break;
1371  }
1372 }
1373 
1374 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1375  ArgStringList &CmdArgs) const {
1376  for (const auto &LibPath : getFilePaths())
1377  if(LibPath.length() > 0)
1378  CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1379 }
1380 
1381 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1382  ArgStringList &CmdArgs) const {
1383  CmdArgs.push_back("-lcc_kext");
1384 }
1385 
1386 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
1387  std::string &Path) const {
1388  // Don't implicitly link in mode-changing libraries in a shared library, since
1389  // this can have very deleterious effects. See the various links from
1390  // https://github.com/llvm/llvm-project/issues/57589 for more information.
1391  bool Default = !Args.hasArgNoClaim(options::OPT_shared);
1392 
1393  // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1394  // (to keep the linker options consistent with gcc and clang itself).
1395  if (Default && !isOptimizationLevelFast(Args)) {
1396  // Check if -ffast-math or -funsafe-math.
1397  Arg *A = Args.getLastArg(
1398  options::OPT_ffast_math, options::OPT_fno_fast_math,
1399  options::OPT_funsafe_math_optimizations,
1400  options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ);
1401 
1402  if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1403  A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1404  Default = false;
1405  if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) {
1406  StringRef Model = A->getValue();
1407  if (Model != "fast")
1408  Default = false;
1409  }
1410  }
1411 
1412  // Whatever decision came as a result of the above implicit settings, either
1413  // -mdaz-ftz or -mno-daz-ftz is capable of overriding it.
1414  if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default))
1415  return false;
1416 
1417  // If crtfastmath.o exists add it to the arguments.
1418  Path = GetFilePath("crtfastmath.o");
1419  return (Path != "crtfastmath.o"); // Not found.
1420 }
1421 
1423  ArgStringList &CmdArgs) const {
1424  std::string Path;
1425  if (isFastMathRuntimeAvailable(Args, Path)) {
1426  CmdArgs.push_back(Args.MakeArgString(Path));
1427  return true;
1428  }
1429 
1430  return false;
1431 }
1432 
1434 ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1435  return SmallVector<std::string>();
1436 }
1437 
1439  // Return sanitizers which don't require runtime support and are not
1440  // platform dependent.
1441 
1442  SanitizerMask Res =
1444  (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1445  SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1446  SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1447  SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1448  SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1449  if (getTriple().getArch() == llvm::Triple::x86 ||
1450  getTriple().getArch() == llvm::Triple::x86_64 ||
1451  getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
1452  getTriple().isAArch64() || getTriple().isRISCV() ||
1453  getTriple().isLoongArch64())
1454  Res |= SanitizerKind::CFIICall;
1455  if (getTriple().getArch() == llvm::Triple::x86_64 ||
1456  getTriple().isAArch64(64) || getTriple().isRISCV())
1457  Res |= SanitizerKind::ShadowCallStack;
1458  if (getTriple().isAArch64(64))
1459  Res |= SanitizerKind::MemTag;
1460  return Res;
1461 }
1462 
1463 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1464  ArgStringList &CC1Args) const {}
1465 
1466 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1467  ArgStringList &CC1Args) const {}
1468 
1471  const ArgList &DriverArgs,
1472  const Action::OffloadKind DeviceOffloadingKind) const {
1473  return {};
1474 }
1475 
1476 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1477  ArgStringList &CC1Args) const {}
1478 
1479 static VersionTuple separateMSVCFullVersion(unsigned Version) {
1480  if (Version < 100)
1481  return VersionTuple(Version);
1482 
1483  if (Version < 10000)
1484  return VersionTuple(Version / 100, Version % 100);
1485 
1486  unsigned Build = 0, Factor = 1;
1487  for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1488  Build = Build + (Version % 10) * Factor;
1489  return VersionTuple(Version / 100, Version % 100, Build);
1490 }
1491 
1492 VersionTuple
1494  const llvm::opt::ArgList &Args) const {
1495  const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1496  const Arg *MSCompatibilityVersion =
1497  Args.getLastArg(options::OPT_fms_compatibility_version);
1498 
1499  if (MSCVersion && MSCompatibilityVersion) {
1500  if (D)
1501  D->Diag(diag::err_drv_argument_not_allowed_with)
1502  << MSCVersion->getAsString(Args)
1503  << MSCompatibilityVersion->getAsString(Args);
1504  return VersionTuple();
1505  }
1506 
1507  if (MSCompatibilityVersion) {
1508  VersionTuple MSVT;
1509  if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1510  if (D)
1511  D->Diag(diag::err_drv_invalid_value)
1512  << MSCompatibilityVersion->getAsString(Args)
1513  << MSCompatibilityVersion->getValue();
1514  } else {
1515  return MSVT;
1516  }
1517  }
1518 
1519  if (MSCVersion) {
1520  unsigned Version = 0;
1521  if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1522  if (D)
1523  D->Diag(diag::err_drv_invalid_value)
1524  << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1525  } else {
1526  return separateMSVCFullVersion(Version);
1527  }
1528  }
1529 
1530  return VersionTuple();
1531 }
1532 
1533 llvm::opt::DerivedArgList *ToolChain::TranslateOffloadTargetArgs(
1534  const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1535  SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs,
1536  Action::OffloadKind DeviceOffloadKind) const {
1537  assert((DeviceOffloadKind == Action::OFK_OpenMP ||
1538  DeviceOffloadKind == Action::OFK_SYCL) &&
1539  "requires OpenMP or SYCL offload kind");
1540  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1541  const OptTable &Opts = getDriver().getOpts();
1542  bool Modified = false;
1543 
1544  // Handle -Xopenmp-target and -Xsycl-target-frontend flags
1545  for (auto *A : Args) {
1546  // Exclude flags which may only apply to the host toolchain.
1547  // Do not exclude flags when the host triple (AuxTriple)
1548  // matches the current toolchain triple. If it is not present
1549  // at all, target and host share a toolchain.
1550  if (A->getOption().matches(options::OPT_m_Group)) {
1551  // AMD GPU is a special case, as -mcpu is required for the device
1552  // compilation, except for SYCL which uses --offload-arch.
1553  // Pass code object version to device toolchain
1554  // to correctly set metadata in intermediate files.
1555  if (SameTripleAsHost ||
1556  A->getOption().matches(options::OPT_mcode_object_version_EQ) ||
1557  (getTriple().getArch() == llvm::Triple::amdgcn &&
1558  DeviceOffloadKind != Action::OFK_SYCL)) {
1559  DAL->append(A);
1560  continue;
1561  }
1562  // SPIR/SPIR-V special case for -mlong-double
1563  if (getTriple().isSPIROrSPIRV() &&
1564  A->getOption().matches(options::OPT_LongDouble_Group)) {
1565  DAL->append(A);
1566  continue;
1567  }
1568  Modified = true;
1569  continue;
1570  }
1571 
1572  // Exclude -fsycl
1573  if (A->getOption().matches(options::OPT_fsycl)) {
1574  Modified = true;
1575  continue;
1576  }
1577 
1578  unsigned Index = 0;
1579  unsigned Prev;
1580  bool XOffloadTargetNoTriple;
1581 
1582  // TODO: functionality between OpenMP offloading and SYCL offloading
1583  // is similar, can be improved
1584  if (DeviceOffloadKind == Action::OFK_OpenMP) {
1585  XOffloadTargetNoTriple =
1586  A->getOption().matches(options::OPT_Xopenmp_target);
1587  if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1588  llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1589 
1590  // Passing device args: -Xopenmp-target=<triple> -opt=val.
1591  if (TT.getTriple() == getTripleString())
1592  Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1593  else
1594  continue;
1595  } else if (XOffloadTargetNoTriple) {
1596  // Passing device args: -Xopenmp-target -opt=val.
1597  Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1598  } else {
1599  DAL->append(A);
1600  continue;
1601  }
1602  } else if (DeviceOffloadKind == Action::OFK_SYCL) {
1603  XOffloadTargetNoTriple =
1604  A->getOption().matches(options::OPT_Xsycl_frontend);
1605  if (A->getOption().matches(options::OPT_Xsycl_frontend_EQ)) {
1606  // Passing device args: -Xsycl-target-frontend=<triple> -opt=val.
1607  if (getDriver().MakeSYCLDeviceTriple(A->getValue(0)) == getTriple())
1608  Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1609  else
1610  continue;
1611  } else if (XOffloadTargetNoTriple) {
1612  // Passing device args: -Xsycl-target-frontend -opt=val.
1613  Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1614  } else {
1615  DAL->append(A);
1616  continue;
1617  }
1618  }
1619 
1620  // Parse the argument to -Xopenmp-target.
1621  Prev = Index;
1622  std::unique_ptr<Arg> XOffloadTargetArg(Opts.ParseOneArg(Args, Index));
1623  if (!XOffloadTargetArg || Index > Prev + 1) {
1624  if (DeviceOffloadKind == Action::OFK_OpenMP) {
1625  getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1626  << A->getAsString(Args);
1627  } else {
1628  getDriver().Diag(diag::err_drv_invalid_Xsycl_frontend_with_args)
1629  << A->getAsString(Args);
1630  }
1631  continue;
1632  }
1633  if (XOffloadTargetNoTriple && XOffloadTargetArg) {
1634  // TODO: similar behaviors with OpenMP and SYCL offloading, can be
1635  // improved upon
1636  auto SingleTargetTripleCount = [&Args](OptSpecifier Opt) {
1637  const Arg *TargetArg = Args.getLastArg(Opt);
1638  if (!TargetArg || TargetArg->getValues().size() == 1)
1639  return true;
1640  return false;
1641  };
1642  if (DeviceOffloadKind == Action::OFK_OpenMP &&
1643  !SingleTargetTripleCount(options::OPT_fopenmp_targets_EQ)) {
1644  getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1645  continue;
1646  }
1647  if (DeviceOffloadKind == Action::OFK_SYCL &&
1648  !SingleTargetTripleCount(options::OPT_fsycl_targets_EQ)) {
1649  getDriver().Diag(diag::err_drv_Xsycl_target_missing_triple)
1650  << A->getSpelling();
1651  continue;
1652  }
1653  }
1654 
1655  XOffloadTargetArg->setBaseArg(A);
1656  A = XOffloadTargetArg.release();
1657  AllocatedArgs.push_back(A);
1658  DAL->append(A);
1659  Modified = true;
1660  }
1661 
1662  if (Modified)
1663  return DAL;
1664 
1665  delete DAL;
1666  return nullptr;
1667 }
1668 
1669 // TODO: Currently argument values separated by space e.g.
1670 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1671 // fixed.
1673  const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1674  llvm::opt::DerivedArgList *DAL,
1675  SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1676  const OptTable &Opts = getDriver().getOpts();
1677  unsigned ValuePos = 1;
1678  if (A->getOption().matches(options::OPT_Xarch_device) ||
1679  A->getOption().matches(options::OPT_Xarch_host))
1680  ValuePos = 0;
1681 
1682  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1683  unsigned Prev = Index;
1684  std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1685 
1686  // If the argument parsing failed or more than one argument was
1687  // consumed, the -Xarch_ argument's parameter tried to consume
1688  // extra arguments. Emit an error and ignore.
1689  //
1690  // We also want to disallow any options which would alter the
1691  // driver behavior; that isn't going to work in our model. We
1692  // use options::NoXarchOption to control this.
1693  if (!XarchArg || Index > Prev + 1) {
1694  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1695  << A->getAsString(Args);
1696  return;
1697  } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1698  auto &Diags = getDriver().getDiags();
1699  unsigned DiagID =
1701  "invalid Xarch argument: '%0', not all driver "
1702  "options can be forwared via Xarch argument");
1703  Diags.Report(DiagID) << A->getAsString(Args);
1704  return;
1705  }
1706  XarchArg->setBaseArg(A);
1707  A = XarchArg.release();
1708  if (!AllocatedArgs)
1709  DAL->AddSynthesizedArg(A);
1710  else
1711  AllocatedArgs->push_back(A);
1712 }
1713 
1714 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1715  const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1716  Action::OffloadKind OFK,
1717  SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1718  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1719  bool Modified = false;
1720 
1721  bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
1722  for (Arg *A : Args) {
1723  bool NeedTrans = false;
1724  bool Skip = false;
1725  if (A->getOption().matches(options::OPT_Xarch_device)) {
1726  NeedTrans = IsDevice;
1727  Skip = !IsDevice;
1728  } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1729  NeedTrans = !IsDevice;
1730  Skip = IsDevice;
1731  } else if (A->getOption().matches(options::OPT_Xarch__) && IsDevice) {
1732  // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1733  // they may need special translation.
1734  // Skip this argument unless the architecture matches BoundArch
1735  if (BoundArch.empty() || A->getValue(0) != BoundArch)
1736  Skip = true;
1737  else
1738  NeedTrans = true;
1739  }
1740  if (NeedTrans || Skip)
1741  Modified = true;
1742  if (NeedTrans)
1743  TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1744  if (!Skip)
1745  DAL->append(A);
1746  }
1747 
1748  if (Modified)
1749  return DAL;
1750 
1751  delete DAL;
1752  return nullptr;
1753 }
clang::driver::toolchains::AIX AIX
Definition: AIX.cpp:22
StringRef P
const Environment & Env
Definition: HTMLLogger.cpp:148
Defines types useful for describing an Objective-C runtime.
Defines the clang::SanitizerKind enum.
static void getAArch64MultilibFlags(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, Multilib::flags_list &Result)
Definition: ToolChain.cpp:188
static const DriverSuffix * parseDriverSuffix(StringRef ProgName, size_t &Pos)
Definition: ToolChain.cpp:365
static std::string normalizeProgramName(llvm::StringRef Argv0)
Normalize the program name from argv[0] by stripping the file extension if present and lower-casing t...
Definition: ToolChain.cpp:355
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, const ArgList &Args)
Definition: ToolChain.cpp:652
static llvm::opt::Arg * GetRTTIArgument(const ArgList &Args)
Definition: ToolChain.cpp:60
static const DriverSuffix * FindDriverSuffix(StringRef ProgName, size_t &Pos)
Definition: ToolChain.cpp:322
static VersionTuple separateMSVCFullVersion(unsigned Version)
Definition: ToolChain.cpp:1479
static ToolChain::ExceptionsMode CalculateExceptionsMode(const ArgList &Args)
Definition: ToolChain.cpp:81
static void getARMMultilibFlags(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, Multilib::flags_list &Result)
Definition: ToolChain.cpp:213
static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, const llvm::Triple &Triple, const Arg *CachedRTTIArg)
Definition: ToolChain.cpp:65
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:879
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition: ObjCRuntime.h:53
The base class of the type hierarchy.
Definition: Type.h:1813
ActionClass getKind() const
Definition: Action.h:159
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
std::string SysRoot
sysroot, if present
Definition: Driver.h:182
std::string GetFilePath(StringRef Name, const ToolChain &TC) const
GetFilePath - Lookup Name in the list of file search paths.
Definition: Driver.cpp:9776
llvm::vfs::FileSystem & getVFS() const
Definition: Driver.h:405
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:146
DiagnosticsEngine & getDiags() const
Definition: Driver.h:403
std::string GetProgramPath(StringRef Name, const ToolChain &TC) const
GetProgramPath - Lookup Name in the list of program search paths.
Definition: Driver.cpp:9836
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:401
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:166
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:157
bool IsFlangMode() const
Whether the driver should invoke flang for fortran inputs.
Definition: Driver.h:228
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:215
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getFilename() const
Definition: InputInfo.h:83
std::vector< std::string > flags_list
Definition: Multilib.h:34
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
virtual bool isFastMathRuntimeAvailable(const llvm::opt::ArgList &Args, std::string &Path) const
If a runtime library exists that sets global flags for unsafe floating point math,...
Definition: ToolChain.cpp:1386
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
Definition: ToolChain.cpp:1128
virtual Tool * buildBackendCompiler() const
Definition: ToolChain.cpp:477
const Driver & getDriver() const
Definition: ToolChain.h:269
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:1381
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:1149
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
Definition: ToolChain.cpp:1247
virtual llvm::opt::DerivedArgList * TranslateOffloadTargetArgs(const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, SmallVectorImpl< llvm::opt::Arg * > &AllocatedArgs, Action::OffloadKind DeviceOffloadKind) const
TranslateOffloadTargetArgs - Create a new derived argument list for that contains the Offload target ...
Definition: ToolChain.cpp:1533
path_list & getFilePaths()
Definition: ToolChain.h:311
virtual std::string computeSysRoot() const
Return the sysroot, possibly searching for a default sysroot using target-specific logic.
Definition: ToolChain.cpp:1133
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
Definition: ToolChain.cpp:146
static llvm::Triple getOpenMPTriple(StringRef TripleStr)
Definition: ToolChain.h:822
std::optional< std::string > getStdlibPath() const
Definition: ToolChain.cpp:886
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1159
virtual UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const
How detailed should the unwind tables be by default.
Definition: ToolChain.cpp:453
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:782
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:1349
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments.
Definition: ToolChain.cpp:1262
virtual std::string getInputFilename(const InputInfo &Input) const
Some toolchains need to modify the file name, for example to replace the extension for object files w...
Definition: ToolChain.cpp:448
virtual Tool * buildStaticLibTool() const
Definition: ToolChain.cpp:481
virtual bool IsIntegratedBackendSupported() const
IsIntegratedBackendSupported - Does this tool chain support -fintegrated-objemitter.
Definition: ToolChain.h:461
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:938
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
Definition: ToolChain.cpp:928
path_list & getLibraryPaths()
Definition: ToolChain.h:308
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
Definition: ToolChain.cpp:908
StringRef getOS() const
Definition: ToolChain.h:288
virtual bool isBareMetal() const
isBareMetal - Is this a bare metal target.
Definition: ToolChain.h:644
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
Definition: ToolChain.cpp:1067
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:285
const llvm::Triple & getTriple() const
Definition: ToolChain.h:271
virtual std::string detectLibcxxVersion(StringRef IncludePath) const
Definition: ToolChain.cpp:1294
static std::string concat(StringRef Path, const Twine &A, const Twine &B="", const Twine &C="", const Twine &D="")
Definition: ToolChain.cpp:1286
RTTIMode getRTTIMode() const
Definition: ToolChain.h:343
ExceptionsMode getExceptionsMode() const
Definition: ToolChain.h:346
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:142
Multilib::flags_list getMultilibFlags(const llvm::opt::ArgList &) const
Get flags suitable for multilib selection, based on the provided clang command line arguments.
Definition: ToolChain.cpp:259
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
Definition: ToolChain.cpp:922
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
Definition: ToolChain.cpp:1080
ToolChain(const Driver &D, const llvm::Triple &T, const llvm::opt::ArgList &Args)
Definition: ToolChain.cpp:89
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:307
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
Definition: ToolChain.cpp:1331
bool addFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:1422
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Definition: ToolChain.cpp:1269
virtual bool useIntegratedBackend() const
Check if the toolchain should use the integrated backend.
Definition: ToolChain.cpp:152
std::string GetStaticLibToolPath() const
Returns the linker path for emitting a static library.
Definition: ToolChain.cpp:1018
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
Definition: ToolChain.cpp:1063
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:1355
static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName)
Return any implicit target and/or mode flag for an invocation of the compiler driver as ProgName.
Definition: ToolChain.cpp:399
virtual bool IsIntegratedBackendDefault() const
IsIntegratedBackendDefault - Does this tool chain enable -fintegrated-objemitter by default.
Definition: ToolChain.h:457
virtual Tool * buildLinker() const
Definition: ToolChain.cpp:473
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
Definition: ToolChain.cpp:184
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition: ToolChain.cpp:1025
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: ToolChain.cpp:1037
virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1185
std::optional< std::string > getTargetSubDirPath(StringRef BaseDir) const
Find the target-specific subdirectory for the current target triple under BaseDir,...
Definition: ToolChain.cpp:833
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
Definition: ToolChain.cpp:1151
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
Definition: ToolChain.cpp:1463
virtual std::string getCompilerRTPath() const
Definition: ToolChain.cpp:695
virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type, bool AddArch) const
Definition: ToolChain.cpp:717
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:946
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:751
virtual Expected< SmallVector< std::string > > getSystemGPUArchs(const llvm::opt::ArgList &Args) const
getSystemGPUArchs - Use a tool to detect the user's availible GPUs.
Definition: ToolChain.cpp:1434
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:942
static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system include directories to CC1.
Definition: ToolChain.cpp:1277
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
Definition: ToolChain.cpp:1466
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: ToolChain.cpp:1317
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
Definition: ToolChain.cpp:1493
virtual StringRef getOSLibName() const
Definition: ToolChain.cpp:675
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
Definition: ToolChain.cpp:1476
virtual CXXStdlibType GetDefaultCXXStdlibType() const
Definition: ToolChain.h:519
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:1374
std::string getTripleString() const
Definition: ToolChain.h:294
virtual RuntimeLibType GetDefaultRuntimeLibType() const
GetDefaultRuntimeLibType - Get the default runtime library variant to use.
Definition: ToolChain.h:515
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
Definition: ToolChain.cpp:423
virtual Tool * buildAssembler() const
Definition: ToolChain.cpp:469
void setTripleEnvironment(llvm::Triple::EnvironmentType Env)
Definition: ToolChain.cpp:134
virtual void addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const
Add options that need to be passed to cc1as for this target.
Definition: ToolChain.cpp:1146
virtual bool IsIntegratedAssemblerDefault() const
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition: ToolChain.h:453
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:301
virtual llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, const Action::OffloadKind DeviceOffloadingKind) const
Get paths for device libraries.
Definition: ToolChain.cpp:1470
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1221
llvm::SmallVector< Multilib > SelectedMultilibs
Definition: ToolChain.h:217
llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > executeToolChainProgram(StringRef Executable) const
Executes the given Executable and returns the stdout.
Definition: ToolChain.cpp:108
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition: ToolChain.h:512
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:1142
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
Definition: ToolChain.cpp:1137
virtual UnwindLibType GetDefaultUnwindLibType() const
Definition: ToolChain.h:523
std::optional< std::string > getRuntimePath() const
Definition: ToolChain.cpp:874
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:581
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:1438
virtual path_list getArchSpecificLibPaths() const
Definition: ToolChain.cpp:892
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:1041
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:710
virtual bool IsNonIntegratedBackendSupported() const
IsNonIntegratedBackendSupported - Does this tool chain support -fno-integrated-objemitter.
Definition: ToolChain.h:465
virtual void TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, llvm::opt::DerivedArgList *DAL, SmallVectorImpl< llvm::opt::Arg * > *AllocatedArgs=nullptr) const
Append the argument following A to DAL assuming A is an Xarch argument.
Definition: ToolChain.cpp:1672
virtual bool useRelaxRelocations() const
Check whether to enable x86 relax relocations by default.
Definition: ToolChain.cpp:180
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
Definition: ToolChain.cpp:1057
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
Append Footer tool.
Definition: Clang.h:258
Clang integrated assembler tool.
Definition: Clang.h:127
Clang compiler tool.
Definition: Clang.h:28
File table transformation tool.
Definition: Clang.h:244
Flang compiler tool.
Definition: Flang.h:25
Linker wrapper tool.
Definition: Clang.h:287
Offload bundler tool.
Definition: Clang.h:150
Offload deps tool.
Definition: Clang.h:194
Offload binary tool.
Definition: Clang.h:181
Offload wrapper tool.
Definition: Clang.h:168
SPIR-V translator tool.
Definition: Clang.h:217
SPIR-V to LLVM-IR wrapper tool.
Definition: Clang.h:272
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
void getAArch64TargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features, bool ForAS)
void setArchNameInTriple(const Driver &D, const llvm::opt::ArgList &Args, types::ID InputType, llvm::Triple &Triple)
void setFloatABIInTriple(const Driver &D, const llvm::opt::ArgList &Args, llvm::Triple &triple)
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
llvm::ARM::FPUKind getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features, bool ForAS, bool ForMultilib=false)
SmallVector< StringRef > unifyTargetFeatures(ArrayRef< StringRef > Features)
If there are multiple +xxx or -xxx features, keep the last one.
Definition: CommonArgs.cpp:328
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition: Types.cpp:322
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:217
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:882
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
Helper structure used to pass information extracted from clang executable name such as i686-linux-and...
Definition: ToolChain.h:65