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