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.empty())
293 if (FeatureSet.contains(Ext.PosTargetFeature))
294 MArch.push_back(Ext.UserVisibleName.str());
295 for (const auto &Ext : AArch64::Extensions)
296 if (!Ext.UserVisibleName.empty())
297 if (FeatureSet.contains(Ext.NegTargetFeature))
298 MArch.push_back(("no" + Ext.UserVisibleName).str());
299 StringRef ArchName;
300 for (const auto &ArchInfo : AArch64::ArchInfos)
301 if (FeatureSet.contains(ArchInfo->ArchFeature))
302 ArchName = 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
451ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
452 using namespace clang::options;
453
454 std::vector<std::string> Result;
455 const llvm::Triple Triple(ComputeEffectiveClangTriple(Args));
456 Result.push_back("--target=" + Triple.str());
457
458 // A difference of relocation model (absolutely addressed data, PIC, Arm
459 // ROPI/RWPI) is likely to change whether a particular multilib variant is
460 // compatible with a given link. Determine the relocation model of the
461 // current link, so as to add appropriate multilib flags.
462 llvm::Reloc::Model RelocationModel;
463 unsigned PICLevel;
464 bool IsPIE;
465 {
466 RegisterEffectiveTriple TripleRAII(*this, Triple);
467 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(*this, Args);
468 }
469
470 switch (Triple.getArch()) {
471 case llvm::Triple::aarch64:
472 case llvm::Triple::aarch64_32:
473 case llvm::Triple::aarch64_be:
474 getAArch64MultilibFlags(D, Triple, Args, Result);
475 break;
476 case llvm::Triple::arm:
477 case llvm::Triple::armeb:
478 case llvm::Triple::thumb:
479 case llvm::Triple::thumbeb:
480 getARMMultilibFlags(D, Triple, RelocationModel, Args, Result);
481 break;
482 case llvm::Triple::riscv32:
483 case llvm::Triple::riscv64:
484 case llvm::Triple::riscv32be:
485 case llvm::Triple::riscv64be:
486 getRISCVMultilibFlags(D, Triple, Args, Result,
487 getSanitizerArgs(Args).hasShadowCallStack());
488 break;
489 default:
490 break;
491 }
492
494
495 // Include fno-exceptions and fno-rtti
496 // to improve multilib selection
498 Result.push_back("-fno-rtti");
499 else
500 Result.push_back("-frtti");
501
503 Result.push_back("-fno-exceptions");
504 else
505 Result.push_back("-fexceptions");
506
507 if (RelocationModel == llvm::Reloc::PIC_)
508 Result.push_back(IsPIE ? (PICLevel > 1 ? "-fPIE" : "-fpie")
509 : (PICLevel > 1 ? "-fPIC" : "-fpic"));
510 else
511 Result.push_back("-fno-pic");
512
513 // Sort and remove duplicates.
514 std::sort(Result.begin(), Result.end());
515 Result.erase(llvm::unique(Result), Result.end());
516 return Result;
517}
518
520ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs,
521 StringRef BoundArch,
522 Action::OffloadKind DeviceOffloadKind) const {
523 // When -fno-gpu-sanitize is specified for GPU targets, don't emit
524 // diagnostics about unsupported sanitizers for specific GPU arches,
525 // since sanitizers are disabled for the GPU anyway.
526 bool DiagnoseBoundArchErrors =
527 BoundArchSanitizerArgsChecked.insert(BoundArch).second;
528 if (!BoundArch.empty() && getTriple().isGPU() &&
529 !JobArgs.hasFlag(options::OPT_fgpu_sanitize,
530 options::OPT_fno_gpu_sanitize, true)) {
531 DiagnoseBoundArchErrors = false;
532 }
533
534 SanitizerArgs SanArgs(*this, JobArgs,
535 /*DiagnoseErrors=*/!SanitizerArgsChecked,
536 DiagnoseBoundArchErrors, BoundArch, DeviceOffloadKind);
537
538 SanitizerArgsChecked = true;
539 return SanArgs;
540}
541
542const XRayArgs ToolChain::getXRayArgs(const llvm::opt::ArgList &JobArgs) const {
543 XRayArgs XRayArguments(*this, JobArgs);
544 return XRayArguments;
545}
546
547namespace {
548
549struct DriverSuffix {
550 const char *Suffix;
551 const char *ModeFlag;
552};
553
554} // namespace
555
556static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
557 // A list of known driver suffixes. Suffixes are compared against the
558 // program name in order. If there is a match, the frontend type is updated as
559 // necessary by applying the ModeFlag.
560 static const DriverSuffix DriverSuffixes[] = {
561 {"clang", nullptr},
562 {"clang++", "--driver-mode=g++"},
563 {"clang-c++", "--driver-mode=g++"},
564 {"clang-cc", nullptr},
565 {"clang-cpp", "--driver-mode=cpp"},
566 {"clang-g++", "--driver-mode=g++"},
567 {"clang-gcc", nullptr},
568 {"clang-cl", "--driver-mode=cl"},
569 {"cc", nullptr},
570 {"cpp", "--driver-mode=cpp"},
571 {"cl", "--driver-mode=cl"},
572 {"++", "--driver-mode=g++"},
573 {"flang", "--driver-mode=flang"},
574 // For backwards compatibility, we create a symlink for `flang` called
575 // `flang-new`. This will be removed in the future.
576 {"flang-new", "--driver-mode=flang"},
577 {"clang-dxc", "--driver-mode=dxc"},
578 };
579
580 for (const auto &DS : DriverSuffixes) {
581 StringRef Suffix(DS.Suffix);
582 if (ProgName.ends_with(Suffix)) {
583 Pos = ProgName.size() - Suffix.size();
584 return &DS;
585 }
586 }
587 return nullptr;
588}
589
590/// Normalize the program name from argv[0] by stripping the file extension if
591/// present and lower-casing the string on Windows.
592static std::string normalizeProgramName(llvm::StringRef Argv0) {
593 std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
594 if (is_style_windows(llvm::sys::path::Style::native)) {
595 // Transform to lowercase for case insensitive file systems.
596 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
597 ::tolower);
598 }
599 return ProgName;
600}
601
602static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
603 // Try to infer frontend type and default target from the program name by
604 // comparing it against DriverSuffixes in order.
605
606 // If there is a match, the function tries to identify a target as prefix.
607 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
608 // prefix "x86_64-linux". If such a target prefix is found, it may be
609 // added via -target as implicit first argument.
610 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
611
612 if (!DS && ProgName.ends_with(".exe")) {
613 // Try again after stripping the executable suffix:
614 // clang++.exe -> clang++
615 ProgName = ProgName.drop_back(StringRef(".exe").size());
616 DS = FindDriverSuffix(ProgName, Pos);
617 }
618
619 if (!DS) {
620 // Try again after stripping any trailing version number:
621 // clang++3.5 -> clang++
622 ProgName = ProgName.rtrim("0123456789.");
623 DS = FindDriverSuffix(ProgName, Pos);
624 }
625
626 if (!DS) {
627 // Try again after stripping trailing -component.
628 // clang++-tot -> clang++
629 ProgName = ProgName.slice(0, ProgName.rfind('-'));
630 DS = FindDriverSuffix(ProgName, Pos);
631 }
632 return DS;
633}
634
637 std::string ProgName = normalizeProgramName(PN);
638 size_t SuffixPos;
639 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
640 if (!DS)
641 return {};
642 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
643
644 size_t LastComponent = ProgName.rfind('-', SuffixPos);
645 if (LastComponent == std::string::npos)
646 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
647 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
648 SuffixEnd - LastComponent - 1);
649
650 // Infer target from the prefix.
651 StringRef Prefix(ProgName);
652 Prefix = Prefix.slice(0, LastComponent);
653 std::string IgnoredError;
654
655 llvm::Triple Triple(Prefix);
656 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Triple, IgnoredError);
657 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
658 IsRegistered};
659}
660
662 // In universal driver terms, the arch name accepted by -arch isn't exactly
663 // the same as the ones that appear in the triple. Roughly speaking, this is
664 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
665 switch (Triple.getArch()) {
666 case llvm::Triple::aarch64: {
667 if (getTriple().isArm64e())
668 return "arm64e";
669 return "arm64";
670 }
671 case llvm::Triple::aarch64_32:
672 return "arm64_32";
673 case llvm::Triple::ppc:
674 return "ppc";
675 case llvm::Triple::ppcle:
676 return "ppcle";
677 case llvm::Triple::ppc64:
678 return "ppc64";
679 case llvm::Triple::ppc64le:
680 return "ppc64le";
681 default:
682 return Triple.getArchName();
683 }
684}
685
686std::string ToolChain::getInputFilename(const InputInfo &Input) const {
687 return Input.getFilename();
688}
689
691ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
693}
694
695Tool *ToolChain::getClang() const {
696 if (!Clang)
697 Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
698 return Clang.get();
699}
700
701Tool *ToolChain::getFlang() const {
702 if (!Flang)
703 Flang.reset(new tools::Flang(*this));
704 return Flang.get();
705}
706
708 return new tools::ClangAs(*this);
709}
710
712 llvm_unreachable("Linking is not supported by this toolchain");
713}
714
716 llvm_unreachable("Creating static lib is not supported by this toolchain");
717}
718
719Tool *ToolChain::getAssemble() const {
720 if (!Assemble)
721 Assemble.reset(buildAssembler());
722 return Assemble.get();
723}
724
725Tool *ToolChain::getClangAs() const {
726 if (!Assemble)
727 Assemble.reset(new tools::ClangAs(*this));
728 return Assemble.get();
729}
730
731Tool *ToolChain::getLink() const {
732 if (!Link)
733 Link.reset(buildLinker());
734 return Link.get();
735}
736
737Tool *ToolChain::getStaticLibTool() const {
738 if (!StaticLibTool)
739 StaticLibTool.reset(buildStaticLibTool());
740 return StaticLibTool.get();
741}
742
743Tool *ToolChain::getIfsMerge() const {
744 if (!IfsMerge)
745 IfsMerge.reset(new tools::ifstool::Merger(*this));
746 return IfsMerge.get();
747}
748
749Tool *ToolChain::getOffloadBundler() const {
750 if (!OffloadBundler)
751 OffloadBundler.reset(new tools::OffloadBundler(*this));
752 return OffloadBundler.get();
753}
754
755Tool *ToolChain::getOffloadPackager() const {
756 if (!OffloadPackager)
757 OffloadPackager.reset(new tools::OffloadPackager(*this));
758 return OffloadPackager.get();
759}
760
761Tool *ToolChain::getLinkerWrapper() const {
762 if (!LinkerWrapper)
763 LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
764 return LinkerWrapper.get();
765}
766
768 switch (AC) {
770 return getAssemble();
771
773 return getIfsMerge();
774
776 return getLink();
777
779 return getStaticLibTool();
780
790 llvm_unreachable("Invalid tool kind.");
791
799 return getClang();
800
803 return getOffloadBundler();
804
806 return getOffloadPackager();
808 return getLinkerWrapper();
809 }
810
811 llvm_unreachable("Invalid tool kind.");
812}
813
814static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
815 const ArgList &Args) {
816 const llvm::Triple &Triple = TC.getTriple();
817 bool IsWindows = Triple.isOSWindows();
818
819 if (TC.isBareMetal())
820 return Triple.getArchName();
821
822 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
823 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
824 ? "armhf"
825 : "arm";
826
827 // For historic reasons, Android library is using i686 instead of i386.
828 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
829 return "i686";
830
831 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
832 return "x32";
833
834 return llvm::Triple::getArchTypeName(TC.getArch());
835}
836
837StringRef ToolChain::getOSLibName() const {
838 if (Triple.isOSDarwin())
839 return "darwin";
840
841 switch (Triple.getOS()) {
842 case llvm::Triple::FreeBSD:
843 return "freebsd";
844 case llvm::Triple::NetBSD:
845 return "netbsd";
846 case llvm::Triple::OpenBSD:
847 return "openbsd";
848 case llvm::Triple::Solaris:
849 return "sunos";
850 case llvm::Triple::AIX:
851 return "aix";
852 case llvm::Triple::Serenity:
853 return "serenity";
854 default:
855 return getOS();
856 }
857}
858
859std::string ToolChain::getCompilerRTPath() const {
860 SmallString<128> Path(getDriver().ResourceDir);
861 if (isBareMetal()) {
862 llvm::sys::path::append(Path, "lib", getOSLibName());
863 if (!SelectedMultilibs.empty()) {
864 Path += SelectedMultilibs.back().gccSuffix();
865 }
866 } else if (Triple.isOSUnknown()) {
867 llvm::sys::path::append(Path, "lib");
868 } else {
869 llvm::sys::path::append(Path, "lib", getOSLibName());
870 }
871 return std::string(Path);
872}
873
874std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
875 StringRef Component,
876 FileType Type) const {
877 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
878 return llvm::sys::path::filename(CRTAbsolutePath).str();
879}
880
881std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
882 StringRef Component,
883 FileType Type, bool AddArch,
884 bool IsFortran) const {
885 const llvm::Triple &TT = getTriple();
886 bool IsITANMSVCWindows =
887 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
888
889 const char *Prefix =
890 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
891 const char *Suffix;
892 switch (Type) {
894 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
895 break;
897 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
898 break;
900 if (TT.isOSWindows())
901 Suffix = TT.isOSCygMing() ? ".dll.a" : ".lib";
902 else if (TT.isOSAIX())
903 Suffix = ".a";
904 else
905 Suffix = ".so";
906 break;
907 }
908
909 std::string ArchAndEnv;
910 if (AddArch) {
911 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
912 const char *Env = TT.isAndroid() ? "-android" : "";
913 ArchAndEnv = ("-" + Arch + Env).str();
914 }
915
916 std::string LibName = IsFortran ? "flang_rt." : "clang_rt.";
917 return (Prefix + Twine(LibName) + Component + ArchAndEnv + Suffix).str();
918}
919
920std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
921 FileType Type, bool IsFortran) const {
922 // Check for runtime files in the new layout without the architecture first.
923 std::string CRTBasename = buildCompilerRTBasename(
924 Args, Component, Type, /*AddArch=*/false, IsFortran);
925 SmallString<128> Path;
926 for (const auto &LibPath : getLibraryPaths()) {
927 SmallString<128> P(LibPath);
928 llvm::sys::path::append(P, CRTBasename);
929 if (getVFS().exists(P))
930 return std::string(P);
931 if (Path.empty())
932 Path = P;
933 }
934
935 // Check the filename for the old layout if the new one does not exist.
936 CRTBasename = buildCompilerRTBasename(Args, Component, Type,
937 /*AddArch=*/!IsFortran, IsFortran);
939 llvm::sys::path::append(OldPath, CRTBasename);
940 if (Path.empty() || getVFS().exists(OldPath))
941 return std::string(OldPath);
942
943 // If none is found, use a file name from the new layout, which may get
944 // printed in an error message, aiding users in knowing what Clang is
945 // looking for.
946 return std::string(Path);
947}
948
949const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
950 StringRef Component,
952 bool isFortran) const {
953 return Args.MakeArgString(getCompilerRT(Args, Component, Type, isFortran));
954}
955
956/// Add Fortran runtime libs
957void ToolChain::addFortranRuntimeLibs(const ArgList &Args,
958 llvm::opt::ArgStringList &CmdArgs) const {
959 // Link flang_rt.runtime
960 // These are handled earlier on Windows by telling the frontend driver to
961 // add the correct libraries to link against as dependents in the object
962 // file.
963 if (!getTriple().isKnownWindowsMSVCEnvironment()) {
964 StringRef F128LibName = getDriver().getFlangF128MathLibrary();
965 F128LibName.consume_front_insensitive("lib");
966 if (!F128LibName.empty()) {
967 bool AsNeeded = !getTriple().isOSAIX();
968 CmdArgs.push_back("-lflang_rt.quadmath");
969 if (AsNeeded)
970 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/true);
971 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
972 if (AsNeeded)
973 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/false);
974 }
975 addFlangRTLibPath(Args, CmdArgs);
976
977 // needs libexecinfo for backtrace functions
978 if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() ||
979 getTriple().isOSOpenBSD() || getTriple().isOSDragonFly())
980 CmdArgs.push_back("-lexecinfo");
981 }
982
983 // libomp needs libatomic for atomic operations if using libgcc
984 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
985 options::OPT_fno_openmp, false)) {
988 if ((OMPRuntime == Driver::OMPRT_OMP &&
989 RuntimeLib == ToolChain::RLT_Libgcc) &&
990 !getTriple().isKnownWindowsMSVCEnvironment()) {
991 if (getTriple().isOSAIX())
992 CmdArgs.push_back("-lcompiler_rt");
993 else
994 CmdArgs.push_back("-latomic");
995 }
996 }
997}
998
999void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
1000 ArgStringList &CmdArgs) const {
1001 auto AddLibSearchPathIfExists = [&](const Twine &Path) {
1002 // Linker may emit warnings about non-existing directories
1003 if (!llvm::sys::fs::is_directory(Path))
1004 return;
1005
1006 if (getTriple().isKnownWindowsMSVCEnvironment())
1007 CmdArgs.push_back(Args.MakeArgString("-libpath:" + Path));
1008 else
1009 CmdArgs.push_back(Args.MakeArgString("-L" + Path));
1010 };
1011
1012 // Search for flang_rt.* at the same location as clang_rt.* with
1013 // LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is
1014 // located at the path returned by getRuntimePath() which is already added to
1015 // the library search path. This exception is for Apple-Darwin.
1016 AddLibSearchPathIfExists(getCompilerRTPath());
1017
1018 // Fall back to the non-resource directory <driver-path>/../lib. We will
1019 // probably have to refine this in the future. In particular, on some
1020 // platforms, we may need to use lib64 instead of lib.
1021 SmallString<256> DefaultLibPath =
1022 llvm::sys::path::parent_path(getDriver().Dir);
1023 llvm::sys::path::append(DefaultLibPath, "lib");
1024 AddLibSearchPathIfExists(DefaultLibPath);
1025}
1026
1027void ToolChain::addFlangRTLibPath(const ArgList &Args,
1028 llvm::opt::ArgStringList &CmdArgs) const {
1029 // Link static flang_rt.runtime.a or shared flang_rt.runtime.so.
1030 // On AIX, default to static flang-rt.
1031 if (Args.hasFlag(options::OPT_static_libflangrt,
1032 options::OPT_shared_libflangrt, getTriple().isOSAIX()))
1033 CmdArgs.push_back(
1034 getCompilerRTArgString(Args, "runtime", ToolChain::FT_Static, true));
1035 else {
1036 CmdArgs.push_back("-lflang_rt.runtime");
1037 addArchSpecificRPath(*this, Args, CmdArgs);
1038 }
1039}
1040
1041// Android target triples contain a target version. If we don't have libraries
1042// for the exact target version, we should fall back to the next newest version
1043// or a versionless path, if any.
1044std::optional<std::string>
1045ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
1046 llvm::Triple TripleWithoutLevel(getTriple());
1047 TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
1048 const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
1049 unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
1050 unsigned BestVersion = 0;
1051
1052 SmallString<32> TripleDir;
1053 bool UsingUnversionedDir = false;
1054 std::error_code EC;
1055 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
1056 !EC && LI != LE; LI = LI.increment(EC)) {
1057 StringRef DirName = llvm::sys::path::filename(LI->path());
1058 StringRef DirNameSuffix = DirName;
1059 if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
1060 if (DirNameSuffix.empty() && TripleDir.empty()) {
1061 TripleDir = DirName;
1062 UsingUnversionedDir = true;
1063 } else {
1064 unsigned Version;
1065 if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
1066 Version < TripleVersion) {
1067 BestVersion = Version;
1068 TripleDir = DirName;
1069 UsingUnversionedDir = false;
1070 }
1071 }
1072 }
1073 }
1074
1075 if (TripleDir.empty())
1076 return {};
1077
1078 SmallString<128> P(BaseDir);
1079 llvm::sys::path::append(P, TripleDir);
1080 if (UsingUnversionedDir)
1081 D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
1082 return std::string(P);
1083}
1084
1086 return (Triple.hasEnvironment()
1087 ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
1088 llvm::Triple::getOSTypeName(Triple.getOS()),
1089 llvm::Triple::getEnvironmentTypeName(
1090 Triple.getEnvironment()))
1091 : llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
1092 llvm::Triple::getOSTypeName(Triple.getOS())));
1093}
1094
1095std::optional<std::string>
1096ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
1097 auto getPathForTriple =
1098 [&](const llvm::Triple &Triple) -> std::optional<std::string> {
1099 SmallString<128> P(BaseDir);
1100 llvm::sys::path::append(P, Triple.str());
1101 if (getVFS().exists(P))
1102 return std::string(P);
1103 return {};
1104 };
1105
1106 const llvm::Triple &T = getTriple();
1107 if (auto Path = getPathForTriple(T))
1108 return *Path;
1109
1110 if (T.isOSAIX()) {
1111 llvm::Triple AIXTriple;
1112 if (T.getEnvironment() == Triple::UnknownEnvironment) {
1113 // Strip unknown environment and the OS version from the triple.
1114 AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(),
1115 llvm::Triple::getOSTypeName(T.getOS()));
1116 } else {
1117 // Strip the OS version from the triple.
1118 AIXTriple = getTripleWithoutOSVersion();
1119 }
1120 if (auto Path = getPathForTriple(AIXTriple))
1121 return *Path;
1122 }
1123
1124 if (T.isOSzOS() &&
1125 (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) {
1126 // Build the triple without version information
1127 const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion();
1128 if (auto Path = getPathForTriple(TripleWithoutVersion))
1129 return *Path;
1130 }
1131
1132 // When building with per target runtime directories, various ways of naming
1133 // the Arm architecture may have been normalised to simply "arm".
1134 // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
1135 // Since an armv8l system can use libraries built for earlier architecture
1136 // versions assuming endian and float ABI match.
1137 //
1138 // Original triple: armv8l-unknown-linux-gnueabihf
1139 // Runtime triple: arm-unknown-linux-gnueabihf
1140 //
1141 // We do not do this for armeb (big endian) because doing so could make us
1142 // select little endian libraries. In addition, all known armeb triples only
1143 // use the "armeb" architecture name.
1144 //
1145 // M profile Arm is bare metal and we know they will not be using the per
1146 // target runtime directory layout.
1147 if (T.getArch() == Triple::arm && !T.isArmMClass()) {
1148 llvm::Triple ArmTriple = T;
1149 ArmTriple.setArch(Triple::arm);
1150 if (auto Path = getPathForTriple(ArmTriple))
1151 return *Path;
1152 }
1153
1154 if (T.isAndroid())
1155 return getFallbackAndroidTargetPath(BaseDir);
1156
1157 return {};
1158}
1159
1160std::optional<std::string> ToolChain::getDefaultIntrinsicModuleDir() const {
1161 SmallString<128> P(D.ResourceDir);
1162 llvm::sys::path::append(P, "finclude", "flang");
1163 return getTargetSubDirPath(P);
1164}
1165
1166std::optional<std::string> ToolChain::getRuntimePath() const {
1167 SmallString<128> P(D.ResourceDir);
1168 llvm::sys::path::append(P, "lib");
1169 if (auto Ret = getTargetSubDirPath(P))
1170 return Ret;
1171 // Darwin does not use per-target runtime directory.
1172 if (Triple.isOSDarwin())
1173 return {};
1174
1175 llvm::sys::path::append(P, Triple.str());
1176 return std::string(P);
1177}
1178
1179std::optional<std::string> ToolChain::getStdlibPath() const {
1180 SmallString<128> P(D.Dir);
1181 llvm::sys::path::append(P, "..", "lib");
1182 return getTargetSubDirPath(P);
1183}
1184
1185std::optional<std::string> ToolChain::getStdlibIncludePath() const {
1186 SmallString<128> P(D.Dir);
1187 llvm::sys::path::append(P, "..", "include");
1188 return getTargetSubDirPath(P);
1189}
1190
1192 path_list Paths;
1193
1194 auto AddPath = [&](const ArrayRef<StringRef> &SS) {
1195 SmallString<128> Path(getDriver().ResourceDir);
1196 llvm::sys::path::append(Path, "lib");
1197 for (auto &S : SS)
1198 llvm::sys::path::append(Path, S);
1199 Paths.push_back(std::string(Path));
1200 };
1201
1202 AddPath({getTriple().str()});
1203 AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
1204 return Paths;
1205}
1206
1207bool ToolChain::needsProfileRT(const ArgList &Args) {
1208 if (Args.hasArg(options::OPT_noprofilelib))
1209 return false;
1210
1211 return Args.hasArg(options::OPT_fprofile_generate) ||
1212 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
1213 Args.hasArg(options::OPT_fcs_profile_generate) ||
1214 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
1215 Args.hasArg(options::OPT_fprofile_instr_generate) ||
1216 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
1217 Args.hasArg(options::OPT_fcreate_profile) ||
1218 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage) ||
1219 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage_EQ);
1220}
1221
1222bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
1223 return Args.hasArg(options::OPT_coverage) ||
1224 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
1225 false);
1226}
1227
1229 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
1230 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
1231 Action::ActionClass AC = JA.getKind();
1233 !getTriple().isOSAIX())
1234 return getClangAs();
1235 return getTool(AC);
1236}
1237
1238std::string ToolChain::GetFilePath(const char *Name) const {
1239 return D.GetFilePath(Name, *this);
1240}
1241
1242std::string ToolChain::GetProgramPath(const char *Name) const {
1243 return D.GetProgramPath(Name, *this);
1244}
1245
1246std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
1247 if (LinkerIsLLD)
1248 *LinkerIsLLD = false;
1249
1250 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
1251 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
1252 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
1253 StringRef UseLinker = A ? A->getValue() : getDriver().getPreferredLinker();
1254
1255 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
1256 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
1257 // contain a path component separator.
1258 // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
1259 // that --ld-path= points to is lld.
1260 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
1261 std::string Path(A->getValue());
1262 if (!Path.empty()) {
1263 if (llvm::sys::path::parent_path(Path).empty())
1264 Path = GetProgramPath(A->getValue());
1265 if (llvm::sys::fs::can_execute(Path)) {
1266 if (LinkerIsLLD)
1267 *LinkerIsLLD = UseLinker == "lld";
1268 return std::string(Path);
1269 }
1270 }
1271 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1273 }
1274 // If we're passed -fuse-ld= with no argument, or with the argument ld,
1275 // then use whatever the default system linker is.
1276 if (UseLinker.empty() || UseLinker == "ld") {
1277 const char *DefaultLinker = getDefaultLinker();
1278 if (llvm::sys::path::is_absolute(DefaultLinker))
1279 return std::string(DefaultLinker);
1280 else
1281 return GetProgramPath(DefaultLinker);
1282 }
1283
1284 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
1285 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
1286 // to a relative path is surprising. This is more complex due to priorities
1287 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
1288 if (UseLinker.contains('/'))
1289 getDriver().Diag(diag::warn_drv_fuse_ld_path);
1290
1291 if (llvm::sys::path::is_absolute(UseLinker)) {
1292 // If we're passed what looks like an absolute path, don't attempt to
1293 // second-guess that.
1294 if (llvm::sys::fs::can_execute(UseLinker))
1295 return std::string(UseLinker);
1296 } else {
1297 llvm::SmallString<8> LinkerName;
1298 if (Triple.isOSDarwin())
1299 LinkerName.append("ld64.");
1300 else
1301 LinkerName.append("ld.");
1302 LinkerName.append(UseLinker);
1303
1304 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
1305 if (llvm::sys::fs::can_execute(LinkerPath)) {
1306 if (LinkerIsLLD)
1307 *LinkerIsLLD = UseLinker == "lld";
1308 return LinkerPath;
1309 }
1310 }
1311
1312 if (A)
1313 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1314
1316}
1317
1319 // TODO: Add support for static lib archiving on Windows
1320 if (Triple.isOSDarwin())
1321 return GetProgramPath("libtool");
1322 return GetProgramPath("llvm-ar");
1323}
1324
1327
1328 // Flang always runs the preprocessor and has no notion of "preprocessed
1329 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
1330 // them differently.
1331 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
1332 id = types::TY_Fortran;
1333
1334 return id;
1335}
1336
1338 return false;
1339}
1340
1342
1343bool ToolChain::isUsingLTO(const llvm::opt::ArgList &Args,
1344 Action::OffloadKind Kind) const {
1345 return getLTOMode(Args, Kind) != LTOK_None;
1346}
1347
1348static LTOKind parseLTOMode(const llvm::opt::ArgList &Args,
1349 llvm::opt::OptSpecifier OptEq,
1350 llvm::opt::OptSpecifier OptNeg) {
1351 if (!Args.hasFlag(OptEq, OptNeg, false))
1352 return LTOK_None;
1353
1354 const Arg *A = Args.getLastArg(OptEq);
1355 StringRef LTOName = A->getValue();
1356
1357 return llvm::StringSwitch<LTOKind>(LTOName)
1358 .Case("full", LTOK_Full)
1359 .Case("thin", LTOK_Thin)
1360 .Case("none", LTOK_None)
1361 .Default(LTOK_Unknown);
1362}
1363
1364LTOKind ToolChain::getLTOMode(const llvm::opt::ArgList &Args,
1365 Action::OffloadKind Kind) const {
1366 bool IsOffload = Kind != Action::OFK_None;
1367 auto OptEq = IsOffload ? options::OPT_foffload_lto_EQ : options::OPT_flto_EQ;
1368 auto OptNeg = IsOffload ? options::OPT_fno_offload_lto : options::OPT_fno_lto;
1369
1370 // -fopenmp-target-jit implies -foffload-lto=full for device compilations,
1371 // overriding any explicit -fno-offload-lto.
1372 if (IsOffload && Args.hasFlag(options::OPT_fopenmp_target_jit,
1373 options::OPT_fno_openmp_target_jit, false)) {
1374 if (Arg *A = Args.getLastArg(OptEq, OptNeg))
1375 if (parseLTOMode(Args, OptEq, OptNeg) != LTOK_Full)
1376 getDriver().Diag(diag::err_drv_incompatible_options)
1377 << A->getSpelling() << "-fopenmp-target-jit";
1378 return LTOK_Full;
1379 }
1380
1381 if (!Args.hasArg(OptEq, OptNeg))
1382 return getDefaultLTOMode();
1383
1384 LTOKind Mode = parseLTOMode(Args, OptEq, OptNeg);
1385
1386 if (Mode == LTOK_Unknown) {
1387 const Arg *A = Args.getLastArg(OptEq);
1388 getDriver().Diag(diag::err_drv_unsupported_option_argument)
1389 << A->getSpelling() << A->getValue();
1390 return LTOK_None;
1391 }
1392 return Mode;
1393}
1394
1396 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
1397 switch (HostTriple.getArch()) {
1398 // The A32/T32/T16 instruction sets are not separate architectures in this
1399 // context.
1400 case llvm::Triple::arm:
1401 case llvm::Triple::armeb:
1402 case llvm::Triple::thumb:
1403 case llvm::Triple::thumbeb:
1404 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
1405 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
1406 default:
1407 return HostTriple.getArch() != getArch();
1408 }
1409}
1410
1412 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
1413 VersionTuple());
1414}
1415
1416llvm::ExceptionHandling
1417ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
1418 return llvm::ExceptionHandling::None;
1419}
1420
1421bool ToolChain::isThreadModelSupported(const StringRef Model) const {
1422 if (Model == "single") {
1423 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
1424 return Triple.getArch() == llvm::Triple::arm ||
1425 Triple.getArch() == llvm::Triple::armeb ||
1426 Triple.getArch() == llvm::Triple::thumb ||
1427 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
1428 } else if (Model == "posix")
1429 return true;
1430
1431 return false;
1432}
1433
1434std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
1435 StringRef BoundArch,
1436 types::ID InputType) const {
1437 switch (getTriple().getArch()) {
1438 default:
1439 return getTripleString().str();
1440
1441 case llvm::Triple::x86_64: {
1442 llvm::Triple Triple = getTriple();
1443 if (!Triple.isOSBinFormatMachO())
1444 return getTripleString().str();
1445
1446 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1447 // x86_64h goes in the triple. Other -march options just use the
1448 // vanilla triple we already have.
1449 StringRef MArch = A->getValue();
1450 if (MArch == "x86_64h")
1451 Triple.setArchName(MArch);
1452 }
1453 return Triple.getTriple();
1454 }
1455 case llvm::Triple::aarch64: {
1456 llvm::Triple Triple = getTriple();
1457 if (!Triple.isOSBinFormatMachO())
1458 return Triple.getTriple();
1459
1460 if (Triple.isArm64e())
1461 return Triple.getTriple();
1462
1463 // FIXME: older versions of ld64 expect the "arm64" component in the actual
1464 // triple string and query it to determine whether an LTO file can be
1465 // handled. Remove this when we don't care any more.
1466 Triple.setArchName("arm64");
1467 return Triple.getTriple();
1468 }
1469 case llvm::Triple::aarch64_32:
1470 return getTripleString().str();
1471 case llvm::Triple::amdgcn: {
1472 llvm::Triple Triple = getTriple();
1473 tools::AMDGPU::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1474 return Triple.getTriple();
1475 }
1476 case llvm::Triple::arm:
1477 case llvm::Triple::armeb:
1478 case llvm::Triple::thumb:
1479 case llvm::Triple::thumbeb: {
1480 llvm::Triple Triple = getTriple();
1481 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1483 return Triple.getTriple();
1484 }
1485 }
1486}
1487
1488std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1489 StringRef BoundArch,
1490 types::ID InputType) const {
1491 return ComputeLLVMTriple(Args, BoundArch, InputType);
1492}
1493
1494std::string ToolChain::computeSysRoot() const {
1495 return D.SysRoot;
1496}
1497
1498void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1499 ArgStringList &CC1Args) const {
1500 // Each toolchain should provide the appropriate include flags.
1501}
1502
1504 const ArgList &DriverArgs, ArgStringList &CC1Args, StringRef BoundArch,
1505 Action::OffloadKind DeviceOffloadKind) const {}
1506
1508 ArgStringList &CC1ASArgs) const {}
1509
1510void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1511
1512void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1513 llvm::opt::ArgStringList &CmdArgs) const {
1514 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1515 return;
1516
1517 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1518}
1519
1521 const ArgList &Args) const {
1522 if (runtimeLibType)
1523 return *runtimeLibType;
1524
1525 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1526 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1527
1528 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1529 if (LibName == "compiler-rt")
1530 runtimeLibType = ToolChain::RLT_CompilerRT;
1531 else if (LibName == "libgcc")
1532 runtimeLibType = ToolChain::RLT_Libgcc;
1533 else if (LibName == "platform")
1534 runtimeLibType = GetDefaultRuntimeLibType();
1535 else {
1536 if (A)
1537 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1538 << A->getAsString(Args);
1539
1540 runtimeLibType = GetDefaultRuntimeLibType();
1541 }
1542
1543 return *runtimeLibType;
1544}
1545
1547 const ArgList &Args) const {
1548 if (unwindLibType)
1549 return *unwindLibType;
1550
1551 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1552 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1553
1554 if (LibName == "none")
1555 unwindLibType = ToolChain::UNW_None;
1556 else if (LibName == "platform" || LibName == "") {
1558 if (RtLibType == ToolChain::RLT_CompilerRT) {
1559 if (getTriple().isAndroid() || getTriple().isOSAIX() ||
1560 getTriple().isOSSerenity())
1561 unwindLibType = ToolChain::UNW_CompilerRT;
1562 else
1563 unwindLibType = ToolChain::UNW_None;
1564 } else if (RtLibType == ToolChain::RLT_Libgcc)
1565 unwindLibType = ToolChain::UNW_Libgcc;
1566 } else if (LibName == "libunwind") {
1567 if (GetRuntimeLibType(Args) == RLT_Libgcc)
1568 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1569 unwindLibType = ToolChain::UNW_CompilerRT;
1570 } else if (LibName == "libgcc")
1571 unwindLibType = ToolChain::UNW_Libgcc;
1572 else {
1573 if (A)
1574 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1575 << A->getAsString(Args);
1576
1577 unwindLibType = GetDefaultUnwindLibType();
1578 }
1579
1580 return *unwindLibType;
1581}
1582
1584 if (cxxStdlibType)
1585 return *cxxStdlibType;
1586
1587 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1588 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1589
1590 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1591 if (LibName == "libc++")
1592 cxxStdlibType = ToolChain::CST_Libcxx;
1593 else if (LibName == "libstdc++")
1594 cxxStdlibType = ToolChain::CST_Libstdcxx;
1595 else if (LibName == "platform")
1596 cxxStdlibType = GetDefaultCXXStdlibType();
1597 else {
1598 if (A)
1599 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1600 << A->getAsString(Args);
1601
1602 cxxStdlibType = GetDefaultCXXStdlibType();
1603 }
1604
1605 return *cxxStdlibType;
1606}
1607
1609 if (cStdlibType)
1610 return *cStdlibType;
1611
1612 const Arg *A = Args.getLastArg(options::OPT_cstdlib_EQ);
1613 StringRef LibName = A ? A->getValue() : "system";
1614
1615 if (LibName == "newlib")
1616 cStdlibType = ToolChain::CST_Newlib;
1617 else if (LibName == "picolibc")
1618 cStdlibType = ToolChain::CST_Picolibc;
1619 else if (LibName == "llvm-libc")
1620 cStdlibType = ToolChain::CST_LLVMLibC;
1621 else if (LibName == "system")
1622 cStdlibType = ToolChain::CST_System;
1623 else {
1624 if (A)
1625 getDriver().Diag(diag::err_drv_invalid_cstdlib_name)
1626 << A->getAsString(Args);
1627 cStdlibType = ToolChain::CST_System;
1628 }
1629
1630 return *cStdlibType;
1631}
1632
1633/// Utility function to add a system framework directory to CC1 arguments.
1634void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs,
1635 llvm::opt::ArgStringList &CC1Args,
1636 const Twine &Path) {
1637 CC1Args.push_back("-internal-iframework");
1638 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1639}
1640
1641/// Utility function to add a system include directory with extern "C"
1642/// semantics to CC1 arguments.
1643///
1644/// Note that this should be used rarely, and only for directories that
1645/// historically and for legacy reasons are treated as having implicit extern
1646/// "C" semantics. These semantics are *ignored* by and large today, but its
1647/// important to preserve the preprocessor changes resulting from the
1648/// classification.
1649void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1650 ArgStringList &CC1Args,
1651 const Twine &Path) {
1652 CC1Args.push_back("-internal-externc-isystem");
1653 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1654}
1655
1656void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1657 ArgStringList &CC1Args,
1658 const Twine &Path) {
1659 if (llvm::sys::fs::exists(Path))
1660 addExternCSystemInclude(DriverArgs, CC1Args, Path);
1661}
1662
1663/// Utility function to add a system include directory to CC1 arguments.
1664/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1665 ArgStringList &CC1Args,
1666 const Twine &Path) {
1667 CC1Args.push_back("-internal-isystem");
1668 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1669}
1670
1671/// Utility function to add a list of system framework directories to CC1.
1672void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs,
1673 ArgStringList &CC1Args,
1674 ArrayRef<StringRef> Paths) {
1675 for (const auto &Path : Paths) {
1676 CC1Args.push_back("-internal-iframework");
1677 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1678 }
1679}
1680
1681/// Utility function to add a list of system include directories to CC1.
1682void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1683 ArgStringList &CC1Args,
1684 ArrayRef<StringRef> Paths) {
1685 for (const auto &Path : Paths) {
1686 CC1Args.push_back("-internal-isystem");
1687 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1688 }
1689}
1690
1691std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B,
1692 const Twine &C, const Twine &D) {
1694 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1695 return std::string(Result);
1696}
1697
1698std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1699 std::error_code EC;
1700 int MaxVersion = 0;
1701 std::string MaxVersionString;
1702 SmallString<128> Path(IncludePath);
1703 llvm::sys::path::append(Path, "c++");
1704 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1705 !EC && LI != LE; LI = LI.increment(EC)) {
1706 StringRef VersionText = llvm::sys::path::filename(LI->path());
1707 int Version;
1708 if (VersionText[0] == 'v' &&
1709 !VersionText.substr(1).getAsInteger(10, Version)) {
1710 if (Version > MaxVersion) {
1711 MaxVersion = Version;
1712 MaxVersionString = std::string(VersionText);
1713 }
1714 }
1715 }
1716 if (!MaxVersion)
1717 return "";
1718 return MaxVersionString;
1719}
1720
1721void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1722 ArgStringList &CC1Args) const {
1723 // Header search paths should be handled by each of the subclasses.
1724 // Historically, they have not been, and instead have been handled inside of
1725 // the CC1-layer frontend. As the logic is hoisted out, this generic function
1726 // will slowly stop being called.
1727 //
1728 // While it is being called, replicate a bit of a hack to propagate the
1729 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1730 // header search paths with it. Once all systems are overriding this
1731 // function, the CC1 flag and this line can be removed.
1732 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1733}
1734
1736 const llvm::opt::ArgList &DriverArgs,
1737 llvm::opt::ArgStringList &CC1Args) const {
1738 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1739 // This intentionally only looks at -nostdinc++, and not -nostdinc or
1740 // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1741 // setups with non-standard search logic for the C++ headers, while still
1742 // allowing users of the toolchain to bring their own C++ headers. Such a
1743 // toolchain likely also has non-standard search logic for the C headers and
1744 // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1745 // still work in that case and only be suppressed by an explicit -nostdinc++
1746 // in a project using the toolchain.
1747 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1748 for (const auto &P :
1749 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1750 addSystemInclude(DriverArgs, CC1Args, P);
1751}
1752
1753bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1754 return getDriver().CCCIsCXX() &&
1755 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1756 options::OPT_nostdlibxx);
1757}
1758
1759void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1760 ArgStringList &CmdArgs) const {
1761 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1762 "should not have called this");
1764
1765 switch (Type) {
1767 CmdArgs.push_back("-lc++");
1768 if (Args.hasArg(options::OPT_fexperimental_library))
1769 CmdArgs.push_back("-lc++experimental");
1770 break;
1771
1773 CmdArgs.push_back("-lstdc++");
1774 break;
1775 }
1776}
1777
1778void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1779 ArgStringList &CmdArgs) const {
1780 for (const auto &LibPath : getFilePaths())
1781 if(LibPath.length() > 0)
1782 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1783}
1784
1785void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1786 ArgStringList &CmdArgs) const {
1787 CmdArgs.push_back("-lcc_kext");
1788}
1789
1791 std::string &Path) const {
1792 // Don't implicitly link in mode-changing libraries in a shared library, since
1793 // this can have very deleterious effects. See the various links from
1794 // https://github.com/llvm/llvm-project/issues/57589 for more information.
1795 bool Default = !Args.hasArgNoClaim(options::OPT_shared);
1796
1797 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1798 // (to keep the linker options consistent with gcc and clang itself).
1799 if (Default && !isOptimizationLevelFast(Args)) {
1800 // Check if -ffast-math or -funsafe-math.
1801 Arg *A = Args.getLastArg(
1802 options::OPT_ffast_math, options::OPT_fno_fast_math,
1803 options::OPT_funsafe_math_optimizations,
1804 options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ);
1805
1806 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1807 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1808 Default = false;
1809 if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) {
1810 StringRef Model = A->getValue();
1811 if (Model != "fast" && Model != "aggressive")
1812 Default = false;
1813 }
1814 }
1815
1816 // Whatever decision came as a result of the above implicit settings, either
1817 // -mdaz-ftz or -mno-daz-ftz is capable of overriding it.
1818 if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default))
1819 return false;
1820
1821 // If crtfastmath.o exists add it to the arguments.
1822 Path = GetFilePath("crtfastmath.o");
1823 return (Path != "crtfastmath.o"); // Not found.
1824}
1825
1827 ArgStringList &CmdArgs) const {
1828 std::string Path;
1829 if (isFastMathRuntimeAvailable(Args, Path)) {
1830 CmdArgs.push_back(Args.MakeArgString(Path));
1831 return true;
1832 }
1833
1834 return false;
1835}
1836
1838ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1839 return SmallVector<std::string>();
1840}
1841
1844 Action::OffloadKind DeviceOffloadKind) const {
1845 // Return sanitizers which don't require runtime support and are not
1846 // platform dependent.
1847
1848 SanitizerMask Res =
1849 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1850 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1851 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1852 SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1853 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1854 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
1855 SanitizerKind::AllocToken;
1856 if (getTriple().getArch() == llvm::Triple::x86 ||
1857 getTriple().getArch() == llvm::Triple::x86_64 ||
1858 getTriple().getArch() == llvm::Triple::arm ||
1859 getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() ||
1860 getTriple().isAArch64() || getTriple().isRISCV() ||
1861 getTriple().isLoongArch64() ||
1862 getTriple().getArch() == llvm::Triple::hexagon)
1863 Res |= SanitizerKind::CFIICall;
1864 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1865 getTriple().isAArch64(64) || getTriple().isRISCV())
1866 Res |= SanitizerKind::ShadowCallStack;
1867 if (getTriple().isAArch64(64))
1868 Res |= SanitizerKind::MemTag;
1869 if (getTriple().isBPF())
1870 Res |= SanitizerKind::KernelAddress;
1871 return Res;
1872}
1873
1874void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1875 ArgStringList &CC1Args) const {}
1876
1877void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1878 ArgStringList &CC1Args) const {}
1879
1880void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
1881 ArgStringList &CC1Args) const {}
1882
1884ToolChain::getDeviceLibs(const ArgList &DriverArgs, StringRef BoundArch,
1885 const Action::OffloadKind DeviceOffloadingKind) const {
1886 return {};
1887}
1888
1889void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1890 ArgStringList &CC1Args) const {}
1891
1892static VersionTuple separateMSVCFullVersion(unsigned Version) {
1893 if (Version < 100)
1894 return VersionTuple(Version);
1895
1896 if (Version < 10000)
1897 return VersionTuple(Version / 100, Version % 100);
1898
1899 unsigned Build = 0, Factor = 1;
1900 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1901 Build = Build + (Version % 10) * Factor;
1902 return VersionTuple(Version / 100, Version % 100, Build);
1903}
1904
1905VersionTuple
1907 const llvm::opt::ArgList &Args) const {
1908 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1909 const Arg *MSCompatibilityVersion =
1910 Args.getLastArg(options::OPT_fms_compatibility_version);
1911
1912 if (MSCVersion && MSCompatibilityVersion) {
1913 if (D)
1914 D->Diag(diag::err_drv_argument_not_allowed_with)
1915 << MSCVersion->getAsString(Args)
1916 << MSCompatibilityVersion->getAsString(Args);
1917 return VersionTuple();
1918 }
1919
1920 if (MSCompatibilityVersion) {
1921 VersionTuple MSVT;
1922 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1923 if (D)
1924 D->Diag(diag::err_drv_invalid_value)
1925 << MSCompatibilityVersion->getAsString(Args)
1926 << MSCompatibilityVersion->getValue();
1927 } else {
1928 return MSVT;
1929 }
1930 }
1931
1932 if (MSCVersion) {
1933 unsigned Version = 0;
1934 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1935 if (D)
1936 D->Diag(diag::err_drv_invalid_value)
1937 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1938 } else {
1939 return separateMSVCFullVersion(Version);
1940 }
1941 }
1942
1943 return VersionTuple();
1944}
1945
1946llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1947 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1948 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1949 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1950 const OptTable &Opts = getDriver().getOpts();
1951 bool Modified = false;
1952
1953 // Handle -Xopenmp-target flags
1954 for (auto *A : Args) {
1955 // Exclude flags which may only apply to the host toolchain.
1956 // Do not exclude flags when the host triple (AuxTriple)
1957 // matches the current toolchain triple. If it is not present
1958 // at all, target and host share a toolchain.
1959 if (A->getOption().matches(options::OPT_m_Group)) {
1960 // Pass certain options to the device toolchain even when the triple
1961 // differs from the host: code object version must be passed to correctly
1962 // set metadata in intermediate files; linker version must be passed
1963 // because the Darwin toolchain requires the host and device linker
1964 // versions to match (the host version is cached in
1965 // MachO::getLinkerVersion).
1966 if (SameTripleAsHost ||
1967 A->getOption().matches(options::OPT_mcode_object_version_EQ) ||
1968 A->getOption().matches(options::OPT_mlinker_version_EQ))
1969 DAL->append(A);
1970 else
1971 Modified = true;
1972 continue;
1973 }
1974
1975 unsigned Index;
1976 unsigned Prev;
1977 bool XOpenMPTargetNoTriple =
1978 A->getOption().matches(options::OPT_Xopenmp_target);
1979
1980 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1981 llvm::Triple TT = normalizeOffloadTriple(A->getValue(0));
1982
1983 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1984 if (TT.isCompatibleWith(getTriple()))
1985 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1986 else
1987 continue;
1988 } else if (XOpenMPTargetNoTriple) {
1989 // Passing device args: -Xopenmp-target -opt=val.
1990 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1991 } else {
1992 DAL->append(A);
1993 continue;
1994 }
1995
1996 // Parse the argument to -Xopenmp-target.
1997 Prev = Index;
1998 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1999 if (!XOpenMPTargetArg || Index > Prev + 1) {
2000 if (!A->isClaimed()) {
2001 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
2002 << A->getAsString(Args);
2003 }
2004 continue;
2005 }
2006 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
2007 Args.getAllArgValues(options::OPT_offload_targets_EQ).size() != 1) {
2008 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
2009 continue;
2010 }
2011 XOpenMPTargetArg->setBaseArg(A);
2012 A = XOpenMPTargetArg.release();
2013 AllocatedArgs.push_back(A);
2014 DAL->append(A);
2015 Modified = true;
2016 }
2017
2018 if (Modified)
2019 return DAL;
2020
2021 delete DAL;
2022 return nullptr;
2023}
2024
2025// TODO: Currently argument values separated by space e.g.
2026// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
2027// fixed.
2029 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
2030 llvm::opt::DerivedArgList *DAL,
2031 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
2032 const OptTable &Opts = getDriver().getOpts();
2033 unsigned ValuePos = 1;
2034 if (A->getOption().matches(options::OPT_Xarch_device) ||
2035 A->getOption().matches(options::OPT_Xarch_host))
2036 ValuePos = 0;
2037
2038 const InputArgList &BaseArgs = Args.getBaseArgs();
2039 unsigned Index = BaseArgs.MakeIndex(A->getValue(ValuePos));
2040 unsigned Prev = Index;
2041 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(
2042 Args, Index, llvm::opt::Visibility(options::ClangOption)));
2043
2044 // If the argument parsing failed or more than one argument was
2045 // consumed, the -Xarch_ argument's parameter tried to consume
2046 // extra arguments. Emit an error and ignore.
2047 //
2048 // We also want to disallow any options which would alter the
2049 // driver behavior; that isn't going to work in our model. We
2050 // use options::NoXarchOption to control this.
2051 if (!XarchArg || Index > Prev + 1) {
2052 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2053 << A->getAsString(Args);
2054 return;
2055 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
2056 auto &Diags = getDriver().getDiags();
2057 unsigned DiagID =
2059 "invalid Xarch argument: '%0', not all driver "
2060 "options can be forwared via Xarch argument");
2061 Diags.Report(DiagID) << A->getAsString(Args);
2062 return;
2063 }
2064
2065 XarchArg->setBaseArg(A);
2066 A = XarchArg.release();
2067
2068 // Linker input arguments require custom handling. The problem is that we
2069 // have already constructed the phase actions, so we can not treat them as
2070 // "input arguments".
2071 if (A->getOption().hasFlag(options::LinkerInput)) {
2072 // Convert the argument into individual Zlinker_input_args. Need to do this
2073 // manually to avoid memory leaks with the allocated arguments.
2074 for (const char *Value : A->getValues()) {
2075 auto Opt = Opts.getOption(options::OPT_Zlinker_input);
2076 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
2077 auto NewArg =
2078 new Arg(Opt, BaseArgs.MakeArgString(Opt.getPrefix() + Opt.getName()),
2079 Index, BaseArgs.getArgString(Index + 1), A);
2080
2081 DAL->append(NewArg);
2082 if (!AllocatedArgs)
2083 DAL->AddSynthesizedArg(NewArg);
2084 else
2085 AllocatedArgs->push_back(NewArg);
2086 }
2087 }
2088
2089 if (!AllocatedArgs)
2090 DAL->AddSynthesizedArg(A);
2091 else
2092 AllocatedArgs->push_back(A);
2093}
2094
2095/// Match any triple recognized arch aliases.
2096static bool isXArchCompatibleTripleArch(const llvm::Triple &TT,
2097 StringRef XArchVal) {
2098 llvm::Triple ParsedTriple(XArchVal);
2099 return TT.getArch() == ParsedTriple.getArch() &&
2100 TT.getSubArch() == ParsedTriple.getSubArch();
2101}
2102
2103llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
2104 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
2106 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
2107 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2108 bool Modified = false;
2109
2110 bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
2111 for (Arg *A : Args) {
2112 bool NeedTrans = false;
2113 bool Skip = false;
2114 if (A->getOption().matches(options::OPT_Xarch_device)) {
2115 NeedTrans = IsDevice;
2116 Skip = !IsDevice;
2117 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
2118 NeedTrans = !IsDevice;
2119 Skip = IsDevice;
2120 } else if (A->getOption().matches(options::OPT_Xarch__)) {
2121 StringRef Val = A->getValue();
2122 NeedTrans = Val == getArchName() ||
2123 (!BoundArch.empty() && Val == BoundArch) ||
2124 isXArchCompatibleTripleArch(Triple, Val);
2125 Skip = !NeedTrans;
2126 }
2127 if (NeedTrans || Skip)
2128 Modified = true;
2129 if (NeedTrans) {
2130 A->claim();
2131 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
2132 }
2133 if (!Skip)
2134 DAL->append(A);
2135 }
2136
2137 if (Modified)
2138 return DAL;
2139
2140 delete DAL;
2141 return nullptr;
2142}
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:914
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:152
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:94
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:849
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:158
StringRef getFlangF128MathLibrary() const
Definition Driver.h:450
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:406
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:410
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:144
StringRef getPreferredLinker() const
Definition Driver.h:432
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:221
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:95
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:904
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 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:495
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:325
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
StringRef getOS() const
Definition ToolChain.h:304
virtual bool isBareMetal() const
isBareMetal - Is this a bare metal target.
Definition ToolChain.h:707
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:301
const Driver & getDriver() const
Definition ToolChain.h:285
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:368
ExceptionsMode getExceptionsMode() const
Definition ToolChain.h:371
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:217
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 SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
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...
virtual llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, llvm::StringRef BoundArch, const Action::OffloadKind DeviceOffloadingKind) const
Get paths for device libraries.
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:491
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition ToolChain.h:546
virtual Tool * buildLinker() const
const llvm::Triple & getTriple() const
Definition ToolChain.h:287
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:219
StringRef getTripleString() const
Definition ToolChain.h:310
virtual std::string getCompilerRTPath() const
llvm::Triple getTripleWithoutOSVersion() const
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type, bool AddArch, bool IsFortran=false) const
virtual Expected< SmallVector< std::string > > getSystemGPUArchs(const llvm::opt::ArgList &Args) const
getSystemGPUArchs - Use a tool to detect the user's availible GPUs.
std::string GetProgramPath(const char *Name) const
static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system include directories to CC1.
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
virtual void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific SYCL includes.
virtual StringRef getOSLibName() const
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
virtual CXXStdlibType GetDefaultCXXStdlibType() const
Definition ToolChain.h:553
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:549
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:487
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
llvm::SmallVector< Multilib > SelectedMultilibs
Definition ToolChain.h:216
path_list & getLibraryPaths()
Definition ToolChain.h:322
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:557
std::optional< std::string > getRuntimePath() const
virtual Tool * getTool(Action::ActionClass AC) const
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, StringRef BoundArch={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, StringRef BoundArch={}, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, StringRef BoundArch="", Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
friend class RegisterEffectiveTriple
Definition ToolChain.h:148
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:499
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:302
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:97
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:58
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
Helper structure used to pass information extracted from clang executable name such as i686-linux-and...
Definition ToolChain.h:68