1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/ToolChain.h"
10 #include "InputInfo.h"
11 #include "ToolChains/Arch/ARM.h"
12 #include "ToolChains/Clang.h"
13 #include "clang/Basic/ObjCRuntime.h"
14 #include "clang/Basic/Sanitizers.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Job.h"
20 #include "clang/Driver/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/XRayArgs.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Config/llvm-config.h"
29 #include "llvm/MC/MCTargetOptions.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptTable.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/TargetParser.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/VersionTuple.h"
40 #include "llvm/Support/VirtualFileSystem.h"
46 using namespace clang;
47 using namespace driver;
48 using namespace tools;
50 using namespace llvm::opt;
52 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
53 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
54 options::OPT_fno_rtti, options::OPT_frtti);
57 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
58 const llvm::Triple &Triple,
59 const Arg *CachedRTTIArg) {
60 // Explicit rtti/no-rtti args
62 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
63 return ToolChain::RM_Enabled;
65 return ToolChain::RM_Disabled;
68 // -frtti is default, except for the PS4 CPU.
69 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
72 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
74 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
75 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
77 if (auto CXXStdlibPath = getCXXStdlibPath())
78 getFilePaths().push_back(*CXXStdlibPath);
81 if (auto RuntimePath = getRuntimePath())
82 getLibraryPaths().push_back(*RuntimePath);
84 std::string CandidateLibPath = getArchSpecificLibPath();
85 if (getVFS().exists(CandidateLibPath))
86 getFilePaths().push_back(CandidateLibPath);
89 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
90 Triple.setEnvironment(Env);
91 if (EffectiveTriple != llvm::Triple())
92 EffectiveTriple.setEnvironment(Env);
95 ToolChain::~ToolChain() = default;
97 llvm::vfs::FileSystem &ToolChain::getVFS() const {
98 return getDriver().getVFS();
101 bool ToolChain::useIntegratedAs() const {
102 return Args.hasFlag(options::OPT_fintegrated_as,
103 options::OPT_fno_integrated_as,
104 IsIntegratedAssemblerDefault());
107 bool ToolChain::useRelaxRelocations() const {
108 return ENABLE_X86_RELAX_RELOCATIONS;
111 bool ToolChain::isNoExecStackDefault() const {
115 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
116 if (!SanitizerArguments.get())
117 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
118 return *SanitizerArguments.get();
121 const XRayArgs& ToolChain::getXRayArgs() const {
122 if (!XRayArguments.get())
123 XRayArguments.reset(new XRayArgs(*this, Args));
124 return *XRayArguments.get();
129 struct DriverSuffix {
131 const char *ModeFlag;
136 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
137 // A list of known driver suffixes. Suffixes are compared against the
138 // program name in order. If there is a match, the frontend type is updated as
139 // necessary by applying the ModeFlag.
140 static const DriverSuffix DriverSuffixes[] = {
142 {"clang++", "--driver-mode=g++"},
143 {"clang-c++", "--driver-mode=g++"},
144 {"clang-cc", nullptr},
145 {"clang-cpp", "--driver-mode=cpp"},
146 {"clang-g++", "--driver-mode=g++"},
147 {"clang-gcc", nullptr},
148 {"clang-cl", "--driver-mode=cl"},
150 {"cpp", "--driver-mode=cpp"},
151 {"cl", "--driver-mode=cl"},
152 {"++", "--driver-mode=g++"},
155 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
156 StringRef Suffix(DriverSuffixes[i].Suffix);
157 if (ProgName.endswith(Suffix)) {
158 Pos = ProgName.size() - Suffix.size();
159 return &DriverSuffixes[i];
165 /// Normalize the program name from argv[0] by stripping the file extension if
166 /// present and lower-casing the string on Windows.
167 static std::string normalizeProgramName(llvm::StringRef Argv0) {
168 std::string ProgName = llvm::sys::path::stem(Argv0);
170 // Transform to lowercase for case insensitive file systems.
171 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
176 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
177 // Try to infer frontend type and default target from the program name by
178 // comparing it against DriverSuffixes in order.
180 // If there is a match, the function tries to identify a target as prefix.
181 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
182 // prefix "x86_64-linux". If such a target prefix is found, it may be
183 // added via -target as implicit first argument.
184 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
187 // Try again after stripping any trailing version number:
188 // clang++3.5 -> clang++
189 ProgName = ProgName.rtrim("0123456789.");
190 DS = FindDriverSuffix(ProgName, Pos);
194 // Try again after stripping trailing -component.
195 // clang++-tot -> clang++
196 ProgName = ProgName.slice(0, ProgName.rfind('-'));
197 DS = FindDriverSuffix(ProgName, Pos);
203 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
204 std::string ProgName = normalizeProgramName(PN);
206 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
209 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
211 size_t LastComponent = ProgName.rfind('-', SuffixPos);
212 if (LastComponent == std::string::npos)
213 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
214 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
215 SuffixEnd - LastComponent - 1);
217 // Infer target from the prefix.
218 StringRef Prefix(ProgName);
219 Prefix = Prefix.slice(0, LastComponent);
220 std::string IgnoredError;
221 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
222 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
225 StringRef ToolChain::getDefaultUniversalArchName() const {
226 // In universal driver terms, the arch name accepted by -arch isn't exactly
227 // the same as the ones that appear in the triple. Roughly speaking, this is
228 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
229 // only interesting special case is powerpc.
230 switch (Triple.getArch()) {
231 case llvm::Triple::ppc:
233 case llvm::Triple::ppc64:
235 case llvm::Triple::ppc64le:
238 return Triple.getArchName();
242 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
243 return Input.getFilename();
246 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
250 Tool *ToolChain::getClang() const {
252 Clang.reset(new tools::Clang(*this));
256 Tool *ToolChain::buildAssembler() const {
257 return new tools::ClangAs(*this);
260 Tool *ToolChain::buildLinker() const {
261 llvm_unreachable("Linking is not supported by this toolchain");
264 Tool *ToolChain::getAssemble() const {
266 Assemble.reset(buildAssembler());
267 return Assemble.get();
270 Tool *ToolChain::getClangAs() const {
272 Assemble.reset(new tools::ClangAs(*this));
273 return Assemble.get();
276 Tool *ToolChain::getLink() const {
278 Link.reset(buildLinker());
282 Tool *ToolChain::getOffloadBundler() const {
284 OffloadBundler.reset(new tools::OffloadBundler(*this));
285 return OffloadBundler.get();
288 Tool *ToolChain::getTool(Action::ActionClass AC) const {
290 case Action::AssembleJobClass:
291 return getAssemble();
293 case Action::LinkJobClass:
296 case Action::InputClass:
297 case Action::BindArchClass:
298 case Action::OffloadClass:
299 case Action::LipoJobClass:
300 case Action::DsymutilJobClass:
301 case Action::VerifyDebugInfoJobClass:
302 llvm_unreachable("Invalid tool kind.");
304 case Action::CompileJobClass:
305 case Action::PrecompileJobClass:
306 case Action::HeaderModulePrecompileJobClass:
307 case Action::PreprocessJobClass:
308 case Action::AnalyzeJobClass:
309 case Action::MigrateJobClass:
310 case Action::VerifyPCHJobClass:
311 case Action::BackendJobClass:
314 case Action::OffloadBundlingJobClass:
315 case Action::OffloadUnbundlingJobClass:
316 return getOffloadBundler();
319 llvm_unreachable("Invalid tool kind.");
322 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
323 const ArgList &Args) {
324 const llvm::Triple &Triple = TC.getTriple();
325 bool IsWindows = Triple.isOSWindows();
327 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
328 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
332 // For historic reasons, Android library is using i686 instead of i386.
333 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
336 return llvm::Triple::getArchTypeName(TC.getArch());
339 StringRef ToolChain::getOSLibName() const {
340 switch (Triple.getOS()) {
341 case llvm::Triple::FreeBSD:
343 case llvm::Triple::NetBSD:
345 case llvm::Triple::OpenBSD:
347 case llvm::Triple::Solaris:
354 std::string ToolChain::getCompilerRTPath() const {
355 SmallString<128> Path(getDriver().ResourceDir);
356 if (Triple.isOSUnknown()) {
357 llvm::sys::path::append(Path, "lib");
359 llvm::sys::path::append(Path, "lib", getOSLibName());
364 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
365 FileType Type) const {
366 const llvm::Triple &TT = getTriple();
367 bool IsITANMSVCWindows =
368 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
371 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
374 case ToolChain::FT_Object:
375 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
377 case ToolChain::FT_Static:
378 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
380 case ToolChain::FT_Shared:
381 Suffix = Triple.isOSWindows()
382 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
387 for (const auto &LibPath : getLibraryPaths()) {
388 SmallString<128> P(LibPath);
389 llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
390 if (getVFS().exists(P))
394 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
395 const char *Env = TT.isAndroid() ? "-android" : "";
396 SmallString<128> Path(getCompilerRTPath());
397 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
398 Arch + Env + Suffix);
402 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
404 FileType Type) const {
405 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
409 Optional<std::string> ToolChain::getRuntimePath() const {
412 // First try the triple passed to driver as --target=<triple>.
413 P.assign(D.ResourceDir);
414 llvm::sys::path::append(P, "lib", D.getTargetTriple());
415 if (getVFS().exists(P))
416 return llvm::Optional<std::string>(P.str());
418 // Second try the normalized triple.
419 P.assign(D.ResourceDir);
420 llvm::sys::path::append(P, "lib", Triple.str());
421 if (getVFS().exists(P))
422 return llvm::Optional<std::string>(P.str());
427 Optional<std::string> ToolChain::getCXXStdlibPath() const {
430 // First try the triple passed to driver as --target=<triple>.
432 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
433 if (getVFS().exists(P))
434 return llvm::Optional<std::string>(P.str());
436 // Second try the normalized triple.
438 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
439 if (getVFS().exists(P))
440 return llvm::Optional<std::string>(P.str());
445 std::string ToolChain::getArchSpecificLibPath() const {
446 SmallString<128> Path(getDriver().ResourceDir);
447 llvm::sys::path::append(Path, "lib", getOSLibName(),
448 llvm::Triple::getArchTypeName(getArch()));
452 bool ToolChain::needsProfileRT(const ArgList &Args) {
453 if (Args.hasArg(options::OPT_noprofilelib))
456 if (needsGCovInstrumentation(Args) ||
457 Args.hasArg(options::OPT_fprofile_generate) ||
458 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
459 Args.hasArg(options::OPT_fcs_profile_generate) ||
460 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
461 Args.hasArg(options::OPT_fprofile_instr_generate) ||
462 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
463 Args.hasArg(options::OPT_fcreate_profile) ||
464 Args.hasArg(options::OPT_forder_file_instrumentation))
470 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
471 return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
473 Args.hasArg(options::OPT_coverage);
476 Tool *ToolChain::SelectTool(const JobAction &JA) const {
477 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
478 Action::ActionClass AC = JA.getKind();
479 if (AC == Action::AssembleJobClass && useIntegratedAs())
484 std::string ToolChain::GetFilePath(const char *Name) const {
485 return D.GetFilePath(Name, *this);
488 std::string ToolChain::GetProgramPath(const char *Name) const {
489 return D.GetProgramPath(Name, *this);
492 std::string ToolChain::GetLinkerPath() const {
493 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
494 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
496 if (llvm::sys::path::is_absolute(UseLinker)) {
497 // If we're passed what looks like an absolute path, don't attempt to
498 // second-guess that.
499 if (llvm::sys::fs::can_execute(UseLinker))
501 } else if (UseLinker.empty() || UseLinker == "ld") {
502 // If we're passed -fuse-ld= with no argument, or with the argument ld,
503 // then use whatever the default system linker is.
504 return GetProgramPath(getDefaultLinker());
506 llvm::SmallString<8> LinkerName;
507 if (Triple.isOSDarwin())
508 LinkerName.append("ld64.");
510 LinkerName.append("ld.");
511 LinkerName.append(UseLinker);
513 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
514 if (llvm::sys::fs::can_execute(LinkerPath))
519 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
521 return GetProgramPath(getDefaultLinker());
524 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
525 return types::lookupTypeForExtension(Ext);
528 bool ToolChain::HasNativeLLVMSupport() const {
532 bool ToolChain::isCrossCompiling() const {
533 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
534 switch (HostTriple.getArch()) {
535 // The A32/T32/T16 instruction sets are not separate architectures in this
537 case llvm::Triple::arm:
538 case llvm::Triple::armeb:
539 case llvm::Triple::thumb:
540 case llvm::Triple::thumbeb:
541 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
542 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
544 return HostTriple.getArch() != getArch();
548 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
549 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
553 llvm::ExceptionHandling
554 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
555 return llvm::ExceptionHandling::None;
558 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
559 if (Model == "single") {
560 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
561 return Triple.getArch() == llvm::Triple::arm ||
562 Triple.getArch() == llvm::Triple::armeb ||
563 Triple.getArch() == llvm::Triple::thumb ||
564 Triple.getArch() == llvm::Triple::thumbeb ||
565 Triple.getArch() == llvm::Triple::wasm32 ||
566 Triple.getArch() == llvm::Triple::wasm64;
567 } else if (Model == "posix")
573 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
574 types::ID InputType) const {
575 switch (getTriple().getArch()) {
577 return getTripleString();
579 case llvm::Triple::x86_64: {
580 llvm::Triple Triple = getTriple();
581 if (!Triple.isOSBinFormatMachO())
582 return getTripleString();
584 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
585 // x86_64h goes in the triple. Other -march options just use the
586 // vanilla triple we already have.
587 StringRef MArch = A->getValue();
588 if (MArch == "x86_64h")
589 Triple.setArchName(MArch);
591 return Triple.getTriple();
593 case llvm::Triple::aarch64: {
594 llvm::Triple Triple = getTriple();
595 if (!Triple.isOSBinFormatMachO())
596 return getTripleString();
598 // FIXME: older versions of ld64 expect the "arm64" component in the actual
599 // triple string and query it to determine whether an LTO file can be
600 // handled. Remove this when we don't care any more.
601 Triple.setArchName("arm64");
602 return Triple.getTriple();
604 case llvm::Triple::arm:
605 case llvm::Triple::armeb:
606 case llvm::Triple::thumb:
607 case llvm::Triple::thumbeb: {
608 // FIXME: Factor into subclasses.
609 llvm::Triple Triple = getTriple();
610 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
611 getTriple().getArch() == llvm::Triple::thumbeb;
613 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
614 // '-mbig-endian'/'-EB'.
615 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
616 options::OPT_mbig_endian)) {
617 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
620 // Thumb2 is the default for V7 on Darwin.
622 // FIXME: Thumb should just be another -target-feaure, not in the triple.
623 StringRef MCPU, MArch;
624 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
625 MCPU = A->getValue();
626 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
627 MArch = A->getValue();
629 Triple.isOSBinFormatMachO()
630 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
631 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
633 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
634 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
635 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
636 getTriple().isOSBinFormatMachO());
637 // FIXME: this is invalid for WindowsCE
638 if (getTriple().isOSWindows())
640 std::string ArchName;
646 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
647 // M-Class CPUs/architecture variants, which is not supported.
648 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
649 options::OPT_mno_thumb, ThumbDefault);
650 if (IsMProfile && ARMModeRequested) {
652 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
654 getDriver().Diag(diag::err_arch_unsupported_isa)
655 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
658 // Check to see if an explicit choice to use thumb has been made via
659 // -mthumb. For assembler files we must check for -mthumb in the options
660 // passed to the assembler via -Wa or -Xassembler.
661 bool IsThumb = false;
662 if (InputType != types::TY_PP_Asm)
663 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
666 // Ideally we would check for these flags in
667 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
668 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
671 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
672 for (StringRef Value : A->getValues()) {
673 if (Value == "-mthumb")
678 // Assembly files should start in ARM mode, unless arch is M-profile, or
679 // -mthumb has been passed explicitly to the assembler. Windows is always
681 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
683 ArchName = "thumbeb";
687 Triple.setArchName(ArchName + Suffix.str());
689 return Triple.getTriple();
694 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
695 types::ID InputType) const {
696 return ComputeLLVMTriple(Args, InputType);
699 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
700 ArgStringList &CC1Args) const {
701 // Each toolchain should provide the appropriate include flags.
704 void ToolChain::addClangTargetOptions(
705 const ArgList &DriverArgs, ArgStringList &CC1Args,
706 Action::OffloadKind DeviceOffloadKind) const {}
708 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
710 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
711 llvm::opt::ArgStringList &CmdArgs) const {
712 if (!needsProfileRT(Args)) return;
714 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
717 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
718 const ArgList &Args) const {
719 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
720 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
722 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
723 if (LibName == "compiler-rt")
724 return ToolChain::RLT_CompilerRT;
725 else if (LibName == "libgcc")
726 return ToolChain::RLT_Libgcc;
727 else if (LibName == "platform")
728 return GetDefaultRuntimeLibType();
731 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
733 return GetDefaultRuntimeLibType();
736 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
737 const ArgList &Args) const {
738 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
739 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
741 if (LibName == "none")
742 return ToolChain::UNW_None;
743 else if (LibName == "platform" || LibName == "") {
744 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
745 if (RtLibType == ToolChain::RLT_CompilerRT)
746 return ToolChain::UNW_None;
747 else if (RtLibType == ToolChain::RLT_Libgcc)
748 return ToolChain::UNW_Libgcc;
749 } else if (LibName == "libunwind") {
750 if (GetRuntimeLibType(Args) == RLT_Libgcc)
751 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
752 return ToolChain::UNW_CompilerRT;
753 } else if (LibName == "libgcc")
754 return ToolChain::UNW_Libgcc;
757 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
758 << A->getAsString(Args);
760 return GetDefaultUnwindLibType();
763 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
764 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
765 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
767 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
768 if (LibName == "libc++")
769 return ToolChain::CST_Libcxx;
770 else if (LibName == "libstdc++")
771 return ToolChain::CST_Libstdcxx;
772 else if (LibName == "platform")
773 return GetDefaultCXXStdlibType();
776 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
778 return GetDefaultCXXStdlibType();
781 /// Utility function to add a system include directory to CC1 arguments.
782 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
783 ArgStringList &CC1Args,
785 CC1Args.push_back("-internal-isystem");
786 CC1Args.push_back(DriverArgs.MakeArgString(Path));
789 /// Utility function to add a system include directory with extern "C"
790 /// semantics to CC1 arguments.
792 /// Note that this should be used rarely, and only for directories that
793 /// historically and for legacy reasons are treated as having implicit extern
794 /// "C" semantics. These semantics are *ignored* by and large today, but its
795 /// important to preserve the preprocessor changes resulting from the
797 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
798 ArgStringList &CC1Args,
800 CC1Args.push_back("-internal-externc-isystem");
801 CC1Args.push_back(DriverArgs.MakeArgString(Path));
804 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
805 ArgStringList &CC1Args,
807 if (llvm::sys::fs::exists(Path))
808 addExternCSystemInclude(DriverArgs, CC1Args, Path);
811 /// Utility function to add a list of system include directories to CC1.
812 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
813 ArgStringList &CC1Args,
814 ArrayRef<StringRef> Paths) {
815 for (const auto Path : Paths) {
816 CC1Args.push_back("-internal-isystem");
817 CC1Args.push_back(DriverArgs.MakeArgString(Path));
821 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
822 ArgStringList &CC1Args) const {
823 // Header search paths should be handled by each of the subclasses.
824 // Historically, they have not been, and instead have been handled inside of
825 // the CC1-layer frontend. As the logic is hoisted out, this generic function
826 // will slowly stop being called.
828 // While it is being called, replicate a bit of a hack to propagate the
829 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
830 // header search paths with it. Once all systems are overriding this
831 // function, the CC1 flag and this line can be removed.
832 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
835 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
836 return getDriver().CCCIsCXX() &&
837 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
838 options::OPT_nostdlibxx);
841 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
842 ArgStringList &CmdArgs) const {
843 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
844 "should not have called this");
845 CXXStdlibType Type = GetCXXStdlibType(Args);
848 case ToolChain::CST_Libcxx:
849 CmdArgs.push_back("-lc++");
852 case ToolChain::CST_Libstdcxx:
853 CmdArgs.push_back("-lstdc++");
858 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
859 ArgStringList &CmdArgs) const {
860 for (const auto &LibPath : getFilePaths())
861 if(LibPath.length() > 0)
862 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
865 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
866 ArgStringList &CmdArgs) const {
867 CmdArgs.push_back("-lcc_kext");
870 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
871 ArgStringList &CmdArgs) const {
872 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
873 // (to keep the linker options consistent with gcc and clang itself).
874 if (!isOptimizationLevelFast(Args)) {
875 // Check if -ffast-math or -funsafe-math.
877 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
878 options::OPT_funsafe_math_optimizations,
879 options::OPT_fno_unsafe_math_optimizations);
881 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
882 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
885 // If crtfastmath.o exists add it to the arguments.
886 std::string Path = GetFilePath("crtfastmath.o");
887 if (Path == "crtfastmath.o") // Not found.
890 CmdArgs.push_back(Args.MakeArgString(Path));
894 SanitizerMask ToolChain::getSupportedSanitizers() const {
895 // Return sanitizers which don't require runtime support and are not
896 // platform dependent.
898 SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
899 ~SanitizerKind::Function) |
900 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
901 SanitizerKind::CFICastStrict |
902 SanitizerKind::FloatDivideByZero |
903 SanitizerKind::UnsignedIntegerOverflow |
904 SanitizerKind::ImplicitConversion |
905 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
906 if (getTriple().getArch() == llvm::Triple::x86 ||
907 getTriple().getArch() == llvm::Triple::x86_64 ||
908 getTriple().getArch() == llvm::Triple::arm ||
909 getTriple().getArch() == llvm::Triple::aarch64 ||
910 getTriple().getArch() == llvm::Triple::wasm32 ||
911 getTriple().getArch() == llvm::Triple::wasm64)
912 Res |= SanitizerKind::CFIICall;
913 if (getTriple().getArch() == llvm::Triple::x86_64 ||
914 getTriple().getArch() == llvm::Triple::aarch64)
915 Res |= SanitizerKind::ShadowCallStack;
919 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
920 ArgStringList &CC1Args) const {}
922 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
923 ArgStringList &CC1Args) const {}
925 static VersionTuple separateMSVCFullVersion(unsigned Version) {
927 return VersionTuple(Version);
930 return VersionTuple(Version / 100, Version % 100);
932 unsigned Build = 0, Factor = 1;
933 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
934 Build = Build + (Version % 10) * Factor;
935 return VersionTuple(Version / 100, Version % 100, Build);
939 ToolChain::computeMSVCVersion(const Driver *D,
940 const llvm::opt::ArgList &Args) const {
941 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
942 const Arg *MSCompatibilityVersion =
943 Args.getLastArg(options::OPT_fms_compatibility_version);
945 if (MSCVersion && MSCompatibilityVersion) {
947 D->Diag(diag::err_drv_argument_not_allowed_with)
948 << MSCVersion->getAsString(Args)
949 << MSCompatibilityVersion->getAsString(Args);
950 return VersionTuple();
953 if (MSCompatibilityVersion) {
955 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
957 D->Diag(diag::err_drv_invalid_value)
958 << MSCompatibilityVersion->getAsString(Args)
959 << MSCompatibilityVersion->getValue();
966 unsigned Version = 0;
967 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
969 D->Diag(diag::err_drv_invalid_value)
970 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
972 return separateMSVCFullVersion(Version);
976 return VersionTuple();
979 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
980 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
981 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
982 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
983 const OptTable &Opts = getDriver().getOpts();
984 bool Modified = false;
986 // Handle -Xopenmp-target flags
987 for (auto *A : Args) {
988 // Exclude flags which may only apply to the host toolchain.
989 // Do not exclude flags when the host triple (AuxTriple)
990 // matches the current toolchain triple. If it is not present
991 // at all, target and host share a toolchain.
992 if (A->getOption().matches(options::OPT_m_Group)) {
993 if (SameTripleAsHost)
1002 bool XOpenMPTargetNoTriple =
1003 A->getOption().matches(options::OPT_Xopenmp_target);
1005 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1006 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1007 if (A->getValue(0) == getTripleString())
1008 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1011 } else if (XOpenMPTargetNoTriple) {
1012 // Passing device args: -Xopenmp-target -opt=val.
1013 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1019 // Parse the argument to -Xopenmp-target.
1021 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1022 if (!XOpenMPTargetArg || Index > Prev + 1) {
1023 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1024 << A->getAsString(Args);
1027 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1028 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1029 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1032 XOpenMPTargetArg->setBaseArg(A);
1033 A = XOpenMPTargetArg.release();
1034 AllocatedArgs.push_back(A);