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
170static void getAArch64MultilibFlags(const Driver &D,
171 const llvm::Triple &Triple,
172 const llvm::opt::ArgList &Args,
173 Multilib::flags_list &Result) {
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
233 processMultilibCustomFlags(Result, Args);
234}
235
236static void getARMMultilibFlags(const Driver &D, const llvm::Triple &Triple,
237 llvm::Reloc::Model RelocationModel,
238 const llvm::opt::ArgList &Args,
239 Multilib::flags_list &Result) {
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
323 processMultilibCustomFlags(Result, Args);
324}
325
326static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple,
327 const llvm::opt::ArgList &Args,
328 Multilib::flags_list &Result) {
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
523 llvm::Triple Triple(Prefix);
524 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Triple, IgnoredError);
525 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
526 IsRegistered};
527}
528
530 // In universal driver terms, the arch name accepted by -arch isn't exactly
531 // the same as the ones that appear in the triple. Roughly speaking, this is
532 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
533 switch (Triple.getArch()) {
534 case llvm::Triple::aarch64: {
535 if (getTriple().isArm64e())
536 return "arm64e";
537 return "arm64";
538 }
539 case llvm::Triple::aarch64_32:
540 return "arm64_32";
541 case llvm::Triple::ppc:
542 return "ppc";
543 case llvm::Triple::ppcle:
544 return "ppcle";
545 case llvm::Triple::ppc64:
546 return "ppc64";
547 case llvm::Triple::ppc64le:
548 return "ppc64le";
549 default:
550 return Triple.getArchName();
551 }
552}
553
554std::string ToolChain::getInputFilename(const InputInfo &Input) const {
555 return Input.getFilename();
556}
557
559ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
561}
562
563Tool *ToolChain::getClang() const {
564 if (!Clang)
565 Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
566 return Clang.get();
567}
568
569Tool *ToolChain::getFlang() const {
570 if (!Flang)
571 Flang.reset(new tools::Flang(*this));
572 return Flang.get();
573}
574
576 return new tools::ClangAs(*this);
577}
578
580 llvm_unreachable("Linking is not supported by this toolchain");
581}
582
584 llvm_unreachable("Creating static lib is not supported by this toolchain");
585}
586
587Tool *ToolChain::getAssemble() const {
588 if (!Assemble)
589 Assemble.reset(buildAssembler());
590 return Assemble.get();
591}
592
593Tool *ToolChain::getClangAs() const {
594 if (!Assemble)
595 Assemble.reset(new tools::ClangAs(*this));
596 return Assemble.get();
597}
598
599Tool *ToolChain::getLink() const {
600 if (!Link)
601 Link.reset(buildLinker());
602 return Link.get();
603}
604
605Tool *ToolChain::getStaticLibTool() const {
606 if (!StaticLibTool)
607 StaticLibTool.reset(buildStaticLibTool());
608 return StaticLibTool.get();
609}
610
611Tool *ToolChain::getIfsMerge() const {
612 if (!IfsMerge)
613 IfsMerge.reset(new tools::ifstool::Merger(*this));
614 return IfsMerge.get();
615}
616
617Tool *ToolChain::getOffloadBundler() const {
618 if (!OffloadBundler)
619 OffloadBundler.reset(new tools::OffloadBundler(*this));
620 return OffloadBundler.get();
621}
622
623Tool *ToolChain::getOffloadPackager() const {
624 if (!OffloadPackager)
625 OffloadPackager.reset(new tools::OffloadPackager(*this));
626 return OffloadPackager.get();
627}
628
629Tool *ToolChain::getLinkerWrapper() const {
630 if (!LinkerWrapper)
631 LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
632 return LinkerWrapper.get();
633}
634
636 switch (AC) {
638 return getAssemble();
639
641 return getIfsMerge();
642
644 return getLink();
645
647 return getStaticLibTool();
648
658 llvm_unreachable("Invalid tool kind.");
659
667 return getClang();
668
671 return getOffloadBundler();
672
674 return getOffloadPackager();
676 return getLinkerWrapper();
677 }
678
679 llvm_unreachable("Invalid tool kind.");
680}
681
682static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
683 const ArgList &Args) {
684 const llvm::Triple &Triple = TC.getTriple();
685 bool IsWindows = Triple.isOSWindows();
686
687 if (TC.isBareMetal())
688 return Triple.getArchName();
689
690 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
691 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
692 ? "armhf"
693 : "arm";
694
695 // For historic reasons, Android library is using i686 instead of i386.
696 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
697 return "i686";
698
699 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
700 return "x32";
701
702 return llvm::Triple::getArchTypeName(TC.getArch());
703}
704
705StringRef ToolChain::getOSLibName() const {
706 if (Triple.isOSDarwin())
707 return "darwin";
708
709 switch (Triple.getOS()) {
710 case llvm::Triple::FreeBSD:
711 return "freebsd";
712 case llvm::Triple::NetBSD:
713 return "netbsd";
714 case llvm::Triple::OpenBSD:
715 return "openbsd";
716 case llvm::Triple::Solaris:
717 return "sunos";
718 case llvm::Triple::AIX:
719 return "aix";
720 default:
721 return getOS();
722 }
723}
724
725std::string ToolChain::getCompilerRTPath() const {
726 SmallString<128> Path(getDriver().ResourceDir);
727 if (isBareMetal()) {
728 llvm::sys::path::append(Path, "lib", getOSLibName());
729 if (!SelectedMultilibs.empty()) {
730 Path += SelectedMultilibs.back().gccSuffix();
731 }
732 } else if (Triple.isOSUnknown()) {
733 llvm::sys::path::append(Path, "lib");
734 } else {
735 llvm::sys::path::append(Path, "lib", getOSLibName());
736 }
737 return std::string(Path);
738}
739
740std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
741 StringRef Component,
742 FileType Type) const {
743 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
744 return llvm::sys::path::filename(CRTAbsolutePath).str();
745}
746
747std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
748 StringRef Component,
749 FileType Type, bool AddArch,
750 bool IsFortran) const {
751 const llvm::Triple &TT = getTriple();
752 bool IsITANMSVCWindows =
753 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
754
755 const char *Prefix =
756 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
757 const char *Suffix;
758 switch (Type) {
760 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
761 break;
763 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
764 break;
766 if (TT.isOSWindows())
767 Suffix = TT.isOSCygMing() ? ".dll.a" : ".lib";
768 else if (TT.isOSAIX())
769 Suffix = ".a";
770 else
771 Suffix = ".so";
772 break;
773 }
774
775 std::string ArchAndEnv;
776 if (AddArch) {
777 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
778 const char *Env = TT.isAndroid() ? "-android" : "";
779 ArchAndEnv = ("-" + Arch + Env).str();
780 }
781
782 std::string LibName = IsFortran ? "flang_rt." : "clang_rt.";
783 return (Prefix + Twine(LibName) + Component + ArchAndEnv + Suffix).str();
784}
785
786std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
787 FileType Type, bool IsFortran) const {
788 // Check for runtime files in the new layout without the architecture first.
789 std::string CRTBasename = buildCompilerRTBasename(
790 Args, Component, Type, /*AddArch=*/false, IsFortran);
791 SmallString<128> Path;
792 for (const auto &LibPath : getLibraryPaths()) {
793 SmallString<128> P(LibPath);
794 llvm::sys::path::append(P, CRTBasename);
795 if (getVFS().exists(P))
796 return std::string(P);
797 if (Path.empty())
798 Path = P;
799 }
800
801 // Check the filename for the old layout if the new one does not exist.
802 CRTBasename = buildCompilerRTBasename(Args, Component, Type,
803 /*AddArch=*/!IsFortran, IsFortran);
805 llvm::sys::path::append(OldPath, CRTBasename);
806 if (Path.empty() || getVFS().exists(OldPath))
807 return std::string(OldPath);
808
809 // If none is found, use a file name from the new layout, which may get
810 // printed in an error message, aiding users in knowing what Clang is
811 // looking for.
812 return std::string(Path);
813}
814
815const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
816 StringRef Component,
818 bool isFortran) const {
819 return Args.MakeArgString(getCompilerRT(Args, Component, Type, isFortran));
820}
821
822/// Add Fortran runtime libs
823void ToolChain::addFortranRuntimeLibs(const ArgList &Args,
824 llvm::opt::ArgStringList &CmdArgs) const {
825 // Link flang_rt.runtime
826 // These are handled earlier on Windows by telling the frontend driver to
827 // add the correct libraries to link against as dependents in the object
828 // file.
829 if (!getTriple().isKnownWindowsMSVCEnvironment()) {
830 StringRef F128LibName = getDriver().getFlangF128MathLibrary();
831 F128LibName.consume_front_insensitive("lib");
832 if (!F128LibName.empty()) {
833 bool AsNeeded = !getTriple().isOSAIX();
834 CmdArgs.push_back("-lflang_rt.quadmath");
835 if (AsNeeded)
836 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/true);
837 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
838 if (AsNeeded)
839 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/false);
840 }
841 addFlangRTLibPath(Args, CmdArgs);
842
843 // needs libexecinfo for backtrace functions
844 if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() ||
845 getTriple().isOSOpenBSD() || getTriple().isOSDragonFly())
846 CmdArgs.push_back("-lexecinfo");
847 }
848
849 // libomp needs libatomic for atomic operations if using libgcc
850 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
851 options::OPT_fno_openmp, false)) {
854 if (OMPRuntime == Driver::OMPRT_OMP && RuntimeLib == ToolChain::RLT_Libgcc)
855 CmdArgs.push_back("-latomic");
856 }
857}
858
859void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
860 ArgStringList &CmdArgs) const {
861 auto AddLibSearchPathIfExists = [&](const Twine &Path) {
862 // Linker may emit warnings about non-existing directories
863 if (!llvm::sys::fs::is_directory(Path))
864 return;
865
866 if (getTriple().isKnownWindowsMSVCEnvironment())
867 CmdArgs.push_back(Args.MakeArgString("-libpath:" + Path));
868 else
869 CmdArgs.push_back(Args.MakeArgString("-L" + Path));
870 };
871
872 // Search for flang_rt.* at the same location as clang_rt.* with
873 // LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is
874 // located at the path returned by getRuntimePath() which is already added to
875 // the library search path. This exception is for Apple-Darwin.
876 AddLibSearchPathIfExists(getCompilerRTPath());
877
878 // Fall back to the non-resource directory <driver-path>/../lib. We will
879 // probably have to refine this in the future. In particular, on some
880 // platforms, we may need to use lib64 instead of lib.
881 SmallString<256> DefaultLibPath =
882 llvm::sys::path::parent_path(getDriver().Dir);
883 llvm::sys::path::append(DefaultLibPath, "lib");
884 AddLibSearchPathIfExists(DefaultLibPath);
885}
886
887void ToolChain::addFlangRTLibPath(const ArgList &Args,
888 llvm::opt::ArgStringList &CmdArgs) const {
889 // Link static flang_rt.runtime.a or shared flang_rt.runtime.so.
890 // On AIX, default to static flang-rt.
891 if (Args.hasFlag(options::OPT_static_libflangrt,
892 options::OPT_shared_libflangrt, getTriple().isOSAIX()))
893 CmdArgs.push_back(
894 getCompilerRTArgString(Args, "runtime", ToolChain::FT_Static, true));
895 else {
896 CmdArgs.push_back("-lflang_rt.runtime");
897 addArchSpecificRPath(*this, Args, CmdArgs);
898 }
899}
900
901// Android target triples contain a target version. If we don't have libraries
902// for the exact target version, we should fall back to the next newest version
903// or a versionless path, if any.
904std::optional<std::string>
905ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
906 llvm::Triple TripleWithoutLevel(getTriple());
907 TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
908 const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
909 unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
910 unsigned BestVersion = 0;
911
912 SmallString<32> TripleDir;
913 bool UsingUnversionedDir = false;
914 std::error_code EC;
915 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
916 !EC && LI != LE; LI = LI.increment(EC)) {
917 StringRef DirName = llvm::sys::path::filename(LI->path());
918 StringRef DirNameSuffix = DirName;
919 if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
920 if (DirNameSuffix.empty() && TripleDir.empty()) {
921 TripleDir = DirName;
922 UsingUnversionedDir = true;
923 } else {
924 unsigned Version;
925 if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
926 Version < TripleVersion) {
927 BestVersion = Version;
928 TripleDir = DirName;
929 UsingUnversionedDir = false;
930 }
931 }
932 }
933 }
934
935 if (TripleDir.empty())
936 return {};
937
938 SmallString<128> P(BaseDir);
939 llvm::sys::path::append(P, TripleDir);
940 if (UsingUnversionedDir)
941 D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
942 return std::string(P);
943}
944
946 return (Triple.hasEnvironment()
947 ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
948 llvm::Triple::getOSTypeName(Triple.getOS()),
949 llvm::Triple::getEnvironmentTypeName(
950 Triple.getEnvironment()))
951 : llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
952 llvm::Triple::getOSTypeName(Triple.getOS())));
953}
954
955std::optional<std::string>
956ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
957 auto getPathForTriple =
958 [&](const llvm::Triple &Triple) -> std::optional<std::string> {
959 SmallString<128> P(BaseDir);
960 llvm::sys::path::append(P, Triple.str());
961 if (getVFS().exists(P))
962 return std::string(P);
963 return {};
964 };
965
966 const llvm::Triple &T = getTriple();
967 if (auto Path = getPathForTriple(T))
968 return *Path;
969
970 if (T.isOSAIX()) {
971 llvm::Triple AIXTriple;
972 if (T.getEnvironment() == Triple::UnknownEnvironment) {
973 // Strip unknown environment and the OS version from the triple.
974 AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(),
975 llvm::Triple::getOSTypeName(T.getOS()));
976 } else {
977 // Strip the OS version from the triple.
978 AIXTriple = getTripleWithoutOSVersion();
979 }
980 if (auto Path = getPathForTriple(AIXTriple))
981 return *Path;
982 }
983
984 if (T.isOSzOS() &&
985 (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) {
986 // Build the triple without version information
987 const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion();
988 if (auto Path = getPathForTriple(TripleWithoutVersion))
989 return *Path;
990 }
991
992 // When building with per target runtime directories, various ways of naming
993 // the Arm architecture may have been normalised to simply "arm".
994 // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
995 // Since an armv8l system can use libraries built for earlier architecture
996 // versions assuming endian and float ABI match.
997 //
998 // Original triple: armv8l-unknown-linux-gnueabihf
999 // Runtime triple: arm-unknown-linux-gnueabihf
1000 //
1001 // We do not do this for armeb (big endian) because doing so could make us
1002 // select little endian libraries. In addition, all known armeb triples only
1003 // use the "armeb" architecture name.
1004 //
1005 // M profile Arm is bare metal and we know they will not be using the per
1006 // target runtime directory layout.
1007 if (T.getArch() == Triple::arm && !T.isArmMClass()) {
1008 llvm::Triple ArmTriple = T;
1009 ArmTriple.setArch(Triple::arm);
1010 if (auto Path = getPathForTriple(ArmTriple))
1011 return *Path;
1012 }
1013
1014 if (T.isAndroid())
1015 return getFallbackAndroidTargetPath(BaseDir);
1016
1017 return {};
1018}
1019
1020std::optional<std::string> ToolChain::getRuntimePath() const {
1021 SmallString<128> P(D.ResourceDir);
1022 llvm::sys::path::append(P, "lib");
1023 if (auto Ret = getTargetSubDirPath(P))
1024 return Ret;
1025 // Darwin does not use per-target runtime directory.
1026 if (Triple.isOSDarwin())
1027 return {};
1028
1029 llvm::sys::path::append(P, Triple.str());
1030 return std::string(P);
1031}
1032
1033std::optional<std::string> ToolChain::getStdlibPath() const {
1034 SmallString<128> P(D.Dir);
1035 llvm::sys::path::append(P, "..", "lib");
1036 return getTargetSubDirPath(P);
1037}
1038
1039std::optional<std::string> ToolChain::getStdlibIncludePath() const {
1040 SmallString<128> P(D.Dir);
1041 llvm::sys::path::append(P, "..", "include");
1042 return getTargetSubDirPath(P);
1043}
1044
1046 path_list Paths;
1047
1048 auto AddPath = [&](const ArrayRef<StringRef> &SS) {
1049 SmallString<128> Path(getDriver().ResourceDir);
1050 llvm::sys::path::append(Path, "lib");
1051 for (auto &S : SS)
1052 llvm::sys::path::append(Path, S);
1053 Paths.push_back(std::string(Path));
1054 };
1055
1056 AddPath({getTriple().str()});
1057 AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
1058 return Paths;
1059}
1060
1061bool ToolChain::needsProfileRT(const ArgList &Args) {
1062 if (Args.hasArg(options::OPT_noprofilelib))
1063 return false;
1064
1065 return Args.hasArg(options::OPT_fprofile_generate) ||
1066 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
1067 Args.hasArg(options::OPT_fcs_profile_generate) ||
1068 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
1069 Args.hasArg(options::OPT_fprofile_instr_generate) ||
1070 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
1071 Args.hasArg(options::OPT_fcreate_profile) ||
1072 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage) ||
1073 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage_EQ);
1074}
1075
1076bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
1077 return Args.hasArg(options::OPT_coverage) ||
1078 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
1079 false);
1080}
1081
1083 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
1084 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
1085 Action::ActionClass AC = JA.getKind();
1087 !getTriple().isOSAIX())
1088 return getClangAs();
1089 return getTool(AC);
1090}
1091
1092std::string ToolChain::GetFilePath(const char *Name) const {
1093 return D.GetFilePath(Name, *this);
1094}
1095
1096std::string ToolChain::GetProgramPath(const char *Name) const {
1097 return D.GetProgramPath(Name, *this);
1098}
1099
1100std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
1101 if (LinkerIsLLD)
1102 *LinkerIsLLD = false;
1103
1104 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
1105 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
1106 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
1107 StringRef UseLinker = A ? A->getValue() : getDriver().getPreferredLinker();
1108
1109 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
1110 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
1111 // contain a path component separator.
1112 // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
1113 // that --ld-path= points to is lld.
1114 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
1115 std::string Path(A->getValue());
1116 if (!Path.empty()) {
1117 if (llvm::sys::path::parent_path(Path).empty())
1118 Path = GetProgramPath(A->getValue());
1119 if (llvm::sys::fs::can_execute(Path)) {
1120 if (LinkerIsLLD)
1121 *LinkerIsLLD = UseLinker == "lld";
1122 return std::string(Path);
1123 }
1124 }
1125 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1127 }
1128 // If we're passed -fuse-ld= with no argument, or with the argument ld,
1129 // then use whatever the default system linker is.
1130 if (UseLinker.empty() || UseLinker == "ld") {
1131 const char *DefaultLinker = getDefaultLinker();
1132 if (llvm::sys::path::is_absolute(DefaultLinker))
1133 return std::string(DefaultLinker);
1134 else
1135 return GetProgramPath(DefaultLinker);
1136 }
1137
1138 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
1139 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
1140 // to a relative path is surprising. This is more complex due to priorities
1141 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
1142 if (UseLinker.contains('/'))
1143 getDriver().Diag(diag::warn_drv_fuse_ld_path);
1144
1145 if (llvm::sys::path::is_absolute(UseLinker)) {
1146 // If we're passed what looks like an absolute path, don't attempt to
1147 // second-guess that.
1148 if (llvm::sys::fs::can_execute(UseLinker))
1149 return std::string(UseLinker);
1150 } else {
1151 llvm::SmallString<8> LinkerName;
1152 if (Triple.isOSDarwin())
1153 LinkerName.append("ld64.");
1154 else
1155 LinkerName.append("ld.");
1156 LinkerName.append(UseLinker);
1157
1158 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
1159 if (llvm::sys::fs::can_execute(LinkerPath)) {
1160 if (LinkerIsLLD)
1161 *LinkerIsLLD = UseLinker == "lld";
1162 return LinkerPath;
1163 }
1164 }
1165
1166 if (A)
1167 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1168
1170}
1171
1173 // TODO: Add support for static lib archiving on Windows
1174 if (Triple.isOSDarwin())
1175 return GetProgramPath("libtool");
1176 return GetProgramPath("llvm-ar");
1177}
1178
1181
1182 // Flang always runs the preprocessor and has no notion of "preprocessed
1183 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
1184 // them differently.
1185 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
1186 id = types::TY_Fortran;
1187
1188 return id;
1189}
1190
1192 return false;
1193}
1194
1196 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
1197 switch (HostTriple.getArch()) {
1198 // The A32/T32/T16 instruction sets are not separate architectures in this
1199 // context.
1200 case llvm::Triple::arm:
1201 case llvm::Triple::armeb:
1202 case llvm::Triple::thumb:
1203 case llvm::Triple::thumbeb:
1204 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
1205 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
1206 default:
1207 return HostTriple.getArch() != getArch();
1208 }
1209}
1210
1212 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
1213 VersionTuple());
1214}
1215
1216llvm::ExceptionHandling
1217ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
1218 return llvm::ExceptionHandling::None;
1219}
1220
1221bool ToolChain::isThreadModelSupported(const StringRef Model) const {
1222 if (Model == "single") {
1223 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
1224 return Triple.getArch() == llvm::Triple::arm ||
1225 Triple.getArch() == llvm::Triple::armeb ||
1226 Triple.getArch() == llvm::Triple::thumb ||
1227 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
1228 } else if (Model == "posix")
1229 return true;
1230
1231 return false;
1232}
1233
1234std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
1235 types::ID InputType) const {
1236 switch (getTriple().getArch()) {
1237 default:
1238 return getTripleString();
1239
1240 case llvm::Triple::x86_64: {
1241 llvm::Triple Triple = getTriple();
1242 if (!Triple.isOSBinFormatMachO())
1243 return getTripleString();
1244
1245 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1246 // x86_64h goes in the triple. Other -march options just use the
1247 // vanilla triple we already have.
1248 StringRef MArch = A->getValue();
1249 if (MArch == "x86_64h")
1250 Triple.setArchName(MArch);
1251 }
1252 return Triple.getTriple();
1253 }
1254 case llvm::Triple::aarch64: {
1255 llvm::Triple Triple = getTriple();
1257 if (!Triple.isOSBinFormatMachO())
1258 return Triple.getTriple();
1259
1260 if (Triple.isArm64e())
1261 return Triple.getTriple();
1262
1263 // FIXME: older versions of ld64 expect the "arm64" component in the actual
1264 // triple string and query it to determine whether an LTO file can be
1265 // handled. Remove this when we don't care any more.
1266 Triple.setArchName("arm64");
1267 return Triple.getTriple();
1268 }
1269 case llvm::Triple::aarch64_32:
1270 return getTripleString();
1271 case llvm::Triple::amdgcn: {
1272 llvm::Triple Triple = getTriple();
1273 if (Args.getLastArgValue(options::OPT_mcpu_EQ) == "amdgcnspirv")
1274 Triple.setArch(llvm::Triple::ArchType::spirv64);
1275 return Triple.getTriple();
1276 }
1277 case llvm::Triple::arm:
1278 case llvm::Triple::armeb:
1279 case llvm::Triple::thumb:
1280 case llvm::Triple::thumbeb: {
1281 llvm::Triple Triple = getTriple();
1282 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1284 return Triple.getTriple();
1285 }
1286 }
1287}
1288
1289std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1290 types::ID InputType) const {
1291 return ComputeLLVMTriple(Args, InputType);
1292}
1293
1294std::string ToolChain::computeSysRoot() const {
1295 return D.SysRoot;
1296}
1297
1298void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1299 ArgStringList &CC1Args) const {
1300 // Each toolchain should provide the appropriate include flags.
1301}
1302
1304 const ArgList &DriverArgs, ArgStringList &CC1Args,
1305 Action::OffloadKind DeviceOffloadKind) const {}
1306
1308 ArgStringList &CC1ASArgs) const {}
1309
1310void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1311
1312void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1313 llvm::opt::ArgStringList &CmdArgs) const {
1314 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1315 return;
1316
1317 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1318}
1319
1321 const ArgList &Args) const {
1322 if (runtimeLibType)
1323 return *runtimeLibType;
1324
1325 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1326 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1327
1328 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1329 if (LibName == "compiler-rt")
1330 runtimeLibType = ToolChain::RLT_CompilerRT;
1331 else if (LibName == "libgcc")
1332 runtimeLibType = ToolChain::RLT_Libgcc;
1333 else if (LibName == "platform")
1334 runtimeLibType = GetDefaultRuntimeLibType();
1335 else {
1336 if (A)
1337 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1338 << A->getAsString(Args);
1339
1340 runtimeLibType = GetDefaultRuntimeLibType();
1341 }
1342
1343 return *runtimeLibType;
1344}
1345
1347 const ArgList &Args) const {
1348 if (unwindLibType)
1349 return *unwindLibType;
1350
1351 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1352 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1353
1354 if (LibName == "none")
1355 unwindLibType = ToolChain::UNW_None;
1356 else if (LibName == "platform" || LibName == "") {
1358 if (RtLibType == ToolChain::RLT_CompilerRT) {
1359 if (getTriple().isAndroid() || getTriple().isOSAIX())
1360 unwindLibType = ToolChain::UNW_CompilerRT;
1361 else
1362 unwindLibType = ToolChain::UNW_None;
1363 } else if (RtLibType == ToolChain::RLT_Libgcc)
1364 unwindLibType = ToolChain::UNW_Libgcc;
1365 } else if (LibName == "libunwind") {
1366 if (GetRuntimeLibType(Args) == RLT_Libgcc)
1367 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1368 unwindLibType = ToolChain::UNW_CompilerRT;
1369 } else if (LibName == "libgcc")
1370 unwindLibType = ToolChain::UNW_Libgcc;
1371 else {
1372 if (A)
1373 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1374 << A->getAsString(Args);
1375
1376 unwindLibType = GetDefaultUnwindLibType();
1377 }
1378
1379 return *unwindLibType;
1380}
1381
1383 if (cxxStdlibType)
1384 return *cxxStdlibType;
1385
1386 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1387 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1388
1389 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1390 if (LibName == "libc++")
1391 cxxStdlibType = ToolChain::CST_Libcxx;
1392 else if (LibName == "libstdc++")
1393 cxxStdlibType = ToolChain::CST_Libstdcxx;
1394 else if (LibName == "platform")
1395 cxxStdlibType = GetDefaultCXXStdlibType();
1396 else {
1397 if (A)
1398 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1399 << A->getAsString(Args);
1400
1401 cxxStdlibType = GetDefaultCXXStdlibType();
1402 }
1403
1404 return *cxxStdlibType;
1405}
1406
1407/// Utility function to add a system framework directory to CC1 arguments.
1408void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs,
1409 llvm::opt::ArgStringList &CC1Args,
1410 const Twine &Path) {
1411 CC1Args.push_back("-internal-iframework");
1412 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1413}
1414
1415/// Utility function to add a system include directory with extern "C"
1416/// semantics to CC1 arguments.
1417///
1418/// Note that this should be used rarely, and only for directories that
1419/// historically and for legacy reasons are treated as having implicit extern
1420/// "C" semantics. These semantics are *ignored* by and large today, but its
1421/// important to preserve the preprocessor changes resulting from the
1422/// classification.
1423void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1424 ArgStringList &CC1Args,
1425 const Twine &Path) {
1426 CC1Args.push_back("-internal-externc-isystem");
1427 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1428}
1429
1430void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1431 ArgStringList &CC1Args,
1432 const Twine &Path) {
1433 if (llvm::sys::fs::exists(Path))
1434 addExternCSystemInclude(DriverArgs, CC1Args, Path);
1435}
1436
1437/// Utility function to add a system include directory to CC1 arguments.
1438/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1439 ArgStringList &CC1Args,
1440 const Twine &Path) {
1441 CC1Args.push_back("-internal-isystem");
1442 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1443}
1444
1445/// Utility function to add a list of system framework directories to CC1.
1446void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs,
1447 ArgStringList &CC1Args,
1448 ArrayRef<StringRef> Paths) {
1449 for (const auto &Path : Paths) {
1450 CC1Args.push_back("-internal-iframework");
1451 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1452 }
1453}
1454
1455/// Utility function to add a list of system include directories to CC1.
1456void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1457 ArgStringList &CC1Args,
1458 ArrayRef<StringRef> Paths) {
1459 for (const auto &Path : Paths) {
1460 CC1Args.push_back("-internal-isystem");
1461 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1462 }
1463}
1464
1465std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B,
1466 const Twine &C, const Twine &D) {
1468 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1469 return std::string(Result);
1470}
1471
1472std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1473 std::error_code EC;
1474 int MaxVersion = 0;
1475 std::string MaxVersionString;
1476 SmallString<128> Path(IncludePath);
1477 llvm::sys::path::append(Path, "c++");
1478 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1479 !EC && LI != LE; LI = LI.increment(EC)) {
1480 StringRef VersionText = llvm::sys::path::filename(LI->path());
1481 int Version;
1482 if (VersionText[0] == 'v' &&
1483 !VersionText.substr(1).getAsInteger(10, Version)) {
1484 if (Version > MaxVersion) {
1485 MaxVersion = Version;
1486 MaxVersionString = std::string(VersionText);
1487 }
1488 }
1489 }
1490 if (!MaxVersion)
1491 return "";
1492 return MaxVersionString;
1493}
1494
1495void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1496 ArgStringList &CC1Args) const {
1497 // Header search paths should be handled by each of the subclasses.
1498 // Historically, they have not been, and instead have been handled inside of
1499 // the CC1-layer frontend. As the logic is hoisted out, this generic function
1500 // will slowly stop being called.
1501 //
1502 // While it is being called, replicate a bit of a hack to propagate the
1503 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1504 // header search paths with it. Once all systems are overriding this
1505 // function, the CC1 flag and this line can be removed.
1506 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1507}
1508
1510 const llvm::opt::ArgList &DriverArgs,
1511 llvm::opt::ArgStringList &CC1Args) const {
1512 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1513 // This intentionally only looks at -nostdinc++, and not -nostdinc or
1514 // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1515 // setups with non-standard search logic for the C++ headers, while still
1516 // allowing users of the toolchain to bring their own C++ headers. Such a
1517 // toolchain likely also has non-standard search logic for the C headers and
1518 // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1519 // still work in that case and only be suppressed by an explicit -nostdinc++
1520 // in a project using the toolchain.
1521 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1522 for (const auto &P :
1523 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1524 addSystemInclude(DriverArgs, CC1Args, P);
1525}
1526
1527bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1528 return getDriver().CCCIsCXX() &&
1529 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1530 options::OPT_nostdlibxx);
1531}
1532
1533void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1534 ArgStringList &CmdArgs) const {
1535 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1536 "should not have called this");
1538
1539 switch (Type) {
1541 CmdArgs.push_back("-lc++");
1542 if (Args.hasArg(options::OPT_fexperimental_library))
1543 CmdArgs.push_back("-lc++experimental");
1544 break;
1545
1547 CmdArgs.push_back("-lstdc++");
1548 break;
1549 }
1550}
1551
1552void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1553 ArgStringList &CmdArgs) const {
1554 for (const auto &LibPath : getFilePaths())
1555 if(LibPath.length() > 0)
1556 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1557}
1558
1559void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1560 ArgStringList &CmdArgs) const {
1561 CmdArgs.push_back("-lcc_kext");
1562}
1563
1565 std::string &Path) const {
1566 // Don't implicitly link in mode-changing libraries in a shared library, since
1567 // this can have very deleterious effects. See the various links from
1568 // https://github.com/llvm/llvm-project/issues/57589 for more information.
1569 bool Default = !Args.hasArgNoClaim(options::OPT_shared);
1570
1571 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1572 // (to keep the linker options consistent with gcc and clang itself).
1573 if (Default && !isOptimizationLevelFast(Args)) {
1574 // Check if -ffast-math or -funsafe-math.
1575 Arg *A = Args.getLastArg(
1576 options::OPT_ffast_math, options::OPT_fno_fast_math,
1577 options::OPT_funsafe_math_optimizations,
1578 options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ);
1579
1580 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1581 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1582 Default = false;
1583 if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) {
1584 StringRef Model = A->getValue();
1585 if (Model != "fast" && Model != "aggressive")
1586 Default = false;
1587 }
1588 }
1589
1590 // Whatever decision came as a result of the above implicit settings, either
1591 // -mdaz-ftz or -mno-daz-ftz is capable of overriding it.
1592 if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default))
1593 return false;
1594
1595 // If crtfastmath.o exists add it to the arguments.
1596 Path = GetFilePath("crtfastmath.o");
1597 return (Path != "crtfastmath.o"); // Not found.
1598}
1599
1601 ArgStringList &CmdArgs) const {
1602 std::string Path;
1603 if (isFastMathRuntimeAvailable(Args, Path)) {
1604 CmdArgs.push_back(Args.MakeArgString(Path));
1605 return true;
1606 }
1607
1608 return false;
1609}
1610
1612ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1613 return SmallVector<std::string>();
1614}
1615
1617 // Return sanitizers which don't require runtime support and are not
1618 // platform dependent.
1619
1620 SanitizerMask Res =
1621 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1622 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1623 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1624 SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1625 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1626 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1627 if (getTriple().getArch() == llvm::Triple::x86 ||
1628 getTriple().getArch() == llvm::Triple::x86_64 ||
1629 getTriple().getArch() == llvm::Triple::arm ||
1630 getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() ||
1631 getTriple().isAArch64() || getTriple().isRISCV() ||
1632 getTriple().isLoongArch64())
1633 Res |= SanitizerKind::CFIICall;
1634 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1635 getTriple().isAArch64(64) || getTriple().isRISCV())
1636 Res |= SanitizerKind::ShadowCallStack;
1637 if (getTriple().isAArch64(64))
1638 Res |= SanitizerKind::MemTag;
1639 return Res;
1640}
1641
1642void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1643 ArgStringList &CC1Args) const {}
1644
1645void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1646 ArgStringList &CC1Args) const {}
1647
1648void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
1649 ArgStringList &CC1Args) const {}
1650
1652ToolChain::getDeviceLibs(const ArgList &DriverArgs,
1653 const Action::OffloadKind DeviceOffloadingKind) const {
1654 return {};
1655}
1656
1657void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1658 ArgStringList &CC1Args) const {}
1659
1660static VersionTuple separateMSVCFullVersion(unsigned Version) {
1661 if (Version < 100)
1662 return VersionTuple(Version);
1663
1664 if (Version < 10000)
1665 return VersionTuple(Version / 100, Version % 100);
1666
1667 unsigned Build = 0, Factor = 1;
1668 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1669 Build = Build + (Version % 10) * Factor;
1670 return VersionTuple(Version / 100, Version % 100, Build);
1671}
1672
1673VersionTuple
1675 const llvm::opt::ArgList &Args) const {
1676 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1677 const Arg *MSCompatibilityVersion =
1678 Args.getLastArg(options::OPT_fms_compatibility_version);
1679
1680 if (MSCVersion && MSCompatibilityVersion) {
1681 if (D)
1682 D->Diag(diag::err_drv_argument_not_allowed_with)
1683 << MSCVersion->getAsString(Args)
1684 << MSCompatibilityVersion->getAsString(Args);
1685 return VersionTuple();
1686 }
1687
1688 if (MSCompatibilityVersion) {
1689 VersionTuple MSVT;
1690 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1691 if (D)
1692 D->Diag(diag::err_drv_invalid_value)
1693 << MSCompatibilityVersion->getAsString(Args)
1694 << MSCompatibilityVersion->getValue();
1695 } else {
1696 return MSVT;
1697 }
1698 }
1699
1700 if (MSCVersion) {
1701 unsigned Version = 0;
1702 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1703 if (D)
1704 D->Diag(diag::err_drv_invalid_value)
1705 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1706 } else {
1707 return separateMSVCFullVersion(Version);
1708 }
1709 }
1710
1711 return VersionTuple();
1712}
1713
1714llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1715 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1716 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1717 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1718 const OptTable &Opts = getDriver().getOpts();
1719 bool Modified = false;
1720
1721 // Handle -Xopenmp-target flags
1722 for (auto *A : Args) {
1723 // Exclude flags which may only apply to the host toolchain.
1724 // Do not exclude flags when the host triple (AuxTriple)
1725 // matches the current toolchain triple. If it is not present
1726 // at all, target and host share a toolchain.
1727 if (A->getOption().matches(options::OPT_m_Group)) {
1728 // Pass code object version to device toolchain
1729 // to correctly set metadata in intermediate files.
1730 if (SameTripleAsHost ||
1731 A->getOption().matches(options::OPT_mcode_object_version_EQ))
1732 DAL->append(A);
1733 else
1734 Modified = true;
1735 continue;
1736 }
1737
1738 unsigned Index;
1739 unsigned Prev;
1740 bool XOpenMPTargetNoTriple =
1741 A->getOption().matches(options::OPT_Xopenmp_target);
1742
1743 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1744 llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1745
1746 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1747 if (TT.getTriple() == getTripleString())
1748 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1749 else
1750 continue;
1751 } else if (XOpenMPTargetNoTriple) {
1752 // Passing device args: -Xopenmp-target -opt=val.
1753 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1754 } else {
1755 DAL->append(A);
1756 continue;
1757 }
1758
1759 // Parse the argument to -Xopenmp-target.
1760 Prev = Index;
1761 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1762 if (!XOpenMPTargetArg || Index > Prev + 1) {
1763 if (!A->isClaimed()) {
1764 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1765 << A->getAsString(Args);
1766 }
1767 continue;
1768 }
1769 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1770 Args.getAllArgValues(options::OPT_offload_targets_EQ).size() != 1) {
1771 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1772 continue;
1773 }
1774 XOpenMPTargetArg->setBaseArg(A);
1775 A = XOpenMPTargetArg.release();
1776 AllocatedArgs.push_back(A);
1777 DAL->append(A);
1778 Modified = true;
1779 }
1780
1781 if (Modified)
1782 return DAL;
1783
1784 delete DAL;
1785 return nullptr;
1786}
1787
1788// TODO: Currently argument values separated by space e.g.
1789// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1790// fixed.
1792 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1793 llvm::opt::DerivedArgList *DAL,
1794 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1795 const OptTable &Opts = getDriver().getOpts();
1796 unsigned ValuePos = 1;
1797 if (A->getOption().matches(options::OPT_Xarch_device) ||
1798 A->getOption().matches(options::OPT_Xarch_host))
1799 ValuePos = 0;
1800
1801 const InputArgList &BaseArgs = Args.getBaseArgs();
1802 unsigned Index = BaseArgs.MakeIndex(A->getValue(ValuePos));
1803 unsigned Prev = Index;
1804 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(
1805 Args, Index, llvm::opt::Visibility(clang::driver::options::ClangOption)));
1806
1807 // If the argument parsing failed or more than one argument was
1808 // consumed, the -Xarch_ argument's parameter tried to consume
1809 // extra arguments. Emit an error and ignore.
1810 //
1811 // We also want to disallow any options which would alter the
1812 // driver behavior; that isn't going to work in our model. We
1813 // use options::NoXarchOption to control this.
1814 if (!XarchArg || Index > Prev + 1) {
1815 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1816 << A->getAsString(Args);
1817 return;
1818 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1819 auto &Diags = getDriver().getDiags();
1820 unsigned DiagID =
1822 "invalid Xarch argument: '%0', not all driver "
1823 "options can be forwared via Xarch argument");
1824 Diags.Report(DiagID) << A->getAsString(Args);
1825 return;
1826 }
1827
1828 XarchArg->setBaseArg(A);
1829 A = XarchArg.release();
1830
1831 // Linker input arguments require custom handling. The problem is that we
1832 // have already constructed the phase actions, so we can not treat them as
1833 // "input arguments".
1834 if (A->getOption().hasFlag(options::LinkerInput)) {
1835 // Convert the argument into individual Zlinker_input_args. Need to do this
1836 // manually to avoid memory leaks with the allocated arguments.
1837 for (const char *Value : A->getValues()) {
1838 auto Opt = Opts.getOption(options::OPT_Zlinker_input);
1839 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
1840 auto NewArg =
1841 new Arg(Opt, BaseArgs.MakeArgString(Opt.getPrefix() + Opt.getName()),
1842 Index, BaseArgs.getArgString(Index + 1), A);
1843
1844 DAL->append(NewArg);
1845 if (!AllocatedArgs)
1846 DAL->AddSynthesizedArg(NewArg);
1847 else
1848 AllocatedArgs->push_back(NewArg);
1849 }
1850 }
1851
1852 if (!AllocatedArgs)
1853 DAL->AddSynthesizedArg(A);
1854 else
1855 AllocatedArgs->push_back(A);
1856}
1857
1858llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1859 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1861 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1862 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1863 bool Modified = false;
1864
1865 bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
1866 for (Arg *A : Args) {
1867 bool NeedTrans = false;
1868 bool Skip = false;
1869 if (A->getOption().matches(options::OPT_Xarch_device)) {
1870 NeedTrans = IsDevice;
1871 Skip = !IsDevice;
1872 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1873 NeedTrans = !IsDevice;
1874 Skip = IsDevice;
1875 } else if (A->getOption().matches(options::OPT_Xarch__)) {
1876 NeedTrans = A->getValue() == getArchName() ||
1877 (!BoundArch.empty() && A->getValue() == BoundArch);
1878 Skip = !NeedTrans;
1879 }
1880 if (NeedTrans || Skip)
1881 Modified = true;
1882 if (NeedTrans) {
1883 A->claim();
1884 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1885 }
1886 if (!Skip)
1887 DAL->append(A);
1888 }
1889
1890 if (Modified)
1891 return DAL;
1892
1893 delete DAL;
1894 return nullptr;
1895}
Defines types useful for describing an Objective-C runtime.
Defines the clang::SanitizerKind enum.
static void processMultilibCustomFlags(Multilib::flags_list &List, const llvm::opt::ArgList &Args)
static const DriverSuffix * parseDriverSuffix(StringRef ProgName, size_t &Pos)
static void getAArch64MultilibFlags(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, Multilib::flags_list &Result)
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...
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, const ArgList &Args)
static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, Multilib::flags_list &Result)
static VersionTuple separateMSVCFullVersion(unsigned Version)
static const DriverSuffix * FindDriverSuffix(StringRef ProgName, size_t &Pos)
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)
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
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
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:432
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:155
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
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,...
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...
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...
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
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.
virtual std::string computeSysRoot() const
Return the sysroot, possibly searching for a default sysroot using target-specific logic.
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
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...
std::optional< std::string > getStdlibPath() const
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
virtual UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const
How detailed should the unwind tables be by default.
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
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.
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.
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...
virtual Tool * buildStaticLibTool() const
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.
std::string GetFilePath(const char *Name) const
virtual void addFortranRuntimeLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Adds Fortran runtime libraries to CmdArgs.
path_list & getFilePaths()
Definition ToolChain.h:295
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
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?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:269
const Driver & getDriver() const
Definition ToolChain.h:253
virtual std::string detectLibcxxVersion(StringRef IncludePath) const
static std::string concat(StringRef Path, const Twine &A, const Twine &B="", const Twine &C="", const Twine &D="")
RTTIMode getRTTIMode() const
Definition ToolChain.h:327
ExceptionsMode getExceptionsMode() const
Definition ToolChain.h:330
llvm::vfs::FileSystem & getVFS() const
Multilib::flags_list getMultilibFlags(const llvm::opt::ArgList &) const
Get flags suitable for multilib selection, based on the provided clang command line arguments.
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
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...
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
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.
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 ...
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...
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
virtual bool useIntegratedBackend() const
Check if the toolchain should use the integrated backend.
std::string GetStaticLibToolPath() const
Returns the linker path for emitting a static library.
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
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...
static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName)
Return any implicit target and/or mode flag for an invocation of the compiler driver as ProgName.
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
const llvm::Triple & getTriple() const
Definition ToolChain.h:255
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const
void addFlangRTLibPath(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Add the path for libflang_rt.runtime.a.
std::optional< std::string > getTargetSubDirPath(StringRef BaseDir) const
Find the target-specific subdirectory for the current target triple under BaseDir,...
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 ...
const XRayArgs getXRayArgs(const llvm::opt::ArgList &) const
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
virtual std::string getCompilerRTPath() const
llvm::Triple getTripleWithoutOSVersion() const
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type, bool AddArch, bool IsFortran=false) const
virtual Expected< SmallVector< std::string > > getSystemGPUArchs(const llvm::opt::ArgList &Args) const
getSystemGPUArchs - Use a tool to detect the user's availible GPUs.
std::string GetProgramPath(const char *Name) const
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.
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
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...
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
virtual void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific SYCL includes.
virtual StringRef getOSLibName() const
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
virtual CXXStdlibType GetDefaultCXXStdlibType() const
Definition ToolChain.h:501
std::optional< std::string > getStdlibIncludePath() const
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
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.
virtual Tool * buildAssembler() const
void setTripleEnvironment(llvm::Triple::EnvironmentType Env)
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.
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
virtual llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, const Action::OffloadKind DeviceOffloadingKind) const
Get paths for device libraries.
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
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.
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.
virtual UnwindLibType GetDefaultUnwindLibType() const
Definition ToolChain.h:505
std::optional< std::string > getRuntimePath() const
virtual Tool * getTool(Action::ActionClass AC) const
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
friend class RegisterEffectiveTriple
Definition ToolChain.h:138
virtual path_list getArchSpecificLibPaths() const
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
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.
virtual bool useRelaxRelocations() const
Check whether to enable x86 relax relocations by default.
StringRef getArchName() const
Definition ToolChain.h:270
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:94
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
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
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.
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.
@ Link
'link' clause, allowed on 'declare' construct.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
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