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