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 "ToolChains/Flang.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Sanitizers.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Driver.h"
20 #include "clang/Driver/DriverDiagnostic.h"
21 #include "clang/Driver/Job.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Driver/SanitizerArgs.h"
24 #include "clang/Driver/XRayArgs.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/MC/MCTargetOptions.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/TargetParser.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/VersionTuple.h"
42 #include "llvm/Support/VirtualFileSystem.h"
48 using namespace clang;
49 using namespace driver;
50 using namespace tools;
52 using namespace llvm::opt;
54 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
55 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
56 options::OPT_fno_rtti, options::OPT_frtti);
59 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
60 const llvm::Triple &Triple,
61 const Arg *CachedRTTIArg) {
62 // Explicit rtti/no-rtti args
64 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
65 return ToolChain::RM_Enabled;
67 return ToolChain::RM_Disabled;
70 // -frtti is default, except for the PS4 CPU.
71 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
76 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
77 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
79 if (auto CXXStdlibPath = getCXXStdlibPath())
80 getFilePaths().push_back(*CXXStdlibPath);
83 if (auto RuntimePath = getRuntimePath())
84 getLibraryPaths().push_back(*RuntimePath);
86 std::string CandidateLibPath = getArchSpecificLibPath();
87 if (getVFS().exists(CandidateLibPath))
88 getFilePaths().push_back(CandidateLibPath);
91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
92 Triple.setEnvironment(Env);
93 if (EffectiveTriple != llvm::Triple())
94 EffectiveTriple.setEnvironment(Env);
97 ToolChain::~ToolChain() = default;
99 llvm::vfs::FileSystem &ToolChain::getVFS() const {
100 return getDriver().getVFS();
103 bool ToolChain::useIntegratedAs() const {
104 return Args.hasFlag(options::OPT_fintegrated_as,
105 options::OPT_fno_integrated_as,
106 IsIntegratedAssemblerDefault());
109 bool ToolChain::useRelaxRelocations() const {
110 return ENABLE_X86_RELAX_RELOCATIONS;
113 bool ToolChain::isNoExecStackDefault() const {
117 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
118 if (!SanitizerArguments.get())
119 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
120 return *SanitizerArguments.get();
123 const XRayArgs& ToolChain::getXRayArgs() const {
124 if (!XRayArguments.get())
125 XRayArguments.reset(new XRayArgs(*this, Args));
126 return *XRayArguments.get();
131 struct DriverSuffix {
133 const char *ModeFlag;
138 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
139 // A list of known driver suffixes. Suffixes are compared against the
140 // program name in order. If there is a match, the frontend type is updated as
141 // necessary by applying the ModeFlag.
142 static const DriverSuffix DriverSuffixes[] = {
144 {"clang++", "--driver-mode=g++"},
145 {"clang-c++", "--driver-mode=g++"},
146 {"clang-cc", nullptr},
147 {"clang-cpp", "--driver-mode=cpp"},
148 {"clang-g++", "--driver-mode=g++"},
149 {"clang-gcc", nullptr},
150 {"clang-cl", "--driver-mode=cl"},
152 {"cpp", "--driver-mode=cpp"},
153 {"cl", "--driver-mode=cl"},
154 {"++", "--driver-mode=g++"},
155 {"flang", "--driver-mode=flang"},
158 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
159 StringRef Suffix(DriverSuffixes[i].Suffix);
160 if (ProgName.endswith(Suffix)) {
161 Pos = ProgName.size() - Suffix.size();
162 return &DriverSuffixes[i];
168 /// Normalize the program name from argv[0] by stripping the file extension if
169 /// present and lower-casing the string on Windows.
170 static std::string normalizeProgramName(llvm::StringRef Argv0) {
171 std::string ProgName = llvm::sys::path::stem(Argv0);
173 // Transform to lowercase for case insensitive file systems.
174 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
179 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
180 // Try to infer frontend type and default target from the program name by
181 // comparing it against DriverSuffixes in order.
183 // If there is a match, the function tries to identify a target as prefix.
184 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
185 // prefix "x86_64-linux". If such a target prefix is found, it may be
186 // added via -target as implicit first argument.
187 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
190 // Try again after stripping any trailing version number:
191 // clang++3.5 -> clang++
192 ProgName = ProgName.rtrim("0123456789.");
193 DS = FindDriverSuffix(ProgName, Pos);
197 // Try again after stripping trailing -component.
198 // clang++-tot -> clang++
199 ProgName = ProgName.slice(0, ProgName.rfind('-'));
200 DS = FindDriverSuffix(ProgName, Pos);
206 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
207 std::string ProgName = normalizeProgramName(PN);
209 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
212 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
214 size_t LastComponent = ProgName.rfind('-', SuffixPos);
215 if (LastComponent == std::string::npos)
216 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
217 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
218 SuffixEnd - LastComponent - 1);
220 // Infer target from the prefix.
221 StringRef Prefix(ProgName);
222 Prefix = Prefix.slice(0, LastComponent);
223 std::string IgnoredError;
224 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
225 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
228 StringRef ToolChain::getDefaultUniversalArchName() const {
229 // In universal driver terms, the arch name accepted by -arch isn't exactly
230 // the same as the ones that appear in the triple. Roughly speaking, this is
231 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
232 // only interesting special case is powerpc.
233 switch (Triple.getArch()) {
234 case llvm::Triple::ppc:
236 case llvm::Triple::ppc64:
238 case llvm::Triple::ppc64le:
241 return Triple.getArchName();
245 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
246 return Input.getFilename();
249 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
253 Tool *ToolChain::getClang() const {
255 Clang.reset(new tools::Clang(*this));
259 Tool *ToolChain::getFlang() const {
261 Flang.reset(new tools::Flang(*this));
265 Tool *ToolChain::buildAssembler() const {
266 return new tools::ClangAs(*this);
269 Tool *ToolChain::buildLinker() const {
270 llvm_unreachable("Linking is not supported by this toolchain");
273 Tool *ToolChain::getAssemble() const {
275 Assemble.reset(buildAssembler());
276 return Assemble.get();
279 Tool *ToolChain::getClangAs() const {
281 Assemble.reset(new tools::ClangAs(*this));
282 return Assemble.get();
285 Tool *ToolChain::getLink() const {
287 Link.reset(buildLinker());
291 Tool *ToolChain::getIfsMerge() const {
293 IfsMerge.reset(new tools::ifstool::Merger(*this));
294 return IfsMerge.get();
297 Tool *ToolChain::getOffloadBundler() const {
299 OffloadBundler.reset(new tools::OffloadBundler(*this));
300 return OffloadBundler.get();
303 Tool *ToolChain::getOffloadWrapper() const {
305 OffloadWrapper.reset(new tools::OffloadWrapper(*this));
306 return OffloadWrapper.get();
309 Tool *ToolChain::getTool(Action::ActionClass AC) const {
311 case Action::AssembleJobClass:
312 return getAssemble();
314 case Action::IfsMergeJobClass:
315 return getIfsMerge();
317 case Action::LinkJobClass:
320 case Action::InputClass:
321 case Action::BindArchClass:
322 case Action::OffloadClass:
323 case Action::LipoJobClass:
324 case Action::DsymutilJobClass:
325 case Action::VerifyDebugInfoJobClass:
326 llvm_unreachable("Invalid tool kind.");
328 case Action::CompileJobClass:
329 case Action::PrecompileJobClass:
330 case Action::HeaderModulePrecompileJobClass:
331 case Action::PreprocessJobClass:
332 case Action::AnalyzeJobClass:
333 case Action::MigrateJobClass:
334 case Action::VerifyPCHJobClass:
335 case Action::BackendJobClass:
338 case Action::OffloadBundlingJobClass:
339 case Action::OffloadUnbundlingJobClass:
340 return getOffloadBundler();
342 case Action::OffloadWrapperJobClass:
343 return getOffloadWrapper();
346 llvm_unreachable("Invalid tool kind.");
349 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
350 const ArgList &Args) {
351 const llvm::Triple &Triple = TC.getTriple();
352 bool IsWindows = Triple.isOSWindows();
354 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
355 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
359 // For historic reasons, Android library is using i686 instead of i386.
360 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
363 return llvm::Triple::getArchTypeName(TC.getArch());
366 StringRef ToolChain::getOSLibName() const {
367 switch (Triple.getOS()) {
368 case llvm::Triple::FreeBSD:
370 case llvm::Triple::NetBSD:
372 case llvm::Triple::OpenBSD:
374 case llvm::Triple::Solaris:
381 std::string ToolChain::getCompilerRTPath() const {
382 SmallString<128> Path(getDriver().ResourceDir);
383 if (Triple.isOSUnknown()) {
384 llvm::sys::path::append(Path, "lib");
386 llvm::sys::path::append(Path, "lib", getOSLibName());
391 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
392 FileType Type) const {
393 const llvm::Triple &TT = getTriple();
394 bool IsITANMSVCWindows =
395 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
398 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
401 case ToolChain::FT_Object:
402 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
404 case ToolChain::FT_Static:
405 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
407 case ToolChain::FT_Shared:
408 Suffix = Triple.isOSWindows()
409 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
414 for (const auto &LibPath : getLibraryPaths()) {
415 SmallString<128> P(LibPath);
416 llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
417 if (getVFS().exists(P))
421 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
422 const char *Env = TT.isAndroid() ? "-android" : "";
423 SmallString<128> Path(getCompilerRTPath());
424 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
425 Arch + Env + Suffix);
429 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
431 FileType Type) const {
432 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
436 Optional<std::string> ToolChain::getRuntimePath() const {
439 // First try the triple passed to driver as --target=<triple>.
440 P.assign(D.ResourceDir);
441 llvm::sys::path::append(P, "lib", D.getTargetTriple());
442 if (getVFS().exists(P))
443 return llvm::Optional<std::string>(P.str());
445 // Second try the normalized triple.
446 P.assign(D.ResourceDir);
447 llvm::sys::path::append(P, "lib", Triple.str());
448 if (getVFS().exists(P))
449 return llvm::Optional<std::string>(P.str());
454 Optional<std::string> ToolChain::getCXXStdlibPath() const {
457 // First try the triple passed to driver as --target=<triple>.
459 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
460 if (getVFS().exists(P))
461 return llvm::Optional<std::string>(P.str());
463 // Second try the normalized triple.
465 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
466 if (getVFS().exists(P))
467 return llvm::Optional<std::string>(P.str());
472 std::string ToolChain::getArchSpecificLibPath() const {
473 SmallString<128> Path(getDriver().ResourceDir);
474 llvm::sys::path::append(Path, "lib", getOSLibName(),
475 llvm::Triple::getArchTypeName(getArch()));
479 bool ToolChain::needsProfileRT(const ArgList &Args) {
480 if (Args.hasArg(options::OPT_noprofilelib))
483 if (needsGCovInstrumentation(Args) ||
484 Args.hasArg(options::OPT_fprofile_generate) ||
485 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
486 Args.hasArg(options::OPT_fcs_profile_generate) ||
487 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
488 Args.hasArg(options::OPT_fprofile_instr_generate) ||
489 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
490 Args.hasArg(options::OPT_fcreate_profile) ||
491 Args.hasArg(options::OPT_forder_file_instrumentation))
497 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
498 return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
500 Args.hasArg(options::OPT_coverage);
503 Tool *ToolChain::SelectTool(const JobAction &JA) const {
504 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
505 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
506 Action::ActionClass AC = JA.getKind();
507 if (AC == Action::AssembleJobClass && useIntegratedAs())
512 std::string ToolChain::GetFilePath(const char *Name) const {
513 return D.GetFilePath(Name, *this);
516 std::string ToolChain::GetProgramPath(const char *Name) const {
517 return D.GetProgramPath(Name, *this);
520 std::string ToolChain::GetLinkerPath() const {
521 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
522 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
524 if (llvm::sys::path::is_absolute(UseLinker)) {
525 // If we're passed what looks like an absolute path, don't attempt to
526 // second-guess that.
527 if (llvm::sys::fs::can_execute(UseLinker))
529 } else if (UseLinker.empty() || UseLinker == "ld") {
530 // If we're passed -fuse-ld= with no argument, or with the argument ld,
531 // then use whatever the default system linker is.
532 return GetProgramPath(getDefaultLinker());
534 llvm::SmallString<8> LinkerName;
535 if (Triple.isOSDarwin())
536 LinkerName.append("ld64.");
538 LinkerName.append("ld.");
539 LinkerName.append(UseLinker);
541 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
542 if (llvm::sys::fs::can_execute(LinkerPath))
547 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
549 return GetProgramPath(getDefaultLinker());
552 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
553 types::ID id = types::lookupTypeForExtension(Ext);
555 // Flang always runs the preprocessor and has no notion of "preprocessed
556 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
558 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
559 id = types::TY_Fortran;
564 bool ToolChain::HasNativeLLVMSupport() const {
568 bool ToolChain::isCrossCompiling() const {
569 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
570 switch (HostTriple.getArch()) {
571 // The A32/T32/T16 instruction sets are not separate architectures in this
573 case llvm::Triple::arm:
574 case llvm::Triple::armeb:
575 case llvm::Triple::thumb:
576 case llvm::Triple::thumbeb:
577 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
578 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
580 return HostTriple.getArch() != getArch();
584 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
585 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
589 llvm::ExceptionHandling
590 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
591 return llvm::ExceptionHandling::None;
594 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
595 if (Model == "single") {
596 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
597 return Triple.getArch() == llvm::Triple::arm ||
598 Triple.getArch() == llvm::Triple::armeb ||
599 Triple.getArch() == llvm::Triple::thumb ||
600 Triple.getArch() == llvm::Triple::thumbeb ||
601 Triple.getArch() == llvm::Triple::wasm32 ||
602 Triple.getArch() == llvm::Triple::wasm64;
603 } else if (Model == "posix")
609 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
610 types::ID InputType) const {
611 switch (getTriple().getArch()) {
613 return getTripleString();
615 case llvm::Triple::x86_64: {
616 llvm::Triple Triple = getTriple();
617 if (!Triple.isOSBinFormatMachO())
618 return getTripleString();
620 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
621 // x86_64h goes in the triple. Other -march options just use the
622 // vanilla triple we already have.
623 StringRef MArch = A->getValue();
624 if (MArch == "x86_64h")
625 Triple.setArchName(MArch);
627 return Triple.getTriple();
629 case llvm::Triple::aarch64: {
630 llvm::Triple Triple = getTriple();
631 if (!Triple.isOSBinFormatMachO())
632 return getTripleString();
634 // FIXME: older versions of ld64 expect the "arm64" component in the actual
635 // triple string and query it to determine whether an LTO file can be
636 // handled. Remove this when we don't care any more.
637 Triple.setArchName("arm64");
638 return Triple.getTriple();
640 case llvm::Triple::aarch64_32:
641 return getTripleString();
642 case llvm::Triple::arm:
643 case llvm::Triple::armeb:
644 case llvm::Triple::thumb:
645 case llvm::Triple::thumbeb: {
646 // FIXME: Factor into subclasses.
647 llvm::Triple Triple = getTriple();
648 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
649 getTriple().getArch() == llvm::Triple::thumbeb;
651 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
652 // '-mbig-endian'/'-EB'.
653 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
654 options::OPT_mbig_endian)) {
655 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
658 // Thumb2 is the default for V7 on Darwin.
660 // FIXME: Thumb should just be another -target-feaure, not in the triple.
661 StringRef MCPU, MArch;
662 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
663 MCPU = A->getValue();
664 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
665 MArch = A->getValue();
667 Triple.isOSBinFormatMachO()
668 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
669 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
671 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
672 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
673 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
674 getTriple().isOSBinFormatMachO());
675 // FIXME: this is invalid for WindowsCE
676 if (getTriple().isOSWindows())
678 std::string ArchName;
684 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
685 // M-Class CPUs/architecture variants, which is not supported.
686 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
687 options::OPT_mno_thumb, ThumbDefault);
688 if (IsMProfile && ARMModeRequested) {
690 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
692 getDriver().Diag(diag::err_arch_unsupported_isa)
693 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
696 // Check to see if an explicit choice to use thumb has been made via
697 // -mthumb. For assembler files we must check for -mthumb in the options
698 // passed to the assembler via -Wa or -Xassembler.
699 bool IsThumb = false;
700 if (InputType != types::TY_PP_Asm)
701 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
704 // Ideally we would check for these flags in
705 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
706 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
709 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
710 for (StringRef Value : A->getValues()) {
711 if (Value == "-mthumb")
716 // Assembly files should start in ARM mode, unless arch is M-profile, or
717 // -mthumb has been passed explicitly to the assembler. Windows is always
719 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
721 ArchName = "thumbeb";
725 Triple.setArchName(ArchName + Suffix.str());
727 return Triple.getTriple();
732 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
733 types::ID InputType) const {
734 return ComputeLLVMTriple(Args, InputType);
737 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
738 ArgStringList &CC1Args) const {
739 // Each toolchain should provide the appropriate include flags.
742 void ToolChain::addClangTargetOptions(
743 const ArgList &DriverArgs, ArgStringList &CC1Args,
744 Action::OffloadKind DeviceOffloadKind) const {}
746 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
748 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
749 llvm::opt::ArgStringList &CmdArgs) const {
750 if (!needsProfileRT(Args)) return;
752 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
755 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
756 const ArgList &Args) const {
757 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
758 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
760 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
761 if (LibName == "compiler-rt")
762 return ToolChain::RLT_CompilerRT;
763 else if (LibName == "libgcc")
764 return ToolChain::RLT_Libgcc;
765 else if (LibName == "platform")
766 return GetDefaultRuntimeLibType();
769 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
771 return GetDefaultRuntimeLibType();
774 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
775 const ArgList &Args) const {
776 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
777 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
779 if (LibName == "none")
780 return ToolChain::UNW_None;
781 else if (LibName == "platform" || LibName == "") {
782 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
783 if (RtLibType == ToolChain::RLT_CompilerRT)
784 return ToolChain::UNW_None;
785 else if (RtLibType == ToolChain::RLT_Libgcc)
786 return ToolChain::UNW_Libgcc;
787 } else if (LibName == "libunwind") {
788 if (GetRuntimeLibType(Args) == RLT_Libgcc)
789 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
790 return ToolChain::UNW_CompilerRT;
791 } else if (LibName == "libgcc")
792 return ToolChain::UNW_Libgcc;
795 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
796 << A->getAsString(Args);
798 return GetDefaultUnwindLibType();
801 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
802 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
803 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
805 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
806 if (LibName == "libc++")
807 return ToolChain::CST_Libcxx;
808 else if (LibName == "libstdc++")
809 return ToolChain::CST_Libstdcxx;
810 else if (LibName == "platform")
811 return GetDefaultCXXStdlibType();
814 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
816 return GetDefaultCXXStdlibType();
819 /// Utility function to add a system include directory to CC1 arguments.
820 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
821 ArgStringList &CC1Args,
823 CC1Args.push_back("-internal-isystem");
824 CC1Args.push_back(DriverArgs.MakeArgString(Path));
827 /// Utility function to add a system include directory with extern "C"
828 /// semantics to CC1 arguments.
830 /// Note that this should be used rarely, and only for directories that
831 /// historically and for legacy reasons are treated as having implicit extern
832 /// "C" semantics. These semantics are *ignored* by and large today, but its
833 /// important to preserve the preprocessor changes resulting from the
835 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
836 ArgStringList &CC1Args,
838 CC1Args.push_back("-internal-externc-isystem");
839 CC1Args.push_back(DriverArgs.MakeArgString(Path));
842 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
843 ArgStringList &CC1Args,
845 if (llvm::sys::fs::exists(Path))
846 addExternCSystemInclude(DriverArgs, CC1Args, Path);
849 /// Utility function to add a list of system include directories to CC1.
850 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
851 ArgStringList &CC1Args,
852 ArrayRef<StringRef> Paths) {
853 for (const auto &Path : Paths) {
854 CC1Args.push_back("-internal-isystem");
855 CC1Args.push_back(DriverArgs.MakeArgString(Path));
859 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
860 ArgStringList &CC1Args) const {
861 // Header search paths should be handled by each of the subclasses.
862 // Historically, they have not been, and instead have been handled inside of
863 // the CC1-layer frontend. As the logic is hoisted out, this generic function
864 // will slowly stop being called.
866 // While it is being called, replicate a bit of a hack to propagate the
867 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
868 // header search paths with it. Once all systems are overriding this
869 // function, the CC1 flag and this line can be removed.
870 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
873 void ToolChain::AddClangCXXStdlibIsystemArgs(
874 const llvm::opt::ArgList &DriverArgs,
875 llvm::opt::ArgStringList &CC1Args) const {
876 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
877 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
879 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
880 addSystemInclude(DriverArgs, CC1Args, P);
883 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
884 return getDriver().CCCIsCXX() &&
885 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
886 options::OPT_nostdlibxx);
889 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
890 ArgStringList &CmdArgs) const {
891 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
892 "should not have called this");
893 CXXStdlibType Type = GetCXXStdlibType(Args);
896 case ToolChain::CST_Libcxx:
897 CmdArgs.push_back("-lc++");
900 case ToolChain::CST_Libstdcxx:
901 CmdArgs.push_back("-lstdc++");
906 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
907 ArgStringList &CmdArgs) const {
908 for (const auto &LibPath : getFilePaths())
909 if(LibPath.length() > 0)
910 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
913 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
914 ArgStringList &CmdArgs) const {
915 CmdArgs.push_back("-lcc_kext");
918 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
919 ArgStringList &CmdArgs) const {
920 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
921 // (to keep the linker options consistent with gcc and clang itself).
922 if (!isOptimizationLevelFast(Args)) {
923 // Check if -ffast-math or -funsafe-math.
925 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
926 options::OPT_funsafe_math_optimizations,
927 options::OPT_fno_unsafe_math_optimizations);
929 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
930 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
933 // If crtfastmath.o exists add it to the arguments.
934 std::string Path = GetFilePath("crtfastmath.o");
935 if (Path == "crtfastmath.o") // Not found.
938 CmdArgs.push_back(Args.MakeArgString(Path));
942 SanitizerMask ToolChain::getSupportedSanitizers() const {
943 // Return sanitizers which don't require runtime support and are not
944 // platform dependent.
946 SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
947 ~SanitizerKind::Function) |
948 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
949 SanitizerKind::CFICastStrict |
950 SanitizerKind::FloatDivideByZero |
951 SanitizerKind::UnsignedIntegerOverflow |
952 SanitizerKind::ImplicitConversion |
953 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
954 if (getTriple().getArch() == llvm::Triple::x86 ||
955 getTriple().getArch() == llvm::Triple::x86_64 ||
956 getTriple().getArch() == llvm::Triple::arm ||
957 getTriple().getArch() == llvm::Triple::wasm32 ||
958 getTriple().getArch() == llvm::Triple::wasm64 || getTriple().isAArch64())
959 Res |= SanitizerKind::CFIICall;
960 if (getTriple().getArch() == llvm::Triple::x86_64 || getTriple().isAArch64())
961 Res |= SanitizerKind::ShadowCallStack;
962 if (getTriple().isAArch64())
963 Res |= SanitizerKind::MemTag;
967 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
968 ArgStringList &CC1Args) const {}
970 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
971 ArgStringList &CC1Args) const {}
973 static VersionTuple separateMSVCFullVersion(unsigned Version) {
975 return VersionTuple(Version);
978 return VersionTuple(Version / 100, Version % 100);
980 unsigned Build = 0, Factor = 1;
981 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
982 Build = Build + (Version % 10) * Factor;
983 return VersionTuple(Version / 100, Version % 100, Build);
987 ToolChain::computeMSVCVersion(const Driver *D,
988 const llvm::opt::ArgList &Args) const {
989 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
990 const Arg *MSCompatibilityVersion =
991 Args.getLastArg(options::OPT_fms_compatibility_version);
993 if (MSCVersion && MSCompatibilityVersion) {
995 D->Diag(diag::err_drv_argument_not_allowed_with)
996 << MSCVersion->getAsString(Args)
997 << MSCompatibilityVersion->getAsString(Args);
998 return VersionTuple();
1001 if (MSCompatibilityVersion) {
1003 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1005 D->Diag(diag::err_drv_invalid_value)
1006 << MSCompatibilityVersion->getAsString(Args)
1007 << MSCompatibilityVersion->getValue();
1014 unsigned Version = 0;
1015 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1017 D->Diag(diag::err_drv_invalid_value)
1018 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1020 return separateMSVCFullVersion(Version);
1024 return VersionTuple();
1027 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1028 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1029 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1030 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1031 const OptTable &Opts = getDriver().getOpts();
1032 bool Modified = false;
1034 // Handle -Xopenmp-target flags
1035 for (auto *A : Args) {
1036 // Exclude flags which may only apply to the host toolchain.
1037 // Do not exclude flags when the host triple (AuxTriple)
1038 // matches the current toolchain triple. If it is not present
1039 // at all, target and host share a toolchain.
1040 if (A->getOption().matches(options::OPT_m_Group)) {
1041 if (SameTripleAsHost)
1050 bool XOpenMPTargetNoTriple =
1051 A->getOption().matches(options::OPT_Xopenmp_target);
1053 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1054 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1055 if (A->getValue(0) == getTripleString())
1056 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1059 } else if (XOpenMPTargetNoTriple) {
1060 // Passing device args: -Xopenmp-target -opt=val.
1061 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1067 // Parse the argument to -Xopenmp-target.
1069 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1070 if (!XOpenMPTargetArg || Index > Prev + 1) {
1071 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1072 << A->getAsString(Args);
1075 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1076 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1077 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1080 XOpenMPTargetArg->setBaseArg(A);
1081 A = XOpenMPTargetArg.release();
1082 AllocatedArgs.push_back(A);