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