clang 24.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
12#include "ToolChains/Arch/ARM.h"
14#include "ToolChains/Clang.h"
15#include "ToolChains/Flang.h"
19#include "clang/Config/config.h"
20#include "clang/Driver/Action.h"
22#include "clang/Driver/Driver.h"
24#include "clang/Driver/Job.h"
28#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Config/llvm-config.h"
33#include "llvm/MC/MCTargetOptions.h"
34#include "llvm/MC/TargetRegistry.h"
35#include "llvm/Option/Arg.h"
36#include "llvm/Option/ArgList.h"
37#include "llvm/Option/OptTable.h"
38#include "llvm/Option/Option.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/FileUtilities.h"
42#include "llvm/Support/MemoryBuffer.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/AMDGPUTargetParser.h"
49#include "llvm/TargetParser/RISCVISAInfo.h"
50#include "llvm/TargetParser/TargetParser.h"
51#include "llvm/TargetParser/Triple.h"
52#include <cassert>
53#include <cstddef>
54#include <cstring>
55#include <string>
56
57using namespace clang;
58using namespace driver;
59using namespace tools;
60using namespace llvm;
61using namespace llvm::opt;
62
63static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
64 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
65 options::OPT_fno_rtti, options::OPT_frtti);
66}
67
68static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
69 const llvm::Triple &Triple,
70 const Arg *CachedRTTIArg) {
71 // Explicit rtti/no-rtti args
72 if (CachedRTTIArg) {
73 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
75 else
77 }
78
79 // -frtti is default, except for the PS4/PS5 and DriverKit.
80 bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
82}
83
85 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
86 true)) {
88 }
90}
91
92ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
93 const ArgList &Args)
94 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
95 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)),
96 CachedExceptionsMode(CalculateExceptionsMode(Args)) {
97 assert(T.str() == T.normalize() && "triple should be normalized");
98 auto addIfExists = [this](path_list &List, const std::string &Path) {
99 if (getVFS().exists(Path))
100 List.push_back(Path);
101 };
102
103 if (std::optional<std::string> Path = getRuntimePath())
104 getLibraryPaths().push_back(*Path);
105 if (std::optional<std::string> Path = getStdlibPath())
106 getFilePaths().push_back(*Path);
107 for (const auto &Path : getArchSpecificLibPaths())
108 addIfExists(getFilePaths(), Path);
109}
110
112 if (!SelectedMultilibs.empty())
113 return llvm::reverse(SelectedMultilibs);
114
116 return llvm::reverse(Default);
117}
118
119bool ToolChain::loadMultilibsFromYAML(const llvm::opt::ArgList &Args,
120 const Driver &D, StringRef Fallback) {
121 std::optional<std::string> MultilibPath =
122 findMultilibsYAML(Args, D, Fallback);
123 if (!MultilibPath)
124 return false;
125 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB =
126 D.getVFS().getBufferForFile(*MultilibPath);
127 if (!MB)
128 return false;
129
131 llvm::ErrorOr<MultilibSet> ErrorOrMultilibSet =
132 MultilibSet::parseYaml(*MB.get());
133 if (ErrorOrMultilibSet.getError())
134 return false;
135
136 Multilibs = std::move(ErrorOrMultilibSet.get());
137
138 SmallVector<StringRef> CustomFlagMacroDefines;
139 bool Result =
140 Multilibs.select(D, Flags, SelectedMultilibs, &CustomFlagMacroDefines);
141
142 // Custom flag macro defines are set by processCustomFlags regardless of
143 // whether variant selection succeeds.
144 MultilibMacroDefines.clear();
145 for (StringRef Define : CustomFlagMacroDefines)
146 MultilibMacroDefines.push_back(Define.str());
147
148 if (!Result) {
149 D.Diag(clang::diag::warn_drv_missing_multilib) << llvm::join(Flags, " ");
151 raw_svector_ostream OS(Data);
152 for (const Multilib &M : Multilibs)
153 if (!M.isError())
154 OS << "\n" << llvm::join(M.flags(), " ");
155 D.Diag(clang::diag::note_drv_available_multilibs) << OS.str();
156
157 for (const Multilib &M : SelectedMultilibs)
158 if (M.isError())
159 D.Diag(clang::diag::err_drv_multilib_custom_error)
160 << M.getErrorMessage();
161
162 SelectedMultilibs.clear();
163 return false;
164 }
165
166 // Prepend variant-specific library paths. The YAML's parent directory is
167 // the base for file paths; getRuntimePath() is the base for runtime paths.
168 StringRef YAMLBase = llvm::sys::path::parent_path(*MultilibPath);
169 std::optional<std::string> RuntimeDir = getRuntimePath();
170 size_t FileInsertPos = 0;
171 size_t LibInsertPos = 0;
172 for (const Multilib &M : getOrderedMultilibs()) {
173 if (M.isDefault())
174 continue;
175 SmallString<128> FilePath(YAMLBase);
176 llvm::sys::path::append(FilePath, M.gccSuffix());
177 getFilePaths().insert(getFilePaths().begin() + FileInsertPos,
178 std::string(FilePath));
179 ++FileInsertPos;
180 if (RuntimeDir) {
181 SmallString<128> LibPath(*RuntimeDir);
182 llvm::sys::path::append(LibPath, M.gccSuffix());
183 getLibraryPaths().insert(getLibraryPaths().begin() + LibInsertPos,
184 std::string(LibPath));
185 ++LibInsertPos;
186 }
187 }
188
189 return true;
190}
191
192std::optional<std::string>
193ToolChain::findMultilibsYAML(const llvm::opt::ArgList &Args, const Driver &D,
194 StringRef FallbackDir) {
195 if (Arg *A = Args.getLastArg(options::OPT_multi_lib_config)) {
196 SmallString<128> MultilibPath(A->getValue());
197 if (!D.getVFS().exists(MultilibPath)) {
198 D.Diag(clang::diag::err_drv_no_such_file) << MultilibPath.str();
199 return std::nullopt;
200 }
201 return std::string(MultilibPath);
202 }
203
204 SmallString<128> MultilibPath;
205 if (!FallbackDir.empty())
206 MultilibPath = FallbackDir;
207 else if (std::optional<std::string> StdlibDir = getStdlibPath())
208 MultilibPath = *StdlibDir;
209 else
210 return std::nullopt;
211 llvm::sys::path::append(MultilibPath, "multilib.yaml");
212 if (!D.getVFS().exists(MultilibPath))
213 return std::nullopt;
214 return std::string(MultilibPath);
215}
216
217void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
218 Triple.setEnvironment(Env);
219 if (EffectiveTriple != llvm::Triple())
220 EffectiveTriple.setEnvironment(Env);
221}
222
223ToolChain::~ToolChain() = default;
224
225llvm::vfs::FileSystem &ToolChain::getVFS() const {
226 return getDriver().getVFS();
227}
228
230 return Args.hasFlag(options::OPT_fintegrated_as,
231 options::OPT_fno_integrated_as,
233}
234
236 assert(
239 "(Non-)integrated backend set incorrectly!");
240
241 bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
242 options::OPT_fno_integrated_objemitter,
244
245 // Diagnose when integrated-objemitter options are not supported by this
246 // toolchain.
247 unsigned DiagID;
248 if ((IBackend && !IsIntegratedBackendSupported()) ||
249 (!IBackend && !IsNonIntegratedBackendSupported()))
250 DiagID = clang::diag::err_drv_unsupported_opt_for_target;
251 else
252 DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
253 Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
255 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
256 A = Args.getLastArg(options::OPT_fintegrated_objemitter);
258 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
259
260 return IBackend;
261}
262
264 return ENABLE_X86_RELAX_RELOCATIONS;
265}
266
268 return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
269}
270
272 const llvm::opt::ArgList &Args) {
273 for (const Arg *MultilibFlagArg :
274 Args.filtered(options::OPT_fmultilib_flag)) {
275 List.push_back(MultilibFlagArg->getAsString(Args));
276 MultilibFlagArg->claim();
277 }
278}
279
280static void getAArch64MultilibFlags(const Driver &D,
281 const llvm::Triple &Triple,
282 const llvm::opt::ArgList &Args,
284 std::vector<StringRef> Features;
285 tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features,
286 /*ForAS=*/false,
287 /*ForMultilib=*/true);
288 const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
289 llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
290 UnifiedFeatures.end());
291 std::vector<std::string> MArch;
292 for (const auto &Ext : AArch64::Extensions)
293 if (Ext.UserVisibleName.value())
294 if (FeatureSet.contains(AArch64::StrTab[Ext.PosTargetFeature]))
295 MArch.push_back(AArch64::StrTab[Ext.UserVisibleName].str());
296 for (const auto &Ext : AArch64::Extensions)
297 if (Ext.UserVisibleName.value())
298 if (FeatureSet.contains(AArch64::StrTab[Ext.NegTargetFeature]))
299 MArch.push_back(("no" + AArch64::StrTab[Ext.UserVisibleName]).str());
300 StringRef ArchName;
301 for (const auto &ArchInfo : AArch64::ArchInfos)
302 if (FeatureSet.contains(AArch64::StrTab[ArchInfo.ArchFeature]))
303 ArchName = AArch64::StrTab[ArchInfo.Name];
304 if (!ArchName.empty()) {
305 MArch.insert(MArch.begin(), ("-march=" + ArchName).str());
306 Result.push_back(llvm::join(MArch, "+"));
307 }
308
309 const Arg *BranchProtectionArg =
310 Args.getLastArgNoClaim(options::OPT_mbranch_protection_EQ);
311 if (BranchProtectionArg) {
312 Result.push_back(BranchProtectionArg->getAsString(Args));
313 }
314
315 if (FeatureSet.contains("+strict-align"))
316 Result.push_back("-mno-unaligned-access");
317 else
318 Result.push_back("-munaligned-access");
319
320 if (Arg *Endian = Args.getLastArg(options::OPT_mbig_endian,
321 options::OPT_mlittle_endian)) {
322 if (Endian->getOption().matches(options::OPT_mbig_endian))
323 Result.push_back(Endian->getAsString(Args));
324 }
325
326 const Arg *ABIArg = Args.getLastArgNoClaim(options::OPT_mabi_EQ);
327 if (ABIArg) {
328 Result.push_back(ABIArg->getAsString(Args));
329 }
330
331 if (const Arg *A = Args.getLastArg(options::OPT_O_Group);
332 A && A->getOption().matches(options::OPT_O)) {
333 switch (A->getValue()[0]) {
334 case 's':
335 Result.push_back("-Os");
336 break;
337 case 'z':
338 Result.push_back("-Oz");
339 break;
340 }
341 }
342}
343
344static void getARMMultilibFlags(const Driver &D, const llvm::Triple &Triple,
345 llvm::Reloc::Model RelocationModel,
346 const llvm::opt::ArgList &Args,
348 std::vector<StringRef> Features;
349 llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures(
350 D, Triple, Args, Features, false /*ForAs*/, true /*ForMultilib*/);
351 const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
352 llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
353 UnifiedFeatures.end());
354 std::vector<std::string> MArch;
355 for (const auto &Ext : ARM::ARCHExtNames)
356 if (!Ext.Name.empty())
357 if (FeatureSet.contains(Ext.Feature))
358 MArch.push_back(Ext.Name.str());
359 for (const auto &Ext : ARM::ARCHExtNames)
360 if (!Ext.Name.empty())
361 if (FeatureSet.contains(Ext.NegFeature))
362 MArch.push_back(("no" + Ext.Name).str());
363 MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
364 Result.push_back(llvm::join(MArch, "+"));
365
366 switch (FPUKind) {
367#define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION) \
368 case llvm::ARM::KIND: \
369 Result.push_back("-mfpu=" NAME); \
370 break;
371#include "llvm/TargetParser/ARMTargetParser.def"
372 default:
373 llvm_unreachable("Invalid FPUKind");
374 }
375
376 switch (arm::getARMFloatABI(D, Triple, Args)) {
377 case arm::FloatABI::Soft:
378 Result.push_back("-mfloat-abi=soft");
379 break;
380 case arm::FloatABI::SoftFP:
381 Result.push_back("-mfloat-abi=softfp");
382 break;
383 case arm::FloatABI::Hard:
384 Result.push_back("-mfloat-abi=hard");
385 break;
386 case arm::FloatABI::Invalid:
387 llvm_unreachable("Invalid float ABI");
388 }
389
390 if (RelocationModel == llvm::Reloc::ROPI ||
391 RelocationModel == llvm::Reloc::ROPI_RWPI)
392 Result.push_back("-fropi");
393 else
394 Result.push_back("-fno-ropi");
395
396 if (RelocationModel == llvm::Reloc::RWPI ||
397 RelocationModel == llvm::Reloc::ROPI_RWPI)
398 Result.push_back("-frwpi");
399 else
400 Result.push_back("-fno-rwpi");
401
402 const Arg *BranchProtectionArg =
403 Args.getLastArgNoClaim(options::OPT_mbranch_protection_EQ);
404 if (BranchProtectionArg) {
405 Result.push_back(BranchProtectionArg->getAsString(Args));
406 }
407
408 if (FeatureSet.contains("+strict-align"))
409 Result.push_back("-mno-unaligned-access");
410 else
411 Result.push_back("-munaligned-access");
412
413 if (Arg *Endian = Args.getLastArg(options::OPT_mbig_endian,
414 options::OPT_mlittle_endian)) {
415 if (Endian->getOption().matches(options::OPT_mbig_endian))
416 Result.push_back(Endian->getAsString(Args));
417 }
418
419 if (const Arg *A = Args.getLastArg(options::OPT_O_Group);
420 A && A->getOption().matches(options::OPT_O)) {
421 switch (A->getValue()[0]) {
422 case 's':
423 Result.push_back("-Os");
424 break;
425 case 'z':
426 Result.push_back("-Oz");
427 break;
428 }
429 }
430}
431
432static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple,
433 const llvm::opt::ArgList &Args,
435 bool hasShadowCallStack) {
436 std::string Arch = riscv::getRISCVArch(Args, Triple);
437 // Canonicalize arch for easier matching
438 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
439 Arch, /*EnableExperimentalExtensions*/ true);
440 if (!llvm::errorToBool(ISAInfo.takeError()))
441 Result.push_back("-march=" + (*ISAInfo)->toString());
442
443 Result.push_back(("-mabi=" + riscv::getRISCVABI(Args, Triple)).str());
444
445 if (hasShadowCallStack)
446 Result.push_back("-fsanitize=shadow-call-stack");
447 else
448 Result.push_back("-fno-sanitize=shadow-call-stack");
449
450 const Arg *CFProtectionArg =
451 Args.getLastArgNoClaim(options::OPT_fcf_protection_EQ);
452 StringRef CFProtectionVal =
453 CFProtectionArg ? CFProtectionArg->getValue() : "none";
454 Result.push_back(("-fcf-protection=" + CFProtectionVal).str());
455
456 if (CFProtectionVal == "branch" || CFProtectionVal == "full") {
457 if (const Arg *SchemeArg =
458 Args.getLastArgNoClaim(options::OPT_mcf_branch_label_scheme_EQ))
459 Result.push_back(SchemeArg->getAsString(Args));
460 }
461}
462
464ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
465 using namespace clang::options;
466
467 std::vector<std::string> Result;
468 const llvm::Triple Triple(ComputeEffectiveClangTriple(Args));
469 Result.push_back("--target=" + Triple.str());
470
471 // A difference of relocation model (absolutely addressed data, PIC, Arm
472 // ROPI/RWPI) is likely to change whether a particular multilib variant is
473 // compatible with a given link. Determine the relocation model of the
474 // current link, so as to add appropriate multilib flags.
475 llvm::Reloc::Model RelocationModel;
476 unsigned PICLevel;
477 bool IsPIE;
478 {
479 RegisterEffectiveTriple TripleRAII(*this, Triple);
480 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(*this, Args);
481 }
482
483 switch (Triple.getArch()) {
484 case llvm::Triple::aarch64:
485 case llvm::Triple::aarch64_32:
486 case llvm::Triple::aarch64_be:
487 getAArch64MultilibFlags(D, Triple, Args, Result);
488 break;
489 case llvm::Triple::arm:
490 case llvm::Triple::armeb:
491 case llvm::Triple::thumb:
492 case llvm::Triple::thumbeb:
493 getARMMultilibFlags(D, Triple, RelocationModel, Args, Result);
494 break;
495 case llvm::Triple::riscv32:
496 case llvm::Triple::riscv64:
497 case llvm::Triple::riscv32be:
498 case llvm::Triple::riscv64be:
499 getRISCVMultilibFlags(D, Triple, Args, Result,
500 getSanitizerArgs(Args).hasShadowCallStack());
501 break;
502 default:
503 break;
504 }
505
507
508 if (Arg *CStdLibArg = Args.getLastArg(options::OPT_cstdlib_EQ))
509 Result.push_back(std::string(CStdLibArg->getOption().getPrefixedName()) +
510 CStdLibArg->getValue());
511
512 // Include fno-exceptions and fno-rtti
513 // to improve multilib selection
515 Result.push_back("-fno-rtti");
516 else
517 Result.push_back("-frtti");
518
520 Result.push_back("-fno-exceptions");
521 else
522 Result.push_back("-fexceptions");
523
524 if (RelocationModel == llvm::Reloc::PIC_)
525 Result.push_back(IsPIE ? (PICLevel > 1 ? "-fPIE" : "-fpie")
526 : (PICLevel > 1 ? "-fPIC" : "-fpic"));
527 else
528 Result.push_back("-fno-pic");
529
530 // Sort and remove duplicates.
531 std::sort(Result.begin(), Result.end());
532 Result.erase(llvm::unique(Result), Result.end());
533 return Result;
534}
535
537ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA,
538 Action::OffloadKind DeviceOffloadKind) const {
539 // When -fno-gpu-sanitize is specified for GPU targets, don't emit
540 // diagnostics about unsupported sanitizers for specific GPU arches,
541 // since sanitizers are disabled for the GPU anyway.
542 bool DiagnoseBoundArchErrors =
543 BoundArchSanitizerArgsChecked.insert(BA.ArchName).second;
544 if (BA && getTriple().isGPU() &&
545 !JobArgs.hasFlag(options::OPT_fgpu_sanitize,
546 options::OPT_fno_gpu_sanitize, true)) {
547 DiagnoseBoundArchErrors = false;
548 }
549
550 SanitizerArgs SanArgs(*this, JobArgs,
551 /*DiagnoseErrors=*/!SanitizerArgsChecked,
552 DiagnoseBoundArchErrors, BA, DeviceOffloadKind);
553
554 SanitizerArgsChecked = true;
555 return SanArgs;
556}
557
558const XRayArgs ToolChain::getXRayArgs(const llvm::opt::ArgList &JobArgs) const {
559 XRayArgs XRayArguments(*this, JobArgs);
560 return XRayArguments;
561}
562
563namespace {
564
565struct DriverSuffix {
566 const char *Suffix;
567 const char *ModeFlag;
568};
569
570} // namespace
571
572static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
573 // A list of known driver suffixes. Suffixes are compared against the
574 // program name in order. If there is a match, the frontend type is updated as
575 // necessary by applying the ModeFlag.
576 static const DriverSuffix DriverSuffixes[] = {
577 {"clang", nullptr},
578 {"clang++", "--driver-mode=g++"},
579 {"clang-c++", "--driver-mode=g++"},
580 {"clang-cc", nullptr},
581 {"clang-cpp", "--driver-mode=cpp"},
582 {"clang-g++", "--driver-mode=g++"},
583 {"clang-gcc", nullptr},
584 {"clang-cl", "--driver-mode=cl"},
585 {"cc", nullptr},
586 {"cpp", "--driver-mode=cpp"},
587 {"cl", "--driver-mode=cl"},
588 {"++", "--driver-mode=g++"},
589 {"flang", "--driver-mode=flang"},
590 // For backwards compatibility, we create a symlink for `flang` called
591 // `flang-new`. This will be removed in the future.
592 {"flang-new", "--driver-mode=flang"},
593 {"clang-dxc", "--driver-mode=dxc"},
594 };
595
596 for (const auto &DS : DriverSuffixes) {
597 StringRef Suffix(DS.Suffix);
598 if (ProgName.ends_with(Suffix)) {
599 Pos = ProgName.size() - Suffix.size();
600 return &DS;
601 }
602 }
603 return nullptr;
604}
605
606/// Normalize the program name from argv[0] by stripping the file extension if
607/// present and lower-casing the string on Windows.
608static std::string normalizeProgramName(llvm::StringRef Argv0) {
609 std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
610 if (is_style_windows(llvm::sys::path::Style::native)) {
611 // Transform to lowercase for case insensitive file systems.
612 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
613 ::tolower);
614 }
615 return ProgName;
616}
617
618static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
619 // Try to infer frontend type and default target from the program name by
620 // comparing it against DriverSuffixes in order.
621
622 // If there is a match, the function tries to identify a target as prefix.
623 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
624 // prefix "x86_64-linux". If such a target prefix is found, it may be
625 // added via -target as implicit first argument.
626 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
627
628 if (!DS && ProgName.ends_with(".exe")) {
629 // Try again after stripping the executable suffix:
630 // clang++.exe -> clang++
631 ProgName = ProgName.drop_back(StringRef(".exe").size());
632 DS = FindDriverSuffix(ProgName, Pos);
633 }
634
635 if (!DS) {
636 // Try again after stripping any trailing version number:
637 // clang++3.5 -> clang++
638 ProgName = ProgName.rtrim("0123456789.");
639 DS = FindDriverSuffix(ProgName, Pos);
640 }
641
642 if (!DS) {
643 // Try again after stripping trailing -component.
644 // clang++-tot -> clang++
645 ProgName = ProgName.slice(0, ProgName.rfind('-'));
646 DS = FindDriverSuffix(ProgName, Pos);
647 }
648 return DS;
649}
650
653 std::string ProgName = normalizeProgramName(PN);
654 size_t SuffixPos;
655 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
656 if (!DS)
657 return {};
658 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
659
660 size_t LastComponent = ProgName.rfind('-', SuffixPos);
661 if (LastComponent == std::string::npos)
662 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
663 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
664 SuffixEnd - LastComponent - 1);
665
666 // Infer target from the prefix.
667 StringRef Prefix(ProgName);
668 Prefix = Prefix.slice(0, LastComponent);
669 std::string IgnoredError;
670
671 llvm::Triple Triple(Prefix);
672 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Triple, IgnoredError);
673 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
674 IsRegistered};
675}
676
678 // In universal driver terms, the arch name accepted by -arch isn't exactly
679 // the same as the ones that appear in the triple. Roughly speaking, this is
680 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
681 switch (Triple.getArch()) {
682 case llvm::Triple::aarch64: {
683 if (getTriple().isArm64e())
684 return "arm64e";
685 return "arm64";
686 }
687 case llvm::Triple::aarch64_32:
688 return "arm64_32";
689 case llvm::Triple::ppc:
690 return "ppc";
691 case llvm::Triple::ppcle:
692 return "ppcle";
693 case llvm::Triple::ppc64:
694 return "ppc64";
695 case llvm::Triple::ppc64le:
696 return "ppc64le";
697 default:
698 return Triple.getArchName();
699 }
700}
701
702std::string ToolChain::getInputFilename(const InputInfo &Input) const {
703 return Input.getFilename();
704}
705
707ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
709}
710
711Tool *ToolChain::getClang() const {
712 if (!Clang)
713 Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
714 return Clang.get();
715}
716
717Tool *ToolChain::getFlang() const {
718 if (!Flang)
719 Flang.reset(new tools::Flang(*this));
720 return Flang.get();
721}
722
724 return new tools::ClangAs(*this);
725}
726
728 llvm_unreachable("Linking is not supported by this toolchain");
729}
730
732 llvm_unreachable("Creating static lib is not supported by this toolchain");
733}
734
735Tool *ToolChain::getAssemble() const {
736 if (!Assemble)
737 Assemble.reset(buildAssembler());
738 return Assemble.get();
739}
740
741Tool *ToolChain::getClangAs() const {
742 if (!Assemble)
743 Assemble.reset(new tools::ClangAs(*this));
744 return Assemble.get();
745}
746
747Tool *ToolChain::getLink() const {
748 if (!Link)
749 Link.reset(buildLinker());
750 return Link.get();
751}
752
753Tool *ToolChain::getStaticLibTool() const {
754 if (!StaticLibTool)
755 StaticLibTool.reset(buildStaticLibTool());
756 return StaticLibTool.get();
757}
758
759Tool *ToolChain::getIfsMerge() const {
760 if (!IfsMerge)
761 IfsMerge.reset(new tools::ifstool::Merger(*this));
762 return IfsMerge.get();
763}
764
765Tool *ToolChain::getOffloadBundler() const {
766 if (!OffloadBundler)
767 OffloadBundler.reset(new tools::OffloadBundler(*this));
768 return OffloadBundler.get();
769}
770
771Tool *ToolChain::getOffloadPackager() const {
772 if (!OffloadPackager)
773 OffloadPackager.reset(new tools::OffloadPackager(*this));
774 return OffloadPackager.get();
775}
776
777Tool *ToolChain::getLinkerWrapper() const {
778 if (!LinkerWrapper)
779 LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
780 return LinkerWrapper.get();
781}
782
784 switch (AC) {
786 return getAssemble();
787
789 return getIfsMerge();
790
792 return getLink();
793
795 return getStaticLibTool();
796
806 llvm_unreachable("Invalid tool kind.");
807
815 return getClang();
816
819 return getOffloadBundler();
820
822 return getOffloadPackager();
824 return getLinkerWrapper();
825 }
826
827 llvm_unreachable("Invalid tool kind.");
828}
829
830static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
831 const ArgList &Args) {
832 const llvm::Triple &Triple = TC.getTriple();
833 bool IsWindows = Triple.isOSWindows();
834
835 if (TC.isBareMetal())
836 return Triple.getArchName();
837
838 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
839 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
840 ? "armhf"
841 : "arm";
842
843 // For historic reasons, Android library is using i686 instead of i386.
844 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
845 return "i686";
846
847 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
848 return "x32";
849
850 return llvm::Triple::getArchTypeName(TC.getArch());
851}
852
853StringRef ToolChain::getOSLibName() const {
854 if (Triple.isOSDarwin())
855 return "darwin";
856 if (Triple.isWindowsCygwinEnvironment())
857 return "cygwin";
858
859 switch (Triple.getOS()) {
860 case llvm::Triple::FreeBSD:
861 return "freebsd";
862 case llvm::Triple::NetBSD:
863 return "netbsd";
864 case llvm::Triple::OpenBSD:
865 return "openbsd";
866 case llvm::Triple::Solaris:
867 return "sunos";
868 case llvm::Triple::AIX:
869 return "aix";
870 case llvm::Triple::Serenity:
871 return "serenity";
872 default:
873 return getOS();
874 }
875}
876
877std::string ToolChain::getCompilerRTPath() const {
878 SmallString<128> Path(getDriver().ResourceDir);
879 if (isBareMetal()) {
880 llvm::sys::path::append(Path, "lib", getOSLibName());
881 if (!SelectedMultilibs.empty()) {
882 Path += SelectedMultilibs.back().gccSuffix();
883 }
884 } else if (Triple.isOSUnknown()) {
885 llvm::sys::path::append(Path, "lib");
886 } else {
887 llvm::sys::path::append(Path, "lib", getOSLibName());
888 }
889 return std::string(Path);
890}
891
892std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
893 StringRef Component,
894 FileType Type) const {
895 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
896 return llvm::sys::path::filename(CRTAbsolutePath).str();
897}
898
899std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
900 StringRef Component,
901 FileType Type, bool AddArch,
902 bool IsFortran) const {
903 const llvm::Triple &TT = getTriple();
904 bool IsITANMSVCWindows =
905 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
906
907 const char *Prefix =
908 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
909 const char *Suffix;
910 switch (Type) {
912 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
913 break;
915 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
916 break;
918 if (TT.isOSWindows())
919 Suffix = TT.isOSCygMing() ? ".dll.a" : ".lib";
920 else if (TT.isOSAIX())
921 Suffix = ".a";
922 else
923 Suffix = ".so";
924 break;
925 }
926
927 std::string ArchAndEnv;
928 if (AddArch) {
929 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
930 const char *Env = TT.isAndroid() ? "-android" : "";
931 ArchAndEnv = ("-" + Arch + Env).str();
932 }
933
934 std::string LibName = IsFortran ? "flang_rt." : "clang_rt.";
935 return (Prefix + Twine(LibName) + Component + ArchAndEnv + Suffix).str();
936}
937
938std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
939 FileType Type, bool IsFortran) const {
940 // Check for runtime files in the new layout without the architecture first.
941 std::string CRTBasename = buildCompilerRTBasename(
942 Args, Component, Type, /*AddArch=*/false, IsFortran);
943 SmallString<128> Path;
944 for (const auto &LibPath : getLibraryPaths()) {
945 SmallString<128> P(LibPath);
946 llvm::sys::path::append(P, CRTBasename);
947 if (getVFS().exists(P))
948 return std::string(P);
949 if (Path.empty())
950 Path = P;
951 }
952
953 // Check the filename for the old layout if the new one does not exist.
954 CRTBasename = buildCompilerRTBasename(Args, Component, Type,
955 /*AddArch=*/!IsFortran, IsFortran);
957 llvm::sys::path::append(OldPath, CRTBasename);
958 if (Path.empty() || getVFS().exists(OldPath))
959 return std::string(OldPath);
960
961 // If none is found, use a file name from the new layout, which may get
962 // printed in an error message, aiding users in knowing what Clang is
963 // looking for.
964 return std::string(Path);
965}
966
967const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
968 StringRef Component,
970 bool isFortran) const {
971 return Args.MakeArgString(getCompilerRT(Args, Component, Type, isFortran));
972}
973
974/// Add Fortran runtime libs
975void ToolChain::addFortranRuntimeLibs(const ArgList &Args,
976 llvm::opt::ArgStringList &CmdArgs) const {
977 // Link flang_rt.runtime
978 // These are handled earlier on Windows by telling the frontend driver to
979 // add the correct libraries to link against as dependents in the object
980 // file.
981 if (!getTriple().isKnownWindowsMSVCEnvironment()) {
982 StringRef F128LibName = getDriver().getFlangF128MathLibrary();
983 F128LibName.consume_front_insensitive("lib");
984 if (!F128LibName.empty()) {
985 bool AsNeeded = !getTriple().isOSAIX();
986 CmdArgs.push_back("-lflang_rt.quadmath");
987 if (AsNeeded)
988 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/true);
989 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
990 if (AsNeeded)
991 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/false);
992 }
993 addFlangRTLibPath(Args, CmdArgs);
994
995 // needs libexecinfo for backtrace functions
996 if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() ||
997 getTriple().isOSOpenBSD() || getTriple().isOSDragonFly())
998 CmdArgs.push_back("-lexecinfo");
999 }
1000
1001 // libomp needs libatomic for atomic operations if using libgcc
1002 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1003 options::OPT_fno_openmp, false)) {
1006 if ((OMPRuntime == Driver::OMPRT_OMP &&
1007 RuntimeLib == ToolChain::RLT_Libgcc) &&
1008 !getTriple().isKnownWindowsMSVCEnvironment()) {
1009 if (getTriple().isOSAIX())
1010 CmdArgs.push_back("-lcompiler_rt");
1011 else
1012 CmdArgs.push_back("-latomic");
1013 }
1014 }
1015}
1016
1017void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
1018 ArgStringList &CmdArgs) const {
1019 auto AddLibSearchPathIfExists = [&](const Twine &Path) {
1020 // Linker may emit warnings about non-existing directories
1021 if (!llvm::sys::fs::is_directory(Path))
1022 return;
1023
1024 if (getTriple().isKnownWindowsMSVCEnvironment())
1025 CmdArgs.push_back(Args.MakeArgString("-libpath:" + Path));
1026 else
1027 CmdArgs.push_back(Args.MakeArgString("-L" + Path));
1028 };
1029
1030 // Search for flang_rt.* at the same location as clang_rt.* with
1031 // LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is
1032 // located at the path returned by getRuntimePath() which is already added to
1033 // the library search path. This exception is for Apple-Darwin.
1034 AddLibSearchPathIfExists(getCompilerRTPath());
1035
1036 // Fall back to the non-resource directory <driver-path>/../lib. We will
1037 // probably have to refine this in the future. In particular, on some
1038 // platforms, we may need to use lib64 instead of lib.
1039 SmallString<256> DefaultLibPath =
1040 llvm::sys::path::parent_path(getDriver().Dir);
1041 llvm::sys::path::append(DefaultLibPath, "lib");
1042 AddLibSearchPathIfExists(DefaultLibPath);
1043}
1044
1045void ToolChain::addFlangRTLibPath(const ArgList &Args,
1046 llvm::opt::ArgStringList &CmdArgs) const {
1047 // Link static flang_rt.runtime.a or shared flang_rt.runtime.so.
1048 // On AIX, default to static flang-rt.
1049 if (Args.hasFlag(options::OPT_static_libflangrt,
1050 options::OPT_shared_libflangrt, getTriple().isOSAIX()))
1051 CmdArgs.push_back(
1052 getCompilerRTArgString(Args, "runtime", ToolChain::FT_Static, true));
1053 else {
1054 CmdArgs.push_back("-lflang_rt.runtime");
1055 addArchSpecificRPath(*this, Args, CmdArgs);
1056 }
1057}
1058
1059// Android target triples contain a target version. If we don't have libraries
1060// for the exact target version, we should fall back to the next newest version
1061// or a versionless path, if any.
1062std::optional<std::string>
1063ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
1064 llvm::Triple TripleWithoutLevel(getTriple());
1065 TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
1066 const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
1067 unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
1068 unsigned BestVersion = 0;
1069
1070 SmallString<32> TripleDir;
1071 bool UsingUnversionedDir = false;
1072 std::error_code EC;
1073 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
1074 !EC && LI != LE; LI = LI.increment(EC)) {
1075 StringRef DirName = llvm::sys::path::filename(LI->path());
1076 StringRef DirNameSuffix = DirName;
1077 if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
1078 if (DirNameSuffix.empty() && TripleDir.empty()) {
1079 TripleDir = DirName;
1080 UsingUnversionedDir = true;
1081 } else {
1082 unsigned Version;
1083 if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
1084 Version < TripleVersion) {
1085 BestVersion = Version;
1086 TripleDir = DirName;
1087 UsingUnversionedDir = false;
1088 }
1089 }
1090 }
1091 }
1092
1093 if (TripleDir.empty())
1094 return {};
1095
1096 SmallString<128> P(BaseDir);
1097 llvm::sys::path::append(P, TripleDir);
1098 if (UsingUnversionedDir)
1099 D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
1100 return std::string(P);
1101}
1102
1104 return (Triple.hasEnvironment()
1105 ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
1106 llvm::Triple::getOSTypeName(Triple.getOS()),
1107 llvm::Triple::getEnvironmentTypeName(
1108 Triple.getEnvironment()))
1109 : llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
1110 llvm::Triple::getOSTypeName(Triple.getOS())));
1111}
1112
1113std::optional<std::string>
1114ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
1115 auto getPathForTriple =
1116 [&](const llvm::Triple &Triple) -> std::optional<std::string> {
1117 SmallString<128> P(BaseDir);
1118 llvm::sys::path::append(P, Triple.str());
1119 if (getVFS().exists(P))
1120 return std::string(P);
1121 return {};
1122 };
1123
1124 const llvm::Triple &T = getTriple();
1125 if (auto Path = getPathForTriple(T))
1126 return *Path;
1127
1128 if (T.isAMDGCN()) {
1129 // Clear the subarch as a fallback.
1130 // TODO: Remove this when libc and compiler-rt builds are migrated.
1131 llvm::Triple AMDGPUTriple = T;
1132 AMDGPUTriple.setArch(Triple::amdgpu);
1133 if (auto Path = getPathForTriple(AMDGPUTriple))
1134 return *Path;
1135
1136 // Try legacy architecture name.
1137 AMDGPUTriple.setArchName("amdgcn");
1138 if (auto Path = getPathForTriple(AMDGPUTriple))
1139 return *Path;
1140 }
1141
1142 if (T.isOSAIX()) {
1143 llvm::Triple AIXTriple;
1144 if (T.getEnvironment() == Triple::UnknownEnvironment) {
1145 // Strip unknown environment and the OS version from the triple.
1146 AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(),
1147 llvm::Triple::getOSTypeName(T.getOS()));
1148 } else {
1149 // Strip the OS version from the triple.
1150 AIXTriple = getTripleWithoutOSVersion();
1151 }
1152 if (auto Path = getPathForTriple(AIXTriple))
1153 return *Path;
1154 }
1155
1156 if (T.isOSzOS() &&
1157 (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) {
1158 // Build the triple without version information
1159 const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion();
1160 if (auto Path = getPathForTriple(TripleWithoutVersion))
1161 return *Path;
1162 }
1163
1164 // When building with per target runtime directories, various ways of naming
1165 // the Arm architecture may have been normalised to simply "arm".
1166 // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
1167 // Since an armv8l system can use libraries built for earlier architecture
1168 // versions assuming endian and float ABI match.
1169 //
1170 // Original triple: armv8l-unknown-linux-gnueabihf
1171 // Runtime triple: arm-unknown-linux-gnueabihf
1172 //
1173 // We do not do this for armeb (big endian) because doing so could make us
1174 // select little endian libraries. In addition, all known armeb triples only
1175 // use the "armeb" architecture name.
1176 //
1177 // M profile Arm is bare metal and we know they will not be using the per
1178 // target runtime directory layout.
1179 if (T.getArch() == Triple::arm && !T.isArmMClass()) {
1180 llvm::Triple ArmTriple = T;
1181 ArmTriple.setArch(Triple::arm);
1182 if (auto Path = getPathForTriple(ArmTriple))
1183 return *Path;
1184 }
1185
1186 if (T.isAndroid())
1187 return getFallbackAndroidTargetPath(BaseDir);
1188
1189 return {};
1190}
1191
1192std::optional<std::string> ToolChain::getDefaultIntrinsicModuleDir() const {
1193 SmallString<128> P(D.ResourceDir);
1194 llvm::sys::path::append(P, "finclude", "flang");
1195 return getTargetSubDirPath(P);
1196}
1197
1198std::optional<std::string> ToolChain::getRuntimePath() const {
1199 SmallString<128> P(D.ResourceDir);
1200 llvm::sys::path::append(P, "lib");
1201 if (auto Ret = getTargetSubDirPath(P))
1202 return Ret;
1203 // Darwin does not use per-target runtime directory.
1204 if (Triple.isOSDarwin())
1205 return {};
1206
1207 llvm::sys::path::append(P, Triple.str());
1208 return std::string(P);
1209}
1210
1211std::optional<std::string> ToolChain::getStdlibPath() const {
1212 SmallString<128> P(D.Dir);
1213 llvm::sys::path::append(P, "..", "lib");
1214 return getTargetSubDirPath(P);
1215}
1216
1217std::optional<std::string> ToolChain::getStdlibIncludePath() const {
1218 SmallString<128> P(D.Dir);
1219 llvm::sys::path::append(P, "..", "include");
1220 return getTargetSubDirPath(P);
1221}
1222
1224 path_list Paths;
1225
1226 auto AddPath = [&](const ArrayRef<StringRef> &SS) {
1227 SmallString<128> Path(getDriver().ResourceDir);
1228 llvm::sys::path::append(Path, "lib");
1229 for (auto &S : SS)
1230 llvm::sys::path::append(Path, S);
1231 Paths.push_back(std::string(Path));
1232 };
1233
1234 AddPath({getTriple().str()});
1235
1236 // For AMDGPU, fall back to the subarch-stripped triple path, trying both the
1237 // canonical "amdgpu" name and the legacy "amdgcn" name.
1238 //
1239 // TODO: Also try major subarch?
1240 // TODO: Remove this when libc and compiler-rt builds are migrated.
1241 if (getTriple().isAMDGCN()) {
1242 llvm::Triple Canon(getTriple());
1243 for (StringRef ArchName : {"amdgpu", "amdgcn"}) {
1244 if (ArchName == getTriple().getArchName())
1245 continue;
1246 Canon.setArchName(ArchName);
1247 AddPath({Canon.str()});
1248 }
1249 }
1250
1251 AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
1252 return Paths;
1253}
1254
1255bool ToolChain::needsProfileRT(const ArgList &Args) {
1256 if (Args.hasArg(options::OPT_noprofilelib))
1257 return false;
1258
1259 return Args.hasArg(options::OPT_fprofile_generate) ||
1260 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
1261 Args.hasArg(options::OPT_fcs_profile_generate) ||
1262 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
1263 Args.hasArg(options::OPT_fprofile_instr_generate) ||
1264 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
1265 Args.hasArg(options::OPT_fcreate_profile) ||
1266 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage) ||
1267 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage_EQ);
1268}
1269
1270bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
1271 return Args.hasArg(options::OPT_coverage) ||
1272 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
1273 false);
1274}
1275
1277 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
1278 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
1279 Action::ActionClass AC = JA.getKind();
1281 !getTriple().isOSAIX())
1282 return getClangAs();
1283 return getTool(AC);
1284}
1285
1286std::string ToolChain::GetFilePath(const char *Name) const {
1287 return D.GetFilePath(Name, *this);
1288}
1289
1290std::string ToolChain::GetProgramPath(const char *Name) const {
1291 return D.GetProgramPath(Name, *this);
1292}
1293
1294std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
1295 if (LinkerIsLLD)
1296 *LinkerIsLLD = false;
1297
1298 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
1299 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
1300 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
1301 StringRef UseLinker = A ? A->getValue() : getDriver().getPreferredLinker();
1302
1303 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
1304 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
1305 // contain a path component separator.
1306 // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
1307 // that --ld-path= points to is lld.
1308 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
1309 std::string Path(A->getValue());
1310 if (!Path.empty()) {
1311 if (llvm::sys::path::parent_path(Path).empty())
1312 Path = GetProgramPath(A->getValue());
1313 if (llvm::sys::fs::can_execute(Path)) {
1314 if (LinkerIsLLD)
1315 *LinkerIsLLD = UseLinker == "lld";
1316 return std::string(Path);
1317 }
1318 }
1319 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1321 }
1322 // If we're passed -fuse-ld= with no argument, or with the argument ld,
1323 // then use whatever the default system linker is.
1324 if (UseLinker.empty() || UseLinker == "ld") {
1325 const char *DefaultLinker = getDefaultLinker();
1326 if (llvm::sys::path::is_absolute(DefaultLinker))
1327 return std::string(DefaultLinker);
1328 else
1329 return GetProgramPath(DefaultLinker);
1330 }
1331
1332 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
1333 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
1334 // to a relative path is surprising. This is more complex due to priorities
1335 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
1336 if (UseLinker.contains('/'))
1337 getDriver().Diag(diag::warn_drv_fuse_ld_path);
1338
1339 if (llvm::sys::path::is_absolute(UseLinker)) {
1340 // If we're passed what looks like an absolute path, don't attempt to
1341 // second-guess that.
1342 if (llvm::sys::fs::can_execute(UseLinker))
1343 return std::string(UseLinker);
1344 } else {
1345 llvm::SmallString<8> LinkerName;
1346 if (Triple.isOSDarwin())
1347 LinkerName.append("ld64.");
1348 else
1349 LinkerName.append("ld.");
1350 LinkerName.append(UseLinker);
1351
1352 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
1353 if (llvm::sys::fs::can_execute(LinkerPath)) {
1354 if (LinkerIsLLD)
1355 *LinkerIsLLD = UseLinker == "lld";
1356 return LinkerPath;
1357 }
1358 }
1359
1360 if (A)
1361 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1362
1364}
1365
1367 // TODO: Add support for static lib archiving on Windows
1368 if (Triple.isOSDarwin())
1369 return GetProgramPath("libtool");
1370 return GetProgramPath("llvm-ar");
1371}
1372
1375
1376 // Flang always runs the preprocessor and has no notion of "preprocessed
1377 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
1378 // them differently.
1379 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
1380 id = types::TY_Fortran;
1381
1382 return id;
1383}
1384
1386 return false;
1387}
1388
1390
1391bool ToolChain::isUsingLTO(const llvm::opt::ArgList &Args,
1392 Action::OffloadKind Kind) const {
1393 return getLTOMode(Args, Kind) != LTOK_None;
1394}
1395
1396static LTOKind parseLTOMode(const llvm::opt::ArgList &Args,
1397 llvm::opt::OptSpecifier OptEq,
1398 llvm::opt::OptSpecifier OptNeg) {
1399 if (!Args.hasFlag(OptEq, OptNeg, false))
1400 return LTOK_None;
1401
1402 const Arg *A = Args.getLastArg(OptEq);
1403 StringRef LTOName = A->getValue();
1404
1405 return llvm::StringSwitch<LTOKind>(LTOName)
1406 .Case("full", LTOK_Full)
1407 .Case("thin", LTOK_Thin)
1408 .Case("none", LTOK_None)
1409 .Default(LTOK_Unknown);
1410}
1411
1412LTOKind ToolChain::getLTOMode(const llvm::opt::ArgList &Args,
1413 Action::OffloadKind Kind) const {
1414 bool IsOffload = Kind != Action::OFK_None;
1415 auto OptEq = IsOffload ? options::OPT_foffload_lto_EQ : options::OPT_flto_EQ;
1416 auto OptNeg = IsOffload ? options::OPT_fno_offload_lto : options::OPT_fno_lto;
1417
1418 // -fopenmp-target-jit implies -foffload-lto=full for device compilations,
1419 // overriding any explicit -fno-offload-lto.
1420 if (IsOffload && Args.hasFlag(options::OPT_fopenmp_target_jit,
1421 options::OPT_fno_openmp_target_jit, false)) {
1422 if (Arg *A = Args.getLastArg(OptEq, OptNeg))
1423 if (parseLTOMode(Args, OptEq, OptNeg) != LTOK_Full)
1424 getDriver().Diag(diag::err_drv_incompatible_options)
1425 << A->getSpelling() << "-fopenmp-target-jit";
1426 return LTOK_Full;
1427 }
1428
1429 if (!Args.hasArg(OptEq, OptNeg))
1430 return getDefaultLTOMode();
1431
1432 LTOKind Mode = parseLTOMode(Args, OptEq, OptNeg);
1433
1434 if (Mode == LTOK_Unknown) {
1435 const Arg *A = Args.getLastArg(OptEq);
1436 getDriver().Diag(diag::err_drv_unsupported_option_argument)
1437 << A->getSpelling() << A->getValue();
1438 return LTOK_None;
1439 }
1440 return Mode;
1441}
1442
1444 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
1445 switch (HostTriple.getArch()) {
1446 // The A32/T32/T16 instruction sets are not separate architectures in this
1447 // context.
1448 case llvm::Triple::arm:
1449 case llvm::Triple::armeb:
1450 case llvm::Triple::thumb:
1451 case llvm::Triple::thumbeb:
1452 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
1453 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
1454 default:
1455 return HostTriple.getArch() != getArch();
1456 }
1457}
1458
1460 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
1461 VersionTuple());
1462}
1463
1464llvm::ExceptionHandling
1465ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
1466 return llvm::ExceptionHandling::None;
1467}
1468
1469bool ToolChain::isThreadModelSupported(const StringRef Model) const {
1470 if (Model == "single") {
1471 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
1472 return Triple.getArch() == llvm::Triple::arm ||
1473 Triple.getArch() == llvm::Triple::armeb ||
1474 Triple.getArch() == llvm::Triple::thumb ||
1475 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
1476 } else if (Model == "posix")
1477 return true;
1478
1479 return false;
1480}
1481
1482std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, BoundArch BA,
1483 types::ID InputType) const {
1484 switch (getTriple().getArch()) {
1485 default:
1486 return getTripleString().str();
1487
1488 case llvm::Triple::x86_64: {
1489 llvm::Triple Triple = getTriple();
1490 if (!Triple.isOSBinFormatMachO())
1491 return getTripleString().str();
1492
1493 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1494 // x86_64h goes in the triple. Other -march options just use the
1495 // vanilla triple we already have.
1496 StringRef MArch = A->getValue();
1497 if (MArch == "x86_64h")
1498 Triple.setArchName(MArch);
1499 }
1500 return Triple.getTriple();
1501 }
1502 case llvm::Triple::aarch64: {
1503 llvm::Triple Triple = getTriple();
1504 if (!Triple.isOSBinFormatMachO())
1505 return Triple.getTriple();
1506
1507 if (Triple.isArm64e())
1508 return Triple.getTriple();
1509
1510 // FIXME: older versions of ld64 expect the "arm64" component in the actual
1511 // triple string and query it to determine whether an LTO file can be
1512 // handled. Remove this when we don't care any more.
1513 Triple.setArchName("arm64");
1514 return Triple.getTriple();
1515 }
1516 case llvm::Triple::aarch64_32:
1517 return getTripleString().str();
1518 case llvm::Triple::amdgpu: {
1519 llvm::Triple Triple = getTriple();
1520 tools::AMDGPU::setArchNameInTriple(getDriver(), Args, BA, InputType,
1521 Triple);
1522 return Triple.getTriple();
1523 }
1524 case llvm::Triple::arm:
1525 case llvm::Triple::armeb:
1526 case llvm::Triple::thumb:
1527 case llvm::Triple::thumbeb: {
1528 llvm::Triple Triple = getTriple();
1529 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1531 return Triple.getTriple();
1532 }
1533 }
1534}
1535
1536std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1537 BoundArch BA,
1538 types::ID InputType) const {
1539 return ComputeLLVMTriple(Args, BA, InputType);
1540}
1541
1542std::string ToolChain::computeSysRoot() const {
1543 return D.SysRoot;
1544}
1545
1546void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1547 ArgStringList &CC1Args) const {
1548 // Each toolchain should provide the appropriate include flags.
1549}
1550
1552 const ArgList &DriverArgs, ArgStringList &CC1Args, BoundArch BA,
1553 Action::OffloadKind DeviceOffloadKind) const {}
1554
1556 ArgStringList &CC1ASArgs) const {}
1557
1558void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1559
1560void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1561 llvm::opt::ArgStringList &CmdArgs) const {
1562 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1563 return;
1564
1565 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1566}
1567
1569 const ArgList &Args) const {
1570 if (runtimeLibType)
1571 return *runtimeLibType;
1572
1573 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1574 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1575
1576 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1577 if (LibName == "compiler-rt")
1578 runtimeLibType = ToolChain::RLT_CompilerRT;
1579 else if (LibName == "libgcc")
1580 runtimeLibType = ToolChain::RLT_Libgcc;
1581 else if (LibName == "platform")
1582 runtimeLibType = GetDefaultRuntimeLibType();
1583 else {
1584 if (A)
1585 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1586 << A->getAsString(Args);
1587
1588 runtimeLibType = GetDefaultRuntimeLibType();
1589 }
1590
1591 return *runtimeLibType;
1592}
1593
1595 const ArgList &Args) const {
1596 if (unwindLibType)
1597 return *unwindLibType;
1598
1599 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1600 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1601
1602 if (LibName == "none")
1603 unwindLibType = ToolChain::UNW_None;
1604 else if (LibName == "platform" || LibName == "") {
1606 if (RtLibType == ToolChain::RLT_CompilerRT) {
1607 if (getTriple().isAndroid() || getTriple().isOSAIX() ||
1608 getTriple().isOSSerenity())
1609 unwindLibType = ToolChain::UNW_CompilerRT;
1610 else
1611 unwindLibType = ToolChain::UNW_None;
1612 } else if (RtLibType == ToolChain::RLT_Libgcc)
1613 unwindLibType = ToolChain::UNW_Libgcc;
1614 } else if (LibName == "libunwind") {
1615 if (GetRuntimeLibType(Args) == RLT_Libgcc)
1616 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1617 unwindLibType = ToolChain::UNW_CompilerRT;
1618 } else if (LibName == "libgcc")
1619 unwindLibType = ToolChain::UNW_Libgcc;
1620 else {
1621 if (A)
1622 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1623 << A->getAsString(Args);
1624
1625 unwindLibType = GetDefaultUnwindLibType();
1626 }
1627
1628 return *unwindLibType;
1629}
1630
1632 if (cxxStdlibType)
1633 return *cxxStdlibType;
1634
1635 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1636 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1637
1638 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1639 if (LibName == "libc++")
1640 cxxStdlibType = ToolChain::CST_Libcxx;
1641 else if (LibName == "libstdc++")
1642 cxxStdlibType = ToolChain::CST_Libstdcxx;
1643 else if (LibName == "platform")
1644 cxxStdlibType = GetDefaultCXXStdlibType();
1645 else {
1646 if (A)
1647 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1648 << A->getAsString(Args);
1649
1650 cxxStdlibType = GetDefaultCXXStdlibType();
1651 }
1652
1653 return *cxxStdlibType;
1654}
1655
1656StringRef ToolChain::GetCXXStdlibName(const ArgList &Args) const {
1657 switch (GetCXXStdlibType(Args)) {
1659 return "libc++";
1661 return "libstdc++";
1662 }
1663 llvm_unreachable("unknown C++ standard library type");
1664}
1665
1667 if (cStdlibType)
1668 return *cStdlibType;
1669
1670 const Arg *A = Args.getLastArg(options::OPT_cstdlib_EQ);
1671 StringRef LibName = A ? A->getValue() : "system";
1672
1673 if (LibName == "newlib")
1674 cStdlibType = ToolChain::CST_Newlib;
1675 else if (LibName == "picolibc")
1676 cStdlibType = ToolChain::CST_Picolibc;
1677 else if (LibName == "llvm-libc")
1678 cStdlibType = ToolChain::CST_LLVMLibC;
1679 else if (LibName == "system")
1680 cStdlibType = ToolChain::CST_System;
1681 else {
1682 if (A)
1683 getDriver().Diag(diag::err_drv_invalid_cstdlib_name)
1684 << A->getAsString(Args);
1685 cStdlibType = ToolChain::CST_System;
1686 }
1687
1688 return *cStdlibType;
1689}
1690
1691/// Utility function to add a system framework directory to CC1 arguments.
1692void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs,
1693 llvm::opt::ArgStringList &CC1Args,
1694 const Twine &Path) {
1695 CC1Args.push_back("-internal-iframework");
1696 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1697}
1698
1699/// Utility function to add a system include directory with extern "C"
1700/// semantics to CC1 arguments.
1701///
1702/// Note that this should be used rarely, and only for directories that
1703/// historically and for legacy reasons are treated as having implicit extern
1704/// "C" semantics. These semantics are *ignored* by and large today, but its
1705/// important to preserve the preprocessor changes resulting from the
1706/// classification.
1707void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1708 ArgStringList &CC1Args,
1709 const Twine &Path) {
1710 CC1Args.push_back("-internal-externc-isystem");
1711 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1712}
1713
1714void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1715 ArgStringList &CC1Args,
1716 const Twine &Path) {
1717 if (llvm::sys::fs::exists(Path))
1718 addExternCSystemInclude(DriverArgs, CC1Args, Path);
1719}
1720
1721/// Utility function to add a system include directory to CC1 arguments.
1722/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1723 ArgStringList &CC1Args,
1724 const Twine &Path) {
1725 CC1Args.push_back("-internal-isystem");
1726 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1727}
1728
1729/// Utility function to add a list of system framework directories to CC1.
1730void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs,
1731 ArgStringList &CC1Args,
1732 ArrayRef<StringRef> Paths) {
1733 for (const auto &Path : Paths) {
1734 CC1Args.push_back("-internal-iframework");
1735 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1736 }
1737}
1738
1739/// Utility function to add a list of system include directories to CC1.
1740void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1741 ArgStringList &CC1Args,
1742 ArrayRef<StringRef> Paths) {
1743 for (const auto &Path : Paths) {
1744 CC1Args.push_back("-internal-isystem");
1745 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1746 }
1747}
1748
1749std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B,
1750 const Twine &C, const Twine &D) {
1752 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1753 return std::string(Result);
1754}
1755
1756std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1757 std::error_code EC;
1758 int MaxVersion = 0;
1759 std::string MaxVersionString;
1760 SmallString<128> Path(IncludePath);
1761 llvm::sys::path::append(Path, "c++");
1762 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1763 !EC && LI != LE; LI = LI.increment(EC)) {
1764 StringRef VersionText = llvm::sys::path::filename(LI->path());
1765 int Version;
1766 if (VersionText[0] == 'v' &&
1767 !VersionText.substr(1).getAsInteger(10, Version)) {
1768 if (Version > MaxVersion) {
1769 MaxVersion = Version;
1770 MaxVersionString = std::string(VersionText);
1771 }
1772 }
1773 }
1774 if (!MaxVersion)
1775 return "";
1776 return MaxVersionString;
1777}
1778
1779void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1780 ArgStringList &CC1Args) const {
1781 // Header search paths should be handled by each of the subclasses.
1782 // Historically, they have not been, and instead have been handled inside of
1783 // the CC1-layer frontend. As the logic is hoisted out, this generic function
1784 // will slowly stop being called.
1785 //
1786 // While it is being called, replicate a bit of a hack to propagate the
1787 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1788 // header search paths with it. Once all systems are overriding this
1789 // function, the CC1 flag and this line can be removed.
1790 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1791}
1792
1794 const llvm::opt::ArgList &DriverArgs,
1795 llvm::opt::ArgStringList &CC1Args) const {
1796 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1797 // This intentionally only looks at -nostdinc++, and not -nostdinc or
1798 // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1799 // setups with non-standard search logic for the C++ headers, while still
1800 // allowing users of the toolchain to bring their own C++ headers. Such a
1801 // toolchain likely also has non-standard search logic for the C headers and
1802 // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1803 // still work in that case and only be suppressed by an explicit -nostdinc++
1804 // in a project using the toolchain.
1805 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1806 for (const auto &P :
1807 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1808 addSystemInclude(DriverArgs, CC1Args, P);
1809}
1810
1811bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1812 return getDriver().CCCIsCXX() &&
1813 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1814 options::OPT_nostdlibxx);
1815}
1816
1817void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1818 ArgStringList &CmdArgs) const {
1819 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1820 "should not have called this");
1822
1823 switch (Type) {
1825 CmdArgs.push_back("-lc++");
1826 if (Args.hasArg(options::OPT_fexperimental_library))
1827 CmdArgs.push_back("-lc++experimental");
1828 break;
1829
1831 CmdArgs.push_back("-lstdc++");
1832 break;
1833 }
1834}
1835
1836void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1837 ArgStringList &CmdArgs) const {
1838 for (const auto &LibPath : getFilePaths())
1839 if(LibPath.length() > 0)
1840 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1841}
1842
1843void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1844 ArgStringList &CmdArgs) const {
1845 CmdArgs.push_back("-lcc_kext");
1846}
1847
1849 std::string &Path) const {
1850 // Don't implicitly link in mode-changing libraries in a shared library, since
1851 // this can have very deleterious effects. See the various links from
1852 // https://github.com/llvm/llvm-project/issues/57589 for more information.
1853 bool Default = !Args.hasArgNoClaim(options::OPT_shared);
1854
1855 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1856 // (to keep the linker options consistent with gcc and clang itself).
1857 if (Default && !isOptimizationLevelFast(Args)) {
1858 // Check if -ffast-math or -funsafe-math.
1859 Arg *A = Args.getLastArg(
1860 options::OPT_ffast_math, options::OPT_fno_fast_math,
1861 options::OPT_funsafe_math_optimizations,
1862 options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ);
1863
1864 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1865 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1866 Default = false;
1867 if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) {
1868 StringRef Model = A->getValue();
1869 if (Model != "fast" && Model != "aggressive")
1870 Default = false;
1871 }
1872 }
1873
1874 // Whatever decision came as a result of the above implicit settings, either
1875 // -mdaz-ftz or -mno-daz-ftz is capable of overriding it.
1876 if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default))
1877 return false;
1878
1879 // If crtfastmath.o exists add it to the arguments.
1880 Path = GetFilePath("crtfastmath.o");
1881 return (Path != "crtfastmath.o"); // Not found.
1882}
1883
1885 ArgStringList &CmdArgs) const {
1886 std::string Path;
1887 if (isFastMathRuntimeAvailable(Args, Path)) {
1888 CmdArgs.push_back(Args.MakeArgString(Path));
1889 return true;
1890 }
1891
1892 return false;
1893}
1894
1896ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1897 return SmallVector<std::string>();
1898}
1899
1902 Action::OffloadKind DeviceOffloadKind) const {
1903 // Return sanitizers which don't require runtime support and are not
1904 // platform dependent.
1905
1906 SanitizerMask Res =
1907 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1908 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1909 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1910 SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1911 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1912 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
1913 SanitizerKind::AllocToken;
1914 if (getTriple().getArch() == llvm::Triple::x86 ||
1915 getTriple().getArch() == llvm::Triple::x86_64 ||
1916 getTriple().getArch() == llvm::Triple::arm ||
1917 getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() ||
1918 getTriple().isAArch64() || getTriple().isRISCV() ||
1919 getTriple().isLoongArch64() ||
1920 getTriple().getArch() == llvm::Triple::hexagon)
1921 Res |= SanitizerKind::CFIICall;
1922 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1923 getTriple().isAArch64(64) || getTriple().isRISCV())
1924 Res |= SanitizerKind::ShadowCallStack;
1925 if (getTriple().isAArch64(64))
1926 Res |= SanitizerKind::MemTag;
1927 if (getTriple().isBPF())
1928 Res |= SanitizerKind::KernelAddress;
1929 return Res;
1930}
1931
1932void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1933 ArgStringList &CC1Args) const {}
1934
1935void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1936 ArgStringList &CC1Args) const {}
1937
1938void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
1939 ArgStringList &CC1Args) const {}
1940
1942ToolChain::getDeviceLibs(const ArgList &DriverArgs, BoundArch BA,
1943 const Action::OffloadKind DeviceOffloadingKind) const {
1944 return {};
1945}
1946
1947void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1948 ArgStringList &CC1Args) const {}
1949
1950static VersionTuple separateMSVCFullVersion(unsigned Version) {
1951 if (Version < 100)
1952 return VersionTuple(Version);
1953
1954 if (Version < 10000)
1955 return VersionTuple(Version / 100, Version % 100);
1956
1957 unsigned Build = 0, Factor = 1;
1958 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1959 Build = Build + (Version % 10) * Factor;
1960 return VersionTuple(Version / 100, Version % 100, Build);
1961}
1962
1963VersionTuple
1965 const llvm::opt::ArgList &Args) const {
1966 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1967 const Arg *MSCompatibilityVersion =
1968 Args.getLastArg(options::OPT_fms_compatibility_version);
1969
1970 if (MSCVersion && MSCompatibilityVersion) {
1971 if (D)
1972 D->Diag(diag::err_drv_argument_not_allowed_with)
1973 << MSCVersion->getAsString(Args)
1974 << MSCompatibilityVersion->getAsString(Args);
1975 return VersionTuple();
1976 }
1977
1978 if (MSCompatibilityVersion) {
1979 VersionTuple MSVT;
1980 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1981 if (D)
1982 D->Diag(diag::err_drv_invalid_value)
1983 << MSCompatibilityVersion->getAsString(Args)
1984 << MSCompatibilityVersion->getValue();
1985 } else {
1986 return MSVT;
1987 }
1988 }
1989
1990 if (MSCVersion) {
1991 unsigned Version = 0;
1992 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1993 if (D)
1994 D->Diag(diag::err_drv_invalid_value)
1995 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1996 } else {
1997 return separateMSVCFullVersion(Version);
1998 }
1999 }
2000
2001 return VersionTuple();
2002}
2003
2004llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
2005 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
2006 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
2007 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2008 const OptTable &Opts = getDriver().getOpts();
2009 bool Modified = false;
2010
2011 // Handle -Xopenmp-target flags
2012 for (auto *A : Args) {
2013 // Exclude flags which may only apply to the host toolchain.
2014 // Do not exclude flags when the host triple (AuxTriple)
2015 // matches the current toolchain triple. If it is not present
2016 // at all, target and host share a toolchain.
2017 if (A->getOption().matches(options::OPT_m_Group)) {
2018 // Pass certain options to the device toolchain even when the triple
2019 // differs from the host: code object version must be passed to correctly
2020 // set metadata in intermediate files; linker version must be passed
2021 // because the Darwin toolchain requires the host and device linker
2022 // versions to match (the host version is cached in
2023 // MachO::getLinkerVersion).
2024 if (SameTripleAsHost ||
2025 A->getOption().matches(options::OPT_mcode_object_version_EQ) ||
2026 A->getOption().matches(options::OPT_mlinker_version_EQ))
2027 DAL->append(A);
2028 else
2029 Modified = true;
2030 continue;
2031 }
2032
2033 unsigned Index;
2034 unsigned Prev;
2035 bool XOpenMPTargetNoTriple =
2036 A->getOption().matches(options::OPT_Xopenmp_target);
2037
2038 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
2039 llvm::Triple TT = normalizeOffloadTriple(A->getValue(0));
2040
2041 // Passing device args: -Xopenmp-target=<triple> -opt=val.
2042 if (TT.isCompatibleWith(getTriple()))
2043 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
2044 else
2045 continue;
2046 } else if (XOpenMPTargetNoTriple) {
2047 // Passing device args: -Xopenmp-target -opt=val.
2048 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
2049 } else {
2050 DAL->append(A);
2051 continue;
2052 }
2053
2054 // Parse the argument to -Xopenmp-target.
2055 Prev = Index;
2056 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
2057 if (!XOpenMPTargetArg || Index > Prev + 1) {
2058 if (!A->isClaimed()) {
2059 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
2060 << A->getAsString(Args);
2061 }
2062 continue;
2063 }
2064 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
2065 Args.getAllArgValues(options::OPT_offload_targets_EQ).size() != 1) {
2066 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
2067 continue;
2068 }
2069 XOpenMPTargetArg->setBaseArg(A);
2070 A = XOpenMPTargetArg.release();
2071 AllocatedArgs.push_back(A);
2072 DAL->append(A);
2073 Modified = true;
2074 }
2075
2076 if (Modified)
2077 return DAL;
2078
2079 delete DAL;
2080 return nullptr;
2081}
2082
2083// TODO: Currently argument values separated by space e.g.
2084// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
2085// fixed.
2087 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
2088 llvm::opt::DerivedArgList *DAL,
2089 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
2090 const OptTable &Opts = getDriver().getOpts();
2091 unsigned ValuePos = 1;
2092 if (A->getOption().matches(options::OPT_Xarch_device) ||
2093 A->getOption().matches(options::OPT_Xarch_host))
2094 ValuePos = 0;
2095
2096 const InputArgList &BaseArgs = Args.getBaseArgs();
2097 unsigned Index = BaseArgs.MakeIndex(A->getValue(ValuePos));
2098 unsigned Prev = Index;
2099 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(
2100 Args, Index, llvm::opt::Visibility(options::ClangOption)));
2101
2102 // If the argument parsing failed or more than one argument was
2103 // consumed, the -Xarch_ argument's parameter tried to consume
2104 // extra arguments. Emit an error and ignore.
2105 //
2106 // We also want to disallow any options which would alter the
2107 // driver behavior; that isn't going to work in our model. We
2108 // use options::NoXarchOption to control this.
2109 if (!XarchArg || Index > Prev + 1) {
2110 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2111 << A->getAsString(Args);
2112 return;
2113 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
2114 auto &Diags = getDriver().getDiags();
2115 unsigned DiagID =
2117 "invalid Xarch argument: '%0', not all driver "
2118 "options can be forwared via Xarch argument");
2119 Diags.Report(DiagID) << A->getAsString(Args);
2120 return;
2121 }
2122
2123 XarchArg->setBaseArg(A);
2124 A = XarchArg.release();
2125
2126 // Linker input arguments require custom handling. The problem is that we
2127 // have already constructed the phase actions, so we can not treat them as
2128 // "input arguments".
2129 if (A->getOption().hasFlag(options::LinkerInput)) {
2130 // Convert the argument into individual Zlinker_input_args. Need to do this
2131 // manually to avoid memory leaks with the allocated arguments.
2132 for (const char *Value : A->getValues()) {
2133 auto Opt = Opts.getOption(options::OPT_Zlinker_input);
2134 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
2135 auto NewArg =
2136 new Arg(Opt, BaseArgs.MakeArgString(Opt.getPrefix() + Opt.getName()),
2137 Index, BaseArgs.getArgString(Index + 1), A);
2138
2139 DAL->append(NewArg);
2140 if (!AllocatedArgs)
2141 DAL->AddSynthesizedArg(NewArg);
2142 else
2143 AllocatedArgs->push_back(NewArg);
2144 }
2145 }
2146
2147 if (!AllocatedArgs)
2148 DAL->AddSynthesizedArg(A);
2149 else
2150 AllocatedArgs->push_back(A);
2151}
2152
2153/// Match any triple recognized arch aliases.
2154static bool isXArchCompatibleTripleArch(const llvm::Triple &TT,
2155 StringRef XArchVal) {
2156 llvm::Triple ParsedTriple(XArchVal);
2157
2158 // Accept -Xarch_amdgcn for all amdgpu subarches, and -Xarch_amdgpu9 for
2159 // amdgpu9.xx
2160 if (TT.isAMDGCN() && ParsedTriple.isAMDGCN())
2161 return llvm::AMDGPU::isSubArchCompatible(TT, ParsedTriple);
2162
2163 return TT.getArch() == ParsedTriple.getArch() &&
2164 TT.getSubArch() == ParsedTriple.getSubArch();
2165}
2166
2167llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
2168 const llvm::opt::DerivedArgList &Args, BoundArch BA,
2170 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
2171 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2172 bool Modified = false;
2173
2174 bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
2175 for (Arg *A : Args) {
2176 bool NeedTrans = false;
2177 bool Skip = false;
2178 if (A->getOption().matches(options::OPT_Xarch_device)) {
2179 NeedTrans = IsDevice;
2180 Skip = !IsDevice;
2181 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
2182 NeedTrans = !IsDevice;
2183 Skip = IsDevice;
2184 } else if (A->getOption().matches(options::OPT_Xarch__)) {
2185 StringRef Val = A->getValue();
2186 NeedTrans = Val == getArchName() || (BA && Val == BA.ArchName) ||
2187 isXArchCompatibleTripleArch(Triple, Val);
2188 Skip = !NeedTrans;
2189 }
2190 if (NeedTrans || Skip)
2191 Modified = true;
2192 if (NeedTrans) {
2193 A->claim();
2194 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
2195 }
2196 if (!Skip)
2197 DAL->append(A);
2198 }
2199
2200 if (Modified)
2201 return DAL;
2202
2203 delete DAL;
2204 return nullptr;
2205}
Result
Implement __builtin_bit_cast and related operations.
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 LTOKind parseLTOMode(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier OptEq, llvm::opt::OptSpecifier OptNeg)
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:84
static llvm::opt::Arg * GetRTTIArgument(const ArgList &Args)
Definition ToolChain.cpp:63
static bool isXArchCompatibleTripleArch(const llvm::Triple &TT, StringRef XArchVal)
Match any triple recognized arch aliases.
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:68
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:926
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:1879
ActionClass getKind() const
Definition Action.h:153
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:96
DiagnosticsEngine & getDiags() const
Definition Driver.h:410
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:896
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:160
StringRef getFlangF128MathLibrary() const
Definition Driver.h:452
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:408
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:412
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:146
StringRef getPreferredLinker() const
Definition Driver.h:434
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:223
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
static llvm::ErrorOr< MultilibSet > parseYaml(llvm::MemoryBufferRef, llvm::SourceMgr::DiagHandlerTy=nullptr, void *DiagHandlerCtxt=nullptr)
Definition Multilib.cpp:479
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag.
Definition Multilib.h:35
std::vector< std::string > flags_list
Definition Multilib.h:37
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:96
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:909
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 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.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
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.
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.
virtual llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, BoundArch BA, const Action::OffloadKind DeviceOffloadingKind) const
Get paths for device libraries.
virtual LTOKind getDefaultLTOMode() const
Returns the default LTO mode for this toolchain.
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:496
virtual void addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Adds the path for the Fortran runtime libraries to CmdArgs.
std::optional< std::string > findMultilibsYAML(const llvm::opt::ArgList &Args, const Driver &D, StringRef FallbackDir={})
Load multilib configuration from a YAML file at MultilibPath,.
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:326
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:305
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isBareMetal() const
isBareMetal - Is this a bare metal target.
Definition ToolChain.h:708
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
virtual SanitizerMask getSupportedSanitizers(BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:302
const Driver & getDriver() const
Definition ToolChain.h:286
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:369
ExceptionsMode getExceptionsMode() const
Definition ToolChain.h:372
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.
bool loadMultilibsFromYAML(const llvm::opt::ArgList &Args, const Driver &D, StringRef Fallback={})
Discover and load a multilib.yaml configuration.
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:92
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.
SmallVector< std::string > MultilibMacroDefines
Definition ToolChain.h:218
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 LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
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:492
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition ToolChain.h:547
virtual Tool * buildLinker() const
const llvm::Triple & getTriple() const
Definition ToolChain.h:288
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.
OrderedMultilibs getOrderedMultilibs() const
Get selected multilibs in priority order with default fallback.
llvm::iterator_range< llvm::SmallVector< Multilib >::const_reverse_iterator > OrderedMultilibs
Definition ToolChain.h:220
StringRef getTripleString() const
Definition ToolChain.h:311
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.
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
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:554
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.
virtual RuntimeLibType GetDefaultRuntimeLibType() const
GetDefaultRuntimeLibType - Get the default runtime library variant to use.
Definition ToolChain.h:550
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
virtual Tool * buildAssembler() const
virtual StringRef GetCXXStdlibName(const llvm::opt::ArgList &Args) 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:488
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
llvm::SmallVector< Multilib > SelectedMultilibs
Definition ToolChain.h:217
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA={}, Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
path_list & getLibraryPaths()
Definition ToolChain.h:323
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:558
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
friend class RegisterEffectiveTriple
Definition ToolChain.h:149
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:500
std::optional< std::string > getDefaultIntrinsicModuleDir() const
Returns the target-specific path for Flang's intrinsic modules in the resource directory if it exists...
virtual void TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, llvm::opt::DerivedArgList *DAL, SmallVectorImpl< llvm::opt::Arg * > *AllocatedArgs=nullptr) const
Append the argument following A to DAL assuming A is an Xarch argument.
virtual bool useRelaxRelocations() const
Check whether to enable x86 relax relocations by default.
StringRef getArchName() const
Definition ToolChain.h:303
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:98
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:124
Clang compiler tool.
Definition Clang.h:28
Flang compiler tool.
Definition Flang.h:25
void setArchNameInTriple(const Driver &D, const llvm::opt::ArgList &Args, BoundArch BA, types::ID InputType, llvm::Triple &Triple)
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:305
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:332
LTOKind
Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
Definition Driver.h:60
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
Top level wrappers for InstallAPI frontend operations.
@ Link
'link' clause, allowed on 'declare' construct.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Represents a bound architecture for offload / multiple architecture compilation.
llvm::StringRef ArchName
Helper structure used to pass information extracted from clang executable name such as i686-linux-and...
Definition ToolChain.h:69