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::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 &&
855 RuntimeLib == ToolChain::RLT_Libgcc) &&
856 !getTriple().isKnownWindowsMSVCEnvironment()) {
857 CmdArgs.push_back("-latomic");
858 }
859 }
860}
861
862void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
863 ArgStringList &CmdArgs) const {
864 auto AddLibSearchPathIfExists = [&](const Twine &Path) {
865 // Linker may emit warnings about non-existing directories
866 if (!llvm::sys::fs::is_directory(Path))
867 return;
868
869 if (getTriple().isKnownWindowsMSVCEnvironment())
870 CmdArgs.push_back(Args.MakeArgString("-libpath:" + Path));
871 else
872 CmdArgs.push_back(Args.MakeArgString("-L" + Path));
873 };
874
875 // Search for flang_rt.* at the same location as clang_rt.* with
876 // LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is
877 // located at the path returned by getRuntimePath() which is already added to
878 // the library search path. This exception is for Apple-Darwin.
879 AddLibSearchPathIfExists(getCompilerRTPath());
880
881 // Fall back to the non-resource directory <driver-path>/../lib. We will
882 // probably have to refine this in the future. In particular, on some
883 // platforms, we may need to use lib64 instead of lib.
884 SmallString<256> DefaultLibPath =
885 llvm::sys::path::parent_path(getDriver().Dir);
886 llvm::sys::path::append(DefaultLibPath, "lib");
887 AddLibSearchPathIfExists(DefaultLibPath);
888}
889
890void ToolChain::addFlangRTLibPath(const ArgList &Args,
891 llvm::opt::ArgStringList &CmdArgs) const {
892 // Link static flang_rt.runtime.a or shared flang_rt.runtime.so.
893 // On AIX, default to static flang-rt.
894 if (Args.hasFlag(options::OPT_static_libflangrt,
895 options::OPT_shared_libflangrt, getTriple().isOSAIX()))
896 CmdArgs.push_back(
897 getCompilerRTArgString(Args, "runtime", ToolChain::FT_Static, true));
898 else {
899 CmdArgs.push_back("-lflang_rt.runtime");
900 addArchSpecificRPath(*this, Args, CmdArgs);
901 }
902}
903
904// Android target triples contain a target version. If we don't have libraries
905// for the exact target version, we should fall back to the next newest version
906// or a versionless path, if any.
907std::optional<std::string>
908ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
909 llvm::Triple TripleWithoutLevel(getTriple());
910 TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
911 const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
912 unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
913 unsigned BestVersion = 0;
914
915 SmallString<32> TripleDir;
916 bool UsingUnversionedDir = false;
917 std::error_code EC;
918 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
919 !EC && LI != LE; LI = LI.increment(EC)) {
920 StringRef DirName = llvm::sys::path::filename(LI->path());
921 StringRef DirNameSuffix = DirName;
922 if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
923 if (DirNameSuffix.empty() && TripleDir.empty()) {
924 TripleDir = DirName;
925 UsingUnversionedDir = true;
926 } else {
927 unsigned Version;
928 if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
929 Version < TripleVersion) {
930 BestVersion = Version;
931 TripleDir = DirName;
932 UsingUnversionedDir = false;
933 }
934 }
935 }
936 }
937
938 if (TripleDir.empty())
939 return {};
940
941 SmallString<128> P(BaseDir);
942 llvm::sys::path::append(P, TripleDir);
943 if (UsingUnversionedDir)
944 D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
945 return std::string(P);
946}
947
949 return (Triple.hasEnvironment()
950 ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
951 llvm::Triple::getOSTypeName(Triple.getOS()),
952 llvm::Triple::getEnvironmentTypeName(
953 Triple.getEnvironment()))
954 : llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
955 llvm::Triple::getOSTypeName(Triple.getOS())));
956}
957
958std::optional<std::string>
959ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
960 auto getPathForTriple =
961 [&](const llvm::Triple &Triple) -> std::optional<std::string> {
962 SmallString<128> P(BaseDir);
963 llvm::sys::path::append(P, Triple.str());
964 if (getVFS().exists(P))
965 return std::string(P);
966 return {};
967 };
968
969 const llvm::Triple &T = getTriple();
970 if (auto Path = getPathForTriple(T))
971 return *Path;
972
973 if (T.isOSAIX()) {
974 llvm::Triple AIXTriple;
975 if (T.getEnvironment() == Triple::UnknownEnvironment) {
976 // Strip unknown environment and the OS version from the triple.
977 AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(),
978 llvm::Triple::getOSTypeName(T.getOS()));
979 } else {
980 // Strip the OS version from the triple.
981 AIXTriple = getTripleWithoutOSVersion();
982 }
983 if (auto Path = getPathForTriple(AIXTriple))
984 return *Path;
985 }
986
987 if (T.isOSzOS() &&
988 (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) {
989 // Build the triple without version information
990 const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion();
991 if (auto Path = getPathForTriple(TripleWithoutVersion))
992 return *Path;
993 }
994
995 // When building with per target runtime directories, various ways of naming
996 // the Arm architecture may have been normalised to simply "arm".
997 // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
998 // Since an armv8l system can use libraries built for earlier architecture
999 // versions assuming endian and float ABI match.
1000 //
1001 // Original triple: armv8l-unknown-linux-gnueabihf
1002 // Runtime triple: arm-unknown-linux-gnueabihf
1003 //
1004 // We do not do this for armeb (big endian) because doing so could make us
1005 // select little endian libraries. In addition, all known armeb triples only
1006 // use the "armeb" architecture name.
1007 //
1008 // M profile Arm is bare metal and we know they will not be using the per
1009 // target runtime directory layout.
1010 if (T.getArch() == Triple::arm && !T.isArmMClass()) {
1011 llvm::Triple ArmTriple = T;
1012 ArmTriple.setArch(Triple::arm);
1013 if (auto Path = getPathForTriple(ArmTriple))
1014 return *Path;
1015 }
1016
1017 if (T.isAndroid())
1018 return getFallbackAndroidTargetPath(BaseDir);
1019
1020 return {};
1021}
1022
1023std::optional<std::string> ToolChain::getDefaultIntrinsicModuleDir() const {
1024 SmallString<128> P(D.ResourceDir);
1025 llvm::sys::path::append(P, "finclude", "flang");
1026 return getTargetSubDirPath(P);
1027}
1028
1029std::optional<std::string> ToolChain::getRuntimePath() const {
1030 SmallString<128> P(D.ResourceDir);
1031 llvm::sys::path::append(P, "lib");
1032 if (auto Ret = getTargetSubDirPath(P))
1033 return Ret;
1034 // Darwin does not use per-target runtime directory.
1035 if (Triple.isOSDarwin())
1036 return {};
1037
1038 llvm::sys::path::append(P, Triple.str());
1039 return std::string(P);
1040}
1041
1042std::optional<std::string> ToolChain::getStdlibPath() const {
1043 SmallString<128> P(D.Dir);
1044 llvm::sys::path::append(P, "..", "lib");
1045 return getTargetSubDirPath(P);
1046}
1047
1048std::optional<std::string> ToolChain::getStdlibIncludePath() const {
1049 SmallString<128> P(D.Dir);
1050 llvm::sys::path::append(P, "..", "include");
1051 return getTargetSubDirPath(P);
1052}
1053
1055 path_list Paths;
1056
1057 auto AddPath = [&](const ArrayRef<StringRef> &SS) {
1058 SmallString<128> Path(getDriver().ResourceDir);
1059 llvm::sys::path::append(Path, "lib");
1060 for (auto &S : SS)
1061 llvm::sys::path::append(Path, S);
1062 Paths.push_back(std::string(Path));
1063 };
1064
1065 AddPath({getTriple().str()});
1066 AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
1067 return Paths;
1068}
1069
1070bool ToolChain::needsProfileRT(const ArgList &Args) {
1071 if (Args.hasArg(options::OPT_noprofilelib))
1072 return false;
1073
1074 return Args.hasArg(options::OPT_fprofile_generate) ||
1075 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
1076 Args.hasArg(options::OPT_fcs_profile_generate) ||
1077 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
1078 Args.hasArg(options::OPT_fprofile_instr_generate) ||
1079 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
1080 Args.hasArg(options::OPT_fcreate_profile) ||
1081 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage) ||
1082 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage_EQ);
1083}
1084
1085bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
1086 return Args.hasArg(options::OPT_coverage) ||
1087 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
1088 false);
1089}
1090
1092 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
1093 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
1094 Action::ActionClass AC = JA.getKind();
1096 !getTriple().isOSAIX())
1097 return getClangAs();
1098 return getTool(AC);
1099}
1100
1101std::string ToolChain::GetFilePath(const char *Name) const {
1102 return D.GetFilePath(Name, *this);
1103}
1104
1105std::string ToolChain::GetProgramPath(const char *Name) const {
1106 return D.GetProgramPath(Name, *this);
1107}
1108
1109std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
1110 if (LinkerIsLLD)
1111 *LinkerIsLLD = false;
1112
1113 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
1114 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
1115 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
1116 StringRef UseLinker = A ? A->getValue() : getDriver().getPreferredLinker();
1117
1118 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
1119 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
1120 // contain a path component separator.
1121 // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
1122 // that --ld-path= points to is lld.
1123 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
1124 std::string Path(A->getValue());
1125 if (!Path.empty()) {
1126 if (llvm::sys::path::parent_path(Path).empty())
1127 Path = GetProgramPath(A->getValue());
1128 if (llvm::sys::fs::can_execute(Path)) {
1129 if (LinkerIsLLD)
1130 *LinkerIsLLD = UseLinker == "lld";
1131 return std::string(Path);
1132 }
1133 }
1134 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1136 }
1137 // If we're passed -fuse-ld= with no argument, or with the argument ld,
1138 // then use whatever the default system linker is.
1139 if (UseLinker.empty() || UseLinker == "ld") {
1140 const char *DefaultLinker = getDefaultLinker();
1141 if (llvm::sys::path::is_absolute(DefaultLinker))
1142 return std::string(DefaultLinker);
1143 else
1144 return GetProgramPath(DefaultLinker);
1145 }
1146
1147 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
1148 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
1149 // to a relative path is surprising. This is more complex due to priorities
1150 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
1151 if (UseLinker.contains('/'))
1152 getDriver().Diag(diag::warn_drv_fuse_ld_path);
1153
1154 if (llvm::sys::path::is_absolute(UseLinker)) {
1155 // If we're passed what looks like an absolute path, don't attempt to
1156 // second-guess that.
1157 if (llvm::sys::fs::can_execute(UseLinker))
1158 return std::string(UseLinker);
1159 } else {
1160 llvm::SmallString<8> LinkerName;
1161 if (Triple.isOSDarwin())
1162 LinkerName.append("ld64.");
1163 else
1164 LinkerName.append("ld.");
1165 LinkerName.append(UseLinker);
1166
1167 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
1168 if (llvm::sys::fs::can_execute(LinkerPath)) {
1169 if (LinkerIsLLD)
1170 *LinkerIsLLD = UseLinker == "lld";
1171 return LinkerPath;
1172 }
1173 }
1174
1175 if (A)
1176 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1177
1179}
1180
1182 // TODO: Add support for static lib archiving on Windows
1183 if (Triple.isOSDarwin())
1184 return GetProgramPath("libtool");
1185 return GetProgramPath("llvm-ar");
1186}
1187
1190
1191 // Flang always runs the preprocessor and has no notion of "preprocessed
1192 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
1193 // them differently.
1194 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
1195 id = types::TY_Fortran;
1196
1197 return id;
1198}
1199
1201 return false;
1202}
1203
1205 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
1206 switch (HostTriple.getArch()) {
1207 // The A32/T32/T16 instruction sets are not separate architectures in this
1208 // context.
1209 case llvm::Triple::arm:
1210 case llvm::Triple::armeb:
1211 case llvm::Triple::thumb:
1212 case llvm::Triple::thumbeb:
1213 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
1214 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
1215 default:
1216 return HostTriple.getArch() != getArch();
1217 }
1218}
1219
1221 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
1222 VersionTuple());
1223}
1224
1225llvm::ExceptionHandling
1226ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
1227 return llvm::ExceptionHandling::None;
1228}
1229
1230bool ToolChain::isThreadModelSupported(const StringRef Model) const {
1231 if (Model == "single") {
1232 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
1233 return Triple.getArch() == llvm::Triple::arm ||
1234 Triple.getArch() == llvm::Triple::armeb ||
1235 Triple.getArch() == llvm::Triple::thumb ||
1236 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
1237 } else if (Model == "posix")
1238 return true;
1239
1240 return false;
1241}
1242
1243std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
1244 types::ID InputType) const {
1245 switch (getTriple().getArch()) {
1246 default:
1247 return getTripleString();
1248
1249 case llvm::Triple::x86_64: {
1250 llvm::Triple Triple = getTriple();
1251 if (!Triple.isOSBinFormatMachO())
1252 return getTripleString();
1253
1254 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1255 // x86_64h goes in the triple. Other -march options just use the
1256 // vanilla triple we already have.
1257 StringRef MArch = A->getValue();
1258 if (MArch == "x86_64h")
1259 Triple.setArchName(MArch);
1260 }
1261 return Triple.getTriple();
1262 }
1263 case llvm::Triple::aarch64: {
1264 llvm::Triple Triple = getTriple();
1265 if (!Triple.isOSBinFormatMachO())
1266 return Triple.getTriple();
1267
1268 if (Triple.isArm64e())
1269 return Triple.getTriple();
1270
1271 // FIXME: older versions of ld64 expect the "arm64" component in the actual
1272 // triple string and query it to determine whether an LTO file can be
1273 // handled. Remove this when we don't care any more.
1274 Triple.setArchName("arm64");
1275 return Triple.getTriple();
1276 }
1277 case llvm::Triple::aarch64_32:
1278 return getTripleString();
1279 case llvm::Triple::amdgcn: {
1280 llvm::Triple Triple = getTriple();
1281 if (Args.getLastArgValue(options::OPT_mcpu_EQ) == "amdgcnspirv")
1282 Triple.setArch(llvm::Triple::ArchType::spirv64);
1283 return Triple.getTriple();
1284 }
1285 case llvm::Triple::arm:
1286 case llvm::Triple::armeb:
1287 case llvm::Triple::thumb:
1288 case llvm::Triple::thumbeb: {
1289 llvm::Triple Triple = getTriple();
1290 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1292 return Triple.getTriple();
1293 }
1294 }
1295}
1296
1297std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1298 types::ID InputType) const {
1299 return ComputeLLVMTriple(Args, InputType);
1300}
1301
1302std::string ToolChain::computeSysRoot() const {
1303 return D.SysRoot;
1304}
1305
1306void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1307 ArgStringList &CC1Args) const {
1308 // Each toolchain should provide the appropriate include flags.
1309}
1310
1312 const ArgList &DriverArgs, ArgStringList &CC1Args,
1313 Action::OffloadKind DeviceOffloadKind) const {}
1314
1316 ArgStringList &CC1ASArgs) const {}
1317
1318void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1319
1320void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1321 llvm::opt::ArgStringList &CmdArgs) const {
1322 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1323 return;
1324
1325 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1326}
1327
1329 const ArgList &Args) const {
1330 if (runtimeLibType)
1331 return *runtimeLibType;
1332
1333 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1334 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1335
1336 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1337 if (LibName == "compiler-rt")
1338 runtimeLibType = ToolChain::RLT_CompilerRT;
1339 else if (LibName == "libgcc")
1340 runtimeLibType = ToolChain::RLT_Libgcc;
1341 else if (LibName == "platform")
1342 runtimeLibType = GetDefaultRuntimeLibType();
1343 else {
1344 if (A)
1345 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1346 << A->getAsString(Args);
1347
1348 runtimeLibType = GetDefaultRuntimeLibType();
1349 }
1350
1351 return *runtimeLibType;
1352}
1353
1355 const ArgList &Args) const {
1356 if (unwindLibType)
1357 return *unwindLibType;
1358
1359 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1360 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1361
1362 if (LibName == "none")
1363 unwindLibType = ToolChain::UNW_None;
1364 else if (LibName == "platform" || LibName == "") {
1366 if (RtLibType == ToolChain::RLT_CompilerRT) {
1367 if (getTriple().isAndroid() || getTriple().isOSAIX())
1368 unwindLibType = ToolChain::UNW_CompilerRT;
1369 else
1370 unwindLibType = ToolChain::UNW_None;
1371 } else if (RtLibType == ToolChain::RLT_Libgcc)
1372 unwindLibType = ToolChain::UNW_Libgcc;
1373 } else if (LibName == "libunwind") {
1374 if (GetRuntimeLibType(Args) == RLT_Libgcc)
1375 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1376 unwindLibType = ToolChain::UNW_CompilerRT;
1377 } else if (LibName == "libgcc")
1378 unwindLibType = ToolChain::UNW_Libgcc;
1379 else {
1380 if (A)
1381 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1382 << A->getAsString(Args);
1383
1384 unwindLibType = GetDefaultUnwindLibType();
1385 }
1386
1387 return *unwindLibType;
1388}
1389
1391 if (cxxStdlibType)
1392 return *cxxStdlibType;
1393
1394 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1395 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1396
1397 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1398 if (LibName == "libc++")
1399 cxxStdlibType = ToolChain::CST_Libcxx;
1400 else if (LibName == "libstdc++")
1401 cxxStdlibType = ToolChain::CST_Libstdcxx;
1402 else if (LibName == "platform")
1403 cxxStdlibType = GetDefaultCXXStdlibType();
1404 else {
1405 if (A)
1406 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1407 << A->getAsString(Args);
1408
1409 cxxStdlibType = GetDefaultCXXStdlibType();
1410 }
1411
1412 return *cxxStdlibType;
1413}
1414
1415/// Utility function to add a system framework directory to CC1 arguments.
1416void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs,
1417 llvm::opt::ArgStringList &CC1Args,
1418 const Twine &Path) {
1419 CC1Args.push_back("-internal-iframework");
1420 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1421}
1422
1423/// Utility function to add a system include directory with extern "C"
1424/// semantics to CC1 arguments.
1425///
1426/// Note that this should be used rarely, and only for directories that
1427/// historically and for legacy reasons are treated as having implicit extern
1428/// "C" semantics. These semantics are *ignored* by and large today, but its
1429/// important to preserve the preprocessor changes resulting from the
1430/// classification.
1431void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1432 ArgStringList &CC1Args,
1433 const Twine &Path) {
1434 CC1Args.push_back("-internal-externc-isystem");
1435 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1436}
1437
1438void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1439 ArgStringList &CC1Args,
1440 const Twine &Path) {
1441 if (llvm::sys::fs::exists(Path))
1442 addExternCSystemInclude(DriverArgs, CC1Args, Path);
1443}
1444
1445/// Utility function to add a system include directory to CC1 arguments.
1446/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1447 ArgStringList &CC1Args,
1448 const Twine &Path) {
1449 CC1Args.push_back("-internal-isystem");
1450 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1451}
1452
1453/// Utility function to add a list of system framework directories to CC1.
1454void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs,
1455 ArgStringList &CC1Args,
1456 ArrayRef<StringRef> Paths) {
1457 for (const auto &Path : Paths) {
1458 CC1Args.push_back("-internal-iframework");
1459 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1460 }
1461}
1462
1463/// Utility function to add a list of system include directories to CC1.
1464void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1465 ArgStringList &CC1Args,
1466 ArrayRef<StringRef> Paths) {
1467 for (const auto &Path : Paths) {
1468 CC1Args.push_back("-internal-isystem");
1469 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1470 }
1471}
1472
1473std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B,
1474 const Twine &C, const Twine &D) {
1476 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1477 return std::string(Result);
1478}
1479
1480std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1481 std::error_code EC;
1482 int MaxVersion = 0;
1483 std::string MaxVersionString;
1484 SmallString<128> Path(IncludePath);
1485 llvm::sys::path::append(Path, "c++");
1486 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1487 !EC && LI != LE; LI = LI.increment(EC)) {
1488 StringRef VersionText = llvm::sys::path::filename(LI->path());
1489 int Version;
1490 if (VersionText[0] == 'v' &&
1491 !VersionText.substr(1).getAsInteger(10, Version)) {
1492 if (Version > MaxVersion) {
1493 MaxVersion = Version;
1494 MaxVersionString = std::string(VersionText);
1495 }
1496 }
1497 }
1498 if (!MaxVersion)
1499 return "";
1500 return MaxVersionString;
1501}
1502
1503void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1504 ArgStringList &CC1Args) const {
1505 // Header search paths should be handled by each of the subclasses.
1506 // Historically, they have not been, and instead have been handled inside of
1507 // the CC1-layer frontend. As the logic is hoisted out, this generic function
1508 // will slowly stop being called.
1509 //
1510 // While it is being called, replicate a bit of a hack to propagate the
1511 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1512 // header search paths with it. Once all systems are overriding this
1513 // function, the CC1 flag and this line can be removed.
1514 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1515}
1516
1518 const llvm::opt::ArgList &DriverArgs,
1519 llvm::opt::ArgStringList &CC1Args) const {
1520 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1521 // This intentionally only looks at -nostdinc++, and not -nostdinc or
1522 // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1523 // setups with non-standard search logic for the C++ headers, while still
1524 // allowing users of the toolchain to bring their own C++ headers. Such a
1525 // toolchain likely also has non-standard search logic for the C headers and
1526 // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1527 // still work in that case and only be suppressed by an explicit -nostdinc++
1528 // in a project using the toolchain.
1529 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1530 for (const auto &P :
1531 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1532 addSystemInclude(DriverArgs, CC1Args, P);
1533}
1534
1535bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1536 return getDriver().CCCIsCXX() &&
1537 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1538 options::OPT_nostdlibxx);
1539}
1540
1541void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1542 ArgStringList &CmdArgs) const {
1543 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1544 "should not have called this");
1546
1547 switch (Type) {
1549 CmdArgs.push_back("-lc++");
1550 if (Args.hasArg(options::OPT_fexperimental_library))
1551 CmdArgs.push_back("-lc++experimental");
1552 break;
1553
1555 CmdArgs.push_back("-lstdc++");
1556 break;
1557 }
1558}
1559
1560void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1561 ArgStringList &CmdArgs) const {
1562 for (const auto &LibPath : getFilePaths())
1563 if(LibPath.length() > 0)
1564 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1565}
1566
1567void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1568 ArgStringList &CmdArgs) const {
1569 CmdArgs.push_back("-lcc_kext");
1570}
1571
1573 std::string &Path) const {
1574 // Don't implicitly link in mode-changing libraries in a shared library, since
1575 // this can have very deleterious effects. See the various links from
1576 // https://github.com/llvm/llvm-project/issues/57589 for more information.
1577 bool Default = !Args.hasArgNoClaim(options::OPT_shared);
1578
1579 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1580 // (to keep the linker options consistent with gcc and clang itself).
1581 if (Default && !isOptimizationLevelFast(Args)) {
1582 // Check if -ffast-math or -funsafe-math.
1583 Arg *A = Args.getLastArg(
1584 options::OPT_ffast_math, options::OPT_fno_fast_math,
1585 options::OPT_funsafe_math_optimizations,
1586 options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ);
1587
1588 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1589 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1590 Default = false;
1591 if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) {
1592 StringRef Model = A->getValue();
1593 if (Model != "fast" && Model != "aggressive")
1594 Default = false;
1595 }
1596 }
1597
1598 // Whatever decision came as a result of the above implicit settings, either
1599 // -mdaz-ftz or -mno-daz-ftz is capable of overriding it.
1600 if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default))
1601 return false;
1602
1603 // If crtfastmath.o exists add it to the arguments.
1604 Path = GetFilePath("crtfastmath.o");
1605 return (Path != "crtfastmath.o"); // Not found.
1606}
1607
1609 ArgStringList &CmdArgs) const {
1610 std::string Path;
1611 if (isFastMathRuntimeAvailable(Args, Path)) {
1612 CmdArgs.push_back(Args.MakeArgString(Path));
1613 return true;
1614 }
1615
1616 return false;
1617}
1618
1620ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1621 return SmallVector<std::string>();
1622}
1623
1625 // Return sanitizers which don't require runtime support and are not
1626 // platform dependent.
1627
1628 SanitizerMask Res =
1629 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1630 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1631 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1632 SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1633 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1634 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
1635 SanitizerKind::AllocToken;
1636 if (getTriple().getArch() == llvm::Triple::x86 ||
1637 getTriple().getArch() == llvm::Triple::x86_64 ||
1638 getTriple().getArch() == llvm::Triple::arm ||
1639 getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() ||
1640 getTriple().isAArch64() || getTriple().isRISCV() ||
1641 getTriple().isLoongArch64())
1642 Res |= SanitizerKind::CFIICall;
1643 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1644 getTriple().isAArch64(64) || getTriple().isRISCV())
1645 Res |= SanitizerKind::ShadowCallStack;
1646 if (getTriple().isAArch64(64))
1647 Res |= SanitizerKind::MemTag;
1648 if (getTriple().isBPF())
1649 Res |= SanitizerKind::KernelAddress;
1650 return Res;
1651}
1652
1653void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1654 ArgStringList &CC1Args) const {}
1655
1656void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1657 ArgStringList &CC1Args) const {}
1658
1659void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
1660 ArgStringList &CC1Args) const {}
1661
1663ToolChain::getDeviceLibs(const ArgList &DriverArgs,
1664 const Action::OffloadKind DeviceOffloadingKind) const {
1665 return {};
1666}
1667
1668void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1669 ArgStringList &CC1Args) const {}
1670
1671static VersionTuple separateMSVCFullVersion(unsigned Version) {
1672 if (Version < 100)
1673 return VersionTuple(Version);
1674
1675 if (Version < 10000)
1676 return VersionTuple(Version / 100, Version % 100);
1677
1678 unsigned Build = 0, Factor = 1;
1679 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1680 Build = Build + (Version % 10) * Factor;
1681 return VersionTuple(Version / 100, Version % 100, Build);
1682}
1683
1684VersionTuple
1686 const llvm::opt::ArgList &Args) const {
1687 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1688 const Arg *MSCompatibilityVersion =
1689 Args.getLastArg(options::OPT_fms_compatibility_version);
1690
1691 if (MSCVersion && MSCompatibilityVersion) {
1692 if (D)
1693 D->Diag(diag::err_drv_argument_not_allowed_with)
1694 << MSCVersion->getAsString(Args)
1695 << MSCompatibilityVersion->getAsString(Args);
1696 return VersionTuple();
1697 }
1698
1699 if (MSCompatibilityVersion) {
1700 VersionTuple MSVT;
1701 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1702 if (D)
1703 D->Diag(diag::err_drv_invalid_value)
1704 << MSCompatibilityVersion->getAsString(Args)
1705 << MSCompatibilityVersion->getValue();
1706 } else {
1707 return MSVT;
1708 }
1709 }
1710
1711 if (MSCVersion) {
1712 unsigned Version = 0;
1713 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1714 if (D)
1715 D->Diag(diag::err_drv_invalid_value)
1716 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1717 } else {
1718 return separateMSVCFullVersion(Version);
1719 }
1720 }
1721
1722 return VersionTuple();
1723}
1724
1725llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1726 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1727 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1728 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1729 const OptTable &Opts = getDriver().getOpts();
1730 bool Modified = false;
1731
1732 // Handle -Xopenmp-target flags
1733 for (auto *A : Args) {
1734 // Exclude flags which may only apply to the host toolchain.
1735 // Do not exclude flags when the host triple (AuxTriple)
1736 // matches the current toolchain triple. If it is not present
1737 // at all, target and host share a toolchain.
1738 if (A->getOption().matches(options::OPT_m_Group)) {
1739 // Pass code object version to device toolchain
1740 // to correctly set metadata in intermediate files.
1741 if (SameTripleAsHost ||
1742 A->getOption().matches(options::OPT_mcode_object_version_EQ))
1743 DAL->append(A);
1744 else
1745 Modified = true;
1746 continue;
1747 }
1748
1749 unsigned Index;
1750 unsigned Prev;
1751 bool XOpenMPTargetNoTriple =
1752 A->getOption().matches(options::OPT_Xopenmp_target);
1753
1754 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1755 llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1756
1757 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1758 if (TT.getTriple() == getTripleString())
1759 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1760 else
1761 continue;
1762 } else if (XOpenMPTargetNoTriple) {
1763 // Passing device args: -Xopenmp-target -opt=val.
1764 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1765 } else {
1766 DAL->append(A);
1767 continue;
1768 }
1769
1770 // Parse the argument to -Xopenmp-target.
1771 Prev = Index;
1772 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1773 if (!XOpenMPTargetArg || Index > Prev + 1) {
1774 if (!A->isClaimed()) {
1775 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1776 << A->getAsString(Args);
1777 }
1778 continue;
1779 }
1780 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1781 Args.getAllArgValues(options::OPT_offload_targets_EQ).size() != 1) {
1782 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1783 continue;
1784 }
1785 XOpenMPTargetArg->setBaseArg(A);
1786 A = XOpenMPTargetArg.release();
1787 AllocatedArgs.push_back(A);
1788 DAL->append(A);
1789 Modified = true;
1790 }
1791
1792 if (Modified)
1793 return DAL;
1794
1795 delete DAL;
1796 return nullptr;
1797}
1798
1799// TODO: Currently argument values separated by space e.g.
1800// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1801// fixed.
1803 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1804 llvm::opt::DerivedArgList *DAL,
1805 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1806 const OptTable &Opts = getDriver().getOpts();
1807 unsigned ValuePos = 1;
1808 if (A->getOption().matches(options::OPT_Xarch_device) ||
1809 A->getOption().matches(options::OPT_Xarch_host))
1810 ValuePos = 0;
1811
1812 const InputArgList &BaseArgs = Args.getBaseArgs();
1813 unsigned Index = BaseArgs.MakeIndex(A->getValue(ValuePos));
1814 unsigned Prev = Index;
1815 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(
1816 Args, Index, llvm::opt::Visibility(options::ClangOption)));
1817
1818 // If the argument parsing failed or more than one argument was
1819 // consumed, the -Xarch_ argument's parameter tried to consume
1820 // extra arguments. Emit an error and ignore.
1821 //
1822 // We also want to disallow any options which would alter the
1823 // driver behavior; that isn't going to work in our model. We
1824 // use options::NoXarchOption to control this.
1825 if (!XarchArg || Index > Prev + 1) {
1826 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1827 << A->getAsString(Args);
1828 return;
1829 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1830 auto &Diags = getDriver().getDiags();
1831 unsigned DiagID =
1833 "invalid Xarch argument: '%0', not all driver "
1834 "options can be forwared via Xarch argument");
1835 Diags.Report(DiagID) << A->getAsString(Args);
1836 return;
1837 }
1838
1839 XarchArg->setBaseArg(A);
1840 A = XarchArg.release();
1841
1842 // Linker input arguments require custom handling. The problem is that we
1843 // have already constructed the phase actions, so we can not treat them as
1844 // "input arguments".
1845 if (A->getOption().hasFlag(options::LinkerInput)) {
1846 // Convert the argument into individual Zlinker_input_args. Need to do this
1847 // manually to avoid memory leaks with the allocated arguments.
1848 for (const char *Value : A->getValues()) {
1849 auto Opt = Opts.getOption(options::OPT_Zlinker_input);
1850 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
1851 auto NewArg =
1852 new Arg(Opt, BaseArgs.MakeArgString(Opt.getPrefix() + Opt.getName()),
1853 Index, BaseArgs.getArgString(Index + 1), A);
1854
1855 DAL->append(NewArg);
1856 if (!AllocatedArgs)
1857 DAL->AddSynthesizedArg(NewArg);
1858 else
1859 AllocatedArgs->push_back(NewArg);
1860 }
1861 }
1862
1863 if (!AllocatedArgs)
1864 DAL->AddSynthesizedArg(A);
1865 else
1866 AllocatedArgs->push_back(A);
1867}
1868
1869llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1870 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1872 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1873 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1874 bool Modified = false;
1875
1876 bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
1877 for (Arg *A : Args) {
1878 bool NeedTrans = false;
1879 bool Skip = false;
1880 if (A->getOption().matches(options::OPT_Xarch_device)) {
1881 NeedTrans = IsDevice;
1882 Skip = !IsDevice;
1883 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1884 NeedTrans = !IsDevice;
1885 Skip = IsDevice;
1886 } else if (A->getOption().matches(options::OPT_Xarch__)) {
1887 NeedTrans = A->getValue() == getArchName() ||
1888 (!BoundArch.empty() && A->getValue() == BoundArch);
1889 Skip = !NeedTrans;
1890 }
1891 if (NeedTrans || Skip)
1892 Modified = true;
1893 if (NeedTrans) {
1894 A->claim();
1895 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1896 }
1897 if (!Skip)
1898 DAL->append(A);
1899 }
1900
1901 if (Modified)
1902 return DAL;
1903
1904 delete DAL;
1905 return nullptr;
1906}
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:905
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:425
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:859
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:169
StringRef getFlangF128MathLibrary() const
Definition Driver.h:469
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:423
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:427
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:155
StringRef getPreferredLinker() const
Definition Driver.h:451
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:840
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:651
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
std::optional< std::string > getDefaultIntrinsicModuleDir() const
Returns the target-specific path for Flang's intrinsic modules in the resource directory if it exists...
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 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:239
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