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