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