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 "ToolChains/InterfaceStubs.h"
14 #include "clang/Basic/ObjCRuntime.h"
15 #include "clang/Basic/Sanitizers.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Action.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/DriverDiagnostic.h"
20 #include "clang/Driver/Job.h"
21 #include "clang/Driver/Options.h"
22 #include "clang/Driver/SanitizerArgs.h"
23 #include "clang/Driver/XRayArgs.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/MC/MCTargetOptions.h"
31 #include "llvm/Option/Arg.h"
32 #include "llvm/Option/ArgList.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/TargetParser.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/VersionTuple.h"
41 #include "llvm/Support/VirtualFileSystem.h"
47 using namespace clang;
48 using namespace driver;
49 using namespace tools;
51 using namespace llvm::opt;
53 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
54 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
55 options::OPT_fno_rtti, options::OPT_frtti);
58 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
59 const llvm::Triple &Triple,
60 const Arg *CachedRTTIArg) {
61 // Explicit rtti/no-rtti args
63 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
64 return ToolChain::RM_Enabled;
66 return ToolChain::RM_Disabled;
69 // -frtti is default, except for the PS4 CPU.
70 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
73 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
75 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
76 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
78 if (auto CXXStdlibPath = getCXXStdlibPath())
79 getFilePaths().push_back(*CXXStdlibPath);
82 if (auto RuntimePath = getRuntimePath())
83 getLibraryPaths().push_back(*RuntimePath);
85 std::string CandidateLibPath = getArchSpecificLibPath();
86 if (getVFS().exists(CandidateLibPath))
87 getFilePaths().push_back(CandidateLibPath);
90 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
91 Triple.setEnvironment(Env);
92 if (EffectiveTriple != llvm::Triple())
93 EffectiveTriple.setEnvironment(Env);
96 ToolChain::~ToolChain() = default;
98 llvm::vfs::FileSystem &ToolChain::getVFS() const {
99 return getDriver().getVFS();
102 bool ToolChain::useIntegratedAs() const {
103 return Args.hasFlag(options::OPT_fintegrated_as,
104 options::OPT_fno_integrated_as,
105 IsIntegratedAssemblerDefault());
108 bool ToolChain::useRelaxRelocations() const {
109 return ENABLE_X86_RELAX_RELOCATIONS;
112 bool ToolChain::isNoExecStackDefault() const {
116 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
117 if (!SanitizerArguments.get())
118 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
119 return *SanitizerArguments.get();
122 const XRayArgs& ToolChain::getXRayArgs() const {
123 if (!XRayArguments.get())
124 XRayArguments.reset(new XRayArgs(*this, Args));
125 return *XRayArguments.get();
130 struct DriverSuffix {
132 const char *ModeFlag;
137 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
138 // A list of known driver suffixes. Suffixes are compared against the
139 // program name in order. If there is a match, the frontend type is updated as
140 // necessary by applying the ModeFlag.
141 static const DriverSuffix DriverSuffixes[] = {
143 {"clang++", "--driver-mode=g++"},
144 {"clang-c++", "--driver-mode=g++"},
145 {"clang-cc", nullptr},
146 {"clang-cpp", "--driver-mode=cpp"},
147 {"clang-g++", "--driver-mode=g++"},
148 {"clang-gcc", nullptr},
149 {"clang-cl", "--driver-mode=cl"},
151 {"cpp", "--driver-mode=cpp"},
152 {"cl", "--driver-mode=cl"},
153 {"++", "--driver-mode=g++"},
156 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
157 StringRef Suffix(DriverSuffixes[i].Suffix);
158 if (ProgName.endswith(Suffix)) {
159 Pos = ProgName.size() - Suffix.size();
160 return &DriverSuffixes[i];
166 /// Normalize the program name from argv[0] by stripping the file extension if
167 /// present and lower-casing the string on Windows.
168 static std::string normalizeProgramName(llvm::StringRef Argv0) {
169 std::string ProgName = llvm::sys::path::stem(Argv0);
171 // Transform to lowercase for case insensitive file systems.
172 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
177 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
178 // Try to infer frontend type and default target from the program name by
179 // comparing it against DriverSuffixes in order.
181 // If there is a match, the function tries to identify a target as prefix.
182 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
183 // prefix "x86_64-linux". If such a target prefix is found, it may be
184 // added via -target as implicit first argument.
185 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
188 // Try again after stripping any trailing version number:
189 // clang++3.5 -> clang++
190 ProgName = ProgName.rtrim("0123456789.");
191 DS = FindDriverSuffix(ProgName, Pos);
195 // Try again after stripping trailing -component.
196 // clang++-tot -> clang++
197 ProgName = ProgName.slice(0, ProgName.rfind('-'));
198 DS = FindDriverSuffix(ProgName, Pos);
204 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
205 std::string ProgName = normalizeProgramName(PN);
207 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
210 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
212 size_t LastComponent = ProgName.rfind('-', SuffixPos);
213 if (LastComponent == std::string::npos)
214 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
215 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
216 SuffixEnd - LastComponent - 1);
218 // Infer target from the prefix.
219 StringRef Prefix(ProgName);
220 Prefix = Prefix.slice(0, LastComponent);
221 std::string IgnoredError;
222 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
223 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
226 StringRef ToolChain::getDefaultUniversalArchName() const {
227 // In universal driver terms, the arch name accepted by -arch isn't exactly
228 // the same as the ones that appear in the triple. Roughly speaking, this is
229 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
230 // only interesting special case is powerpc.
231 switch (Triple.getArch()) {
232 case llvm::Triple::ppc:
234 case llvm::Triple::ppc64:
236 case llvm::Triple::ppc64le:
239 return Triple.getArchName();
243 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
244 return Input.getFilename();
247 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
251 Tool *ToolChain::getClang() const {
253 Clang.reset(new tools::Clang(*this));
257 Tool *ToolChain::buildAssembler() const {
258 return new tools::ClangAs(*this);
261 Tool *ToolChain::buildLinker() const {
262 llvm_unreachable("Linking is not supported by this toolchain");
265 Tool *ToolChain::getAssemble() const {
267 Assemble.reset(buildAssembler());
268 return Assemble.get();
271 Tool *ToolChain::getClangAs() const {
273 Assemble.reset(new tools::ClangAs(*this));
274 return Assemble.get();
277 Tool *ToolChain::getLink() const {
279 Link.reset(buildLinker());
283 Tool *ToolChain::getIfsMerge() const {
285 IfsMerge.reset(new tools::ifstool::Merger(*this));
286 return IfsMerge.get();
289 Tool *ToolChain::getOffloadBundler() const {
291 OffloadBundler.reset(new tools::OffloadBundler(*this));
292 return OffloadBundler.get();
295 Tool *ToolChain::getOffloadWrapper() const {
297 OffloadWrapper.reset(new tools::OffloadWrapper(*this));
298 return OffloadWrapper.get();
301 Tool *ToolChain::getTool(Action::ActionClass AC) const {
303 case Action::AssembleJobClass:
304 return getAssemble();
306 case Action::IfsMergeJobClass:
307 return getIfsMerge();
309 case Action::LinkJobClass:
312 case Action::InputClass:
313 case Action::BindArchClass:
314 case Action::OffloadClass:
315 case Action::LipoJobClass:
316 case Action::DsymutilJobClass:
317 case Action::VerifyDebugInfoJobClass:
318 llvm_unreachable("Invalid tool kind.");
320 case Action::CompileJobClass:
321 case Action::PrecompileJobClass:
322 case Action::HeaderModulePrecompileJobClass:
323 case Action::PreprocessJobClass:
324 case Action::AnalyzeJobClass:
325 case Action::MigrateJobClass:
326 case Action::VerifyPCHJobClass:
327 case Action::BackendJobClass:
330 case Action::OffloadBundlingJobClass:
331 case Action::OffloadUnbundlingJobClass:
332 return getOffloadBundler();
334 case Action::OffloadWrapperJobClass:
335 return getOffloadWrapper();
338 llvm_unreachable("Invalid tool kind.");
341 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
342 const ArgList &Args) {
343 const llvm::Triple &Triple = TC.getTriple();
344 bool IsWindows = Triple.isOSWindows();
346 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
347 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
351 // For historic reasons, Android library is using i686 instead of i386.
352 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
355 return llvm::Triple::getArchTypeName(TC.getArch());
358 StringRef ToolChain::getOSLibName() const {
359 switch (Triple.getOS()) {
360 case llvm::Triple::FreeBSD:
362 case llvm::Triple::NetBSD:
364 case llvm::Triple::OpenBSD:
366 case llvm::Triple::Solaris:
373 std::string ToolChain::getCompilerRTPath() const {
374 SmallString<128> Path(getDriver().ResourceDir);
375 if (Triple.isOSUnknown()) {
376 llvm::sys::path::append(Path, "lib");
378 llvm::sys::path::append(Path, "lib", getOSLibName());
383 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
384 FileType Type) const {
385 const llvm::Triple &TT = getTriple();
386 bool IsITANMSVCWindows =
387 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
390 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
393 case ToolChain::FT_Object:
394 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
396 case ToolChain::FT_Static:
397 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
399 case ToolChain::FT_Shared:
400 Suffix = Triple.isOSWindows()
401 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
406 for (const auto &LibPath : getLibraryPaths()) {
407 SmallString<128> P(LibPath);
408 llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
409 if (getVFS().exists(P))
413 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
414 const char *Env = TT.isAndroid() ? "-android" : "";
415 SmallString<128> Path(getCompilerRTPath());
416 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
417 Arch + Env + Suffix);
421 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
423 FileType Type) const {
424 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
428 Optional<std::string> ToolChain::getRuntimePath() const {
431 // First try the triple passed to driver as --target=<triple>.
432 P.assign(D.ResourceDir);
433 llvm::sys::path::append(P, "lib", D.getTargetTriple());
434 if (getVFS().exists(P))
435 return llvm::Optional<std::string>(P.str());
437 // Second try the normalized triple.
438 P.assign(D.ResourceDir);
439 llvm::sys::path::append(P, "lib", Triple.str());
440 if (getVFS().exists(P))
441 return llvm::Optional<std::string>(P.str());
446 Optional<std::string> ToolChain::getCXXStdlibPath() const {
449 // First try the triple passed to driver as --target=<triple>.
451 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
452 if (getVFS().exists(P))
453 return llvm::Optional<std::string>(P.str());
455 // Second try the normalized triple.
457 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
458 if (getVFS().exists(P))
459 return llvm::Optional<std::string>(P.str());
464 std::string ToolChain::getArchSpecificLibPath() const {
465 SmallString<128> Path(getDriver().ResourceDir);
466 llvm::sys::path::append(Path, "lib", getOSLibName(),
467 llvm::Triple::getArchTypeName(getArch()));
471 bool ToolChain::needsProfileRT(const ArgList &Args) {
472 if (Args.hasArg(options::OPT_noprofilelib))
475 if (needsGCovInstrumentation(Args) ||
476 Args.hasArg(options::OPT_fprofile_generate) ||
477 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
478 Args.hasArg(options::OPT_fcs_profile_generate) ||
479 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
480 Args.hasArg(options::OPT_fprofile_instr_generate) ||
481 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
482 Args.hasArg(options::OPT_fcreate_profile) ||
483 Args.hasArg(options::OPT_forder_file_instrumentation))
489 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
490 return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
492 Args.hasArg(options::OPT_coverage);
495 Tool *ToolChain::SelectTool(const JobAction &JA) const {
496 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
497 Action::ActionClass AC = JA.getKind();
498 if (AC == Action::AssembleJobClass && useIntegratedAs())
503 std::string ToolChain::GetFilePath(const char *Name) const {
504 return D.GetFilePath(Name, *this);
507 std::string ToolChain::GetProgramPath(const char *Name) const {
508 return D.GetProgramPath(Name, *this);
511 std::string ToolChain::GetLinkerPath() const {
512 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
513 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
515 if (llvm::sys::path::is_absolute(UseLinker)) {
516 // If we're passed what looks like an absolute path, don't attempt to
517 // second-guess that.
518 if (llvm::sys::fs::can_execute(UseLinker))
520 } else if (UseLinker.empty() || UseLinker == "ld") {
521 // If we're passed -fuse-ld= with no argument, or with the argument ld,
522 // then use whatever the default system linker is.
523 return GetProgramPath(getDefaultLinker());
525 llvm::SmallString<8> LinkerName;
526 if (Triple.isOSDarwin())
527 LinkerName.append("ld64.");
529 LinkerName.append("ld.");
530 LinkerName.append(UseLinker);
532 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
533 if (llvm::sys::fs::can_execute(LinkerPath))
538 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
540 return GetProgramPath(getDefaultLinker());
543 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
544 return types::lookupTypeForExtension(Ext);
547 bool ToolChain::HasNativeLLVMSupport() const {
551 bool ToolChain::isCrossCompiling() const {
552 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
553 switch (HostTriple.getArch()) {
554 // The A32/T32/T16 instruction sets are not separate architectures in this
556 case llvm::Triple::arm:
557 case llvm::Triple::armeb:
558 case llvm::Triple::thumb:
559 case llvm::Triple::thumbeb:
560 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
561 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
563 return HostTriple.getArch() != getArch();
567 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
568 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
572 llvm::ExceptionHandling
573 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
574 return llvm::ExceptionHandling::None;
577 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
578 if (Model == "single") {
579 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
580 return Triple.getArch() == llvm::Triple::arm ||
581 Triple.getArch() == llvm::Triple::armeb ||
582 Triple.getArch() == llvm::Triple::thumb ||
583 Triple.getArch() == llvm::Triple::thumbeb ||
584 Triple.getArch() == llvm::Triple::wasm32 ||
585 Triple.getArch() == llvm::Triple::wasm64;
586 } else if (Model == "posix")
592 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
593 types::ID InputType) const {
594 switch (getTriple().getArch()) {
596 return getTripleString();
598 case llvm::Triple::x86_64: {
599 llvm::Triple Triple = getTriple();
600 if (!Triple.isOSBinFormatMachO())
601 return getTripleString();
603 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
604 // x86_64h goes in the triple. Other -march options just use the
605 // vanilla triple we already have.
606 StringRef MArch = A->getValue();
607 if (MArch == "x86_64h")
608 Triple.setArchName(MArch);
610 return Triple.getTriple();
612 case llvm::Triple::aarch64: {
613 llvm::Triple Triple = getTriple();
614 if (!Triple.isOSBinFormatMachO())
615 return getTripleString();
617 // FIXME: older versions of ld64 expect the "arm64" component in the actual
618 // triple string and query it to determine whether an LTO file can be
619 // handled. Remove this when we don't care any more.
620 Triple.setArchName("arm64");
621 return Triple.getTriple();
623 case llvm::Triple::arm:
624 case llvm::Triple::armeb:
625 case llvm::Triple::thumb:
626 case llvm::Triple::thumbeb: {
627 // FIXME: Factor into subclasses.
628 llvm::Triple Triple = getTriple();
629 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
630 getTriple().getArch() == llvm::Triple::thumbeb;
632 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
633 // '-mbig-endian'/'-EB'.
634 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
635 options::OPT_mbig_endian)) {
636 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
639 // Thumb2 is the default for V7 on Darwin.
641 // FIXME: Thumb should just be another -target-feaure, not in the triple.
642 StringRef MCPU, MArch;
643 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
644 MCPU = A->getValue();
645 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
646 MArch = A->getValue();
648 Triple.isOSBinFormatMachO()
649 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
650 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
652 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
653 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
654 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
655 getTriple().isOSBinFormatMachO());
656 // FIXME: this is invalid for WindowsCE
657 if (getTriple().isOSWindows())
659 std::string ArchName;
665 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
666 // M-Class CPUs/architecture variants, which is not supported.
667 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
668 options::OPT_mno_thumb, ThumbDefault);
669 if (IsMProfile && ARMModeRequested) {
671 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
673 getDriver().Diag(diag::err_arch_unsupported_isa)
674 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
677 // Check to see if an explicit choice to use thumb has been made via
678 // -mthumb. For assembler files we must check for -mthumb in the options
679 // passed to the assembler via -Wa or -Xassembler.
680 bool IsThumb = false;
681 if (InputType != types::TY_PP_Asm)
682 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
685 // Ideally we would check for these flags in
686 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
687 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
690 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
691 for (StringRef Value : A->getValues()) {
692 if (Value == "-mthumb")
697 // Assembly files should start in ARM mode, unless arch is M-profile, or
698 // -mthumb has been passed explicitly to the assembler. Windows is always
700 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
702 ArchName = "thumbeb";
706 Triple.setArchName(ArchName + Suffix.str());
708 return Triple.getTriple();
713 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
714 types::ID InputType) const {
715 return ComputeLLVMTriple(Args, InputType);
718 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
719 ArgStringList &CC1Args) const {
720 // Each toolchain should provide the appropriate include flags.
723 void ToolChain::addClangTargetOptions(
724 const ArgList &DriverArgs, ArgStringList &CC1Args,
725 Action::OffloadKind DeviceOffloadKind) const {}
727 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
729 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
730 llvm::opt::ArgStringList &CmdArgs) const {
731 if (!needsProfileRT(Args)) return;
733 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
736 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
737 const ArgList &Args) const {
738 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
739 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
741 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
742 if (LibName == "compiler-rt")
743 return ToolChain::RLT_CompilerRT;
744 else if (LibName == "libgcc")
745 return ToolChain::RLT_Libgcc;
746 else if (LibName == "platform")
747 return GetDefaultRuntimeLibType();
750 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
752 return GetDefaultRuntimeLibType();
755 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
756 const ArgList &Args) const {
757 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
758 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
760 if (LibName == "none")
761 return ToolChain::UNW_None;
762 else if (LibName == "platform" || LibName == "") {
763 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
764 if (RtLibType == ToolChain::RLT_CompilerRT)
765 return ToolChain::UNW_None;
766 else if (RtLibType == ToolChain::RLT_Libgcc)
767 return ToolChain::UNW_Libgcc;
768 } else if (LibName == "libunwind") {
769 if (GetRuntimeLibType(Args) == RLT_Libgcc)
770 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
771 return ToolChain::UNW_CompilerRT;
772 } else if (LibName == "libgcc")
773 return ToolChain::UNW_Libgcc;
776 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
777 << A->getAsString(Args);
779 return GetDefaultUnwindLibType();
782 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
783 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
784 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
786 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
787 if (LibName == "libc++")
788 return ToolChain::CST_Libcxx;
789 else if (LibName == "libstdc++")
790 return ToolChain::CST_Libstdcxx;
791 else if (LibName == "platform")
792 return GetDefaultCXXStdlibType();
795 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
797 return GetDefaultCXXStdlibType();
800 /// Utility function to add a system include directory to CC1 arguments.
801 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
802 ArgStringList &CC1Args,
804 CC1Args.push_back("-internal-isystem");
805 CC1Args.push_back(DriverArgs.MakeArgString(Path));
808 /// Utility function to add a system include directory with extern "C"
809 /// semantics to CC1 arguments.
811 /// Note that this should be used rarely, and only for directories that
812 /// historically and for legacy reasons are treated as having implicit extern
813 /// "C" semantics. These semantics are *ignored* by and large today, but its
814 /// important to preserve the preprocessor changes resulting from the
816 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
817 ArgStringList &CC1Args,
819 CC1Args.push_back("-internal-externc-isystem");
820 CC1Args.push_back(DriverArgs.MakeArgString(Path));
823 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
824 ArgStringList &CC1Args,
826 if (llvm::sys::fs::exists(Path))
827 addExternCSystemInclude(DriverArgs, CC1Args, Path);
830 /// Utility function to add a list of system include directories to CC1.
831 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
832 ArgStringList &CC1Args,
833 ArrayRef<StringRef> Paths) {
834 for (const auto Path : Paths) {
835 CC1Args.push_back("-internal-isystem");
836 CC1Args.push_back(DriverArgs.MakeArgString(Path));
840 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
841 ArgStringList &CC1Args) const {
842 // Header search paths should be handled by each of the subclasses.
843 // Historically, they have not been, and instead have been handled inside of
844 // the CC1-layer frontend. As the logic is hoisted out, this generic function
845 // will slowly stop being called.
847 // While it is being called, replicate a bit of a hack to propagate the
848 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
849 // header search paths with it. Once all systems are overriding this
850 // function, the CC1 flag and this line can be removed.
851 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
854 void ToolChain::AddClangCXXStdlibIsystemArgs(
855 const llvm::opt::ArgList &DriverArgs,
856 llvm::opt::ArgStringList &CC1Args) const {
857 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
858 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
860 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
861 addSystemInclude(DriverArgs, CC1Args, P);
864 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
865 return getDriver().CCCIsCXX() &&
866 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
867 options::OPT_nostdlibxx);
870 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
871 ArgStringList &CmdArgs) const {
872 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
873 "should not have called this");
874 CXXStdlibType Type = GetCXXStdlibType(Args);
877 case ToolChain::CST_Libcxx:
878 CmdArgs.push_back("-lc++");
881 case ToolChain::CST_Libstdcxx:
882 CmdArgs.push_back("-lstdc++");
887 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
888 ArgStringList &CmdArgs) const {
889 for (const auto &LibPath : getFilePaths())
890 if(LibPath.length() > 0)
891 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
894 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
895 ArgStringList &CmdArgs) const {
896 CmdArgs.push_back("-lcc_kext");
899 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
900 ArgStringList &CmdArgs) const {
901 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
902 // (to keep the linker options consistent with gcc and clang itself).
903 if (!isOptimizationLevelFast(Args)) {
904 // Check if -ffast-math or -funsafe-math.
906 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
907 options::OPT_funsafe_math_optimizations,
908 options::OPT_fno_unsafe_math_optimizations);
910 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
911 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
914 // If crtfastmath.o exists add it to the arguments.
915 std::string Path = GetFilePath("crtfastmath.o");
916 if (Path == "crtfastmath.o") // Not found.
919 CmdArgs.push_back(Args.MakeArgString(Path));
923 SanitizerMask ToolChain::getSupportedSanitizers() const {
924 // Return sanitizers which don't require runtime support and are not
925 // platform dependent.
927 SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
928 ~SanitizerKind::Function) |
929 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
930 SanitizerKind::CFICastStrict |
931 SanitizerKind::FloatDivideByZero |
932 SanitizerKind::UnsignedIntegerOverflow |
933 SanitizerKind::ImplicitConversion |
934 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
935 if (getTriple().getArch() == llvm::Triple::x86 ||
936 getTriple().getArch() == llvm::Triple::x86_64 ||
937 getTriple().getArch() == llvm::Triple::arm ||
938 getTriple().getArch() == llvm::Triple::aarch64 ||
939 getTriple().getArch() == llvm::Triple::wasm32 ||
940 getTriple().getArch() == llvm::Triple::wasm64)
941 Res |= SanitizerKind::CFIICall;
942 if (getTriple().getArch() == llvm::Triple::x86_64 ||
943 getTriple().getArch() == llvm::Triple::aarch64)
944 Res |= SanitizerKind::ShadowCallStack;
945 if (getTriple().getArch() == llvm::Triple::aarch64 ||
946 getTriple().getArch() == llvm::Triple::aarch64_be)
947 Res |= SanitizerKind::MemTag;
951 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
952 ArgStringList &CC1Args) const {}
954 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
955 ArgStringList &CC1Args) const {}
957 static VersionTuple separateMSVCFullVersion(unsigned Version) {
959 return VersionTuple(Version);
962 return VersionTuple(Version / 100, Version % 100);
964 unsigned Build = 0, Factor = 1;
965 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
966 Build = Build + (Version % 10) * Factor;
967 return VersionTuple(Version / 100, Version % 100, Build);
971 ToolChain::computeMSVCVersion(const Driver *D,
972 const llvm::opt::ArgList &Args) const {
973 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
974 const Arg *MSCompatibilityVersion =
975 Args.getLastArg(options::OPT_fms_compatibility_version);
977 if (MSCVersion && MSCompatibilityVersion) {
979 D->Diag(diag::err_drv_argument_not_allowed_with)
980 << MSCVersion->getAsString(Args)
981 << MSCompatibilityVersion->getAsString(Args);
982 return VersionTuple();
985 if (MSCompatibilityVersion) {
987 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
989 D->Diag(diag::err_drv_invalid_value)
990 << MSCompatibilityVersion->getAsString(Args)
991 << MSCompatibilityVersion->getValue();
998 unsigned Version = 0;
999 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1001 D->Diag(diag::err_drv_invalid_value)
1002 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1004 return separateMSVCFullVersion(Version);
1008 return VersionTuple();
1011 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1012 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1013 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1014 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1015 const OptTable &Opts = getDriver().getOpts();
1016 bool Modified = false;
1018 // Handle -Xopenmp-target flags
1019 for (auto *A : Args) {
1020 // Exclude flags which may only apply to the host toolchain.
1021 // Do not exclude flags when the host triple (AuxTriple)
1022 // matches the current toolchain triple. If it is not present
1023 // at all, target and host share a toolchain.
1024 if (A->getOption().matches(options::OPT_m_Group)) {
1025 if (SameTripleAsHost)
1034 bool XOpenMPTargetNoTriple =
1035 A->getOption().matches(options::OPT_Xopenmp_target);
1037 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1038 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1039 if (A->getValue(0) == getTripleString())
1040 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1043 } else if (XOpenMPTargetNoTriple) {
1044 // Passing device args: -Xopenmp-target -opt=val.
1045 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1051 // Parse the argument to -Xopenmp-target.
1053 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1054 if (!XOpenMPTargetArg || Index > Prev + 1) {
1055 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1056 << A->getAsString(Args);
1059 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1060 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1061 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1064 XOpenMPTargetArg->setBaseArg(A);
1065 A = XOpenMPTargetArg.release();
1066 AllocatedArgs.push_back(A);