1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/ToolChain.h"
11 #include "InputInfo.h"
12 #include "ToolChains/Arch/ARM.h"
13 #include "ToolChains/Clang.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)) {
79 P.assign(D.ResourceDir);
80 llvm::sys::path::append(P, D.getTargetTriple(), "lib");
81 if (getVFS().exists(P))
82 getLibraryPaths().push_back(P.str());
84 P.assign(D.ResourceDir);
85 llvm::sys::path::append(P, Triple.str(), "lib");
86 if (getVFS().exists(P))
87 getLibraryPaths().push_back(P.str());
89 std::string CandidateLibPath = getArchSpecificLibPath();
90 if (getVFS().exists(CandidateLibPath))
91 getFilePaths().push_back(CandidateLibPath);
94 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
95 Triple.setEnvironment(Env);
96 if (EffectiveTriple != llvm::Triple())
97 EffectiveTriple.setEnvironment(Env);
100 ToolChain::~ToolChain() = default;
102 llvm::vfs::FileSystem &ToolChain::getVFS() const {
103 return getDriver().getVFS();
106 bool ToolChain::useIntegratedAs() const {
107 return Args.hasFlag(options::OPT_fintegrated_as,
108 options::OPT_fno_integrated_as,
109 IsIntegratedAssemblerDefault());
112 bool ToolChain::useRelaxRelocations() const {
113 return ENABLE_X86_RELAX_RELOCATIONS;
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::getOffloadBundler() const {
285 OffloadBundler.reset(new tools::OffloadBundler(*this));
286 return OffloadBundler.get();
289 Tool *ToolChain::getTool(Action::ActionClass AC) const {
291 case Action::AssembleJobClass:
292 return getAssemble();
294 case Action::LinkJobClass:
297 case Action::InputClass:
298 case Action::BindArchClass:
299 case Action::OffloadClass:
300 case Action::LipoJobClass:
301 case Action::DsymutilJobClass:
302 case Action::VerifyDebugInfoJobClass:
303 llvm_unreachable("Invalid tool kind.");
305 case Action::CompileJobClass:
306 case Action::PrecompileJobClass:
307 case Action::HeaderModulePrecompileJobClass:
308 case Action::PreprocessJobClass:
309 case Action::AnalyzeJobClass:
310 case Action::MigrateJobClass:
311 case Action::VerifyPCHJobClass:
312 case Action::BackendJobClass:
315 case Action::OffloadBundlingJobClass:
316 case Action::OffloadUnbundlingJobClass:
317 return getOffloadBundler();
320 llvm_unreachable("Invalid tool kind.");
323 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
324 const ArgList &Args) {
325 const llvm::Triple &Triple = TC.getTriple();
326 bool IsWindows = Triple.isOSWindows();
328 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
329 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
333 // For historic reasons, Android library is using i686 instead of i386.
334 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
337 return llvm::Triple::getArchTypeName(TC.getArch());
340 StringRef ToolChain::getOSLibName() const {
341 switch (Triple.getOS()) {
342 case llvm::Triple::FreeBSD:
344 case llvm::Triple::NetBSD:
346 case llvm::Triple::OpenBSD:
348 case llvm::Triple::Solaris:
355 std::string ToolChain::getCompilerRTPath() const {
356 SmallString<128> Path(getDriver().ResourceDir);
357 if (Triple.isOSUnknown()) {
358 llvm::sys::path::append(Path, "lib");
360 llvm::sys::path::append(Path, "lib", getOSLibName());
365 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
367 const llvm::Triple &TT = getTriple();
368 bool IsITANMSVCWindows =
369 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
371 const char *Prefix = IsITANMSVCWindows ? "" : "lib";
372 const char *Suffix = Shared ? (Triple.isOSWindows() ? ".lib" : ".so")
373 : (IsITANMSVCWindows ? ".lib" : ".a");
374 if (Shared && Triple.isWindowsGNUEnvironment())
377 for (const auto &LibPath : getLibraryPaths()) {
378 SmallString<128> P(LibPath);
379 llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
380 if (getVFS().exists(P))
384 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
385 const char *Env = TT.isAndroid() ? "-android" : "";
386 SmallString<128> Path(getCompilerRTPath());
387 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
388 Arch + Env + Suffix);
392 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
395 return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
398 std::string ToolChain::getArchSpecificLibPath() const {
399 SmallString<128> Path(getDriver().ResourceDir);
400 llvm::sys::path::append(Path, "lib", getOSLibName(),
401 llvm::Triple::getArchTypeName(getArch()));
405 bool ToolChain::needsProfileRT(const ArgList &Args) {
406 if (needsGCovInstrumentation(Args) ||
407 Args.hasArg(options::OPT_fprofile_generate) ||
408 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
409 Args.hasArg(options::OPT_fprofile_instr_generate) ||
410 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
411 Args.hasArg(options::OPT_fcreate_profile))
417 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
418 return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
420 Args.hasArg(options::OPT_coverage);
423 Tool *ToolChain::SelectTool(const JobAction &JA) const {
424 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
425 Action::ActionClass AC = JA.getKind();
426 if (AC == Action::AssembleJobClass && useIntegratedAs())
431 std::string ToolChain::GetFilePath(const char *Name) const {
432 return D.GetFilePath(Name, *this);
435 std::string ToolChain::GetProgramPath(const char *Name) const {
436 return D.GetProgramPath(Name, *this);
439 std::string ToolChain::GetLinkerPath() const {
440 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
441 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
443 if (llvm::sys::path::is_absolute(UseLinker)) {
444 // If we're passed what looks like an absolute path, don't attempt to
445 // second-guess that.
446 if (llvm::sys::fs::can_execute(UseLinker))
448 } else if (UseLinker.empty() || UseLinker == "ld") {
449 // If we're passed -fuse-ld= with no argument, or with the argument ld,
450 // then use whatever the default system linker is.
451 return GetProgramPath(getDefaultLinker());
453 llvm::SmallString<8> LinkerName;
454 if (Triple.isOSDarwin())
455 LinkerName.append("ld64.");
457 LinkerName.append("ld.");
458 LinkerName.append(UseLinker);
460 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
461 if (llvm::sys::fs::can_execute(LinkerPath))
466 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
468 return GetProgramPath(getDefaultLinker());
471 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
472 return types::lookupTypeForExtension(Ext);
475 bool ToolChain::HasNativeLLVMSupport() const {
479 bool ToolChain::isCrossCompiling() const {
480 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
481 switch (HostTriple.getArch()) {
482 // The A32/T32/T16 instruction sets are not separate architectures in this
484 case llvm::Triple::arm:
485 case llvm::Triple::armeb:
486 case llvm::Triple::thumb:
487 case llvm::Triple::thumbeb:
488 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
489 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
491 return HostTriple.getArch() != getArch();
495 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
496 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
500 llvm::ExceptionHandling
501 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
502 return llvm::ExceptionHandling::None;
505 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
506 if (Model == "single") {
507 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
508 return Triple.getArch() == llvm::Triple::arm ||
509 Triple.getArch() == llvm::Triple::armeb ||
510 Triple.getArch() == llvm::Triple::thumb ||
511 Triple.getArch() == llvm::Triple::thumbeb ||
512 Triple.getArch() == llvm::Triple::wasm32 ||
513 Triple.getArch() == llvm::Triple::wasm64;
514 } else if (Model == "posix")
520 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
521 types::ID InputType) const {
522 switch (getTriple().getArch()) {
524 return getTripleString();
526 case llvm::Triple::x86_64: {
527 llvm::Triple Triple = getTriple();
528 if (!Triple.isOSBinFormatMachO())
529 return getTripleString();
531 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
532 // x86_64h goes in the triple. Other -march options just use the
533 // vanilla triple we already have.
534 StringRef MArch = A->getValue();
535 if (MArch == "x86_64h")
536 Triple.setArchName(MArch);
538 return Triple.getTriple();
540 case llvm::Triple::aarch64: {
541 llvm::Triple Triple = getTriple();
542 if (!Triple.isOSBinFormatMachO())
543 return getTripleString();
545 // FIXME: older versions of ld64 expect the "arm64" component in the actual
546 // triple string and query it to determine whether an LTO file can be
547 // handled. Remove this when we don't care any more.
548 Triple.setArchName("arm64");
549 return Triple.getTriple();
551 case llvm::Triple::arm:
552 case llvm::Triple::armeb:
553 case llvm::Triple::thumb:
554 case llvm::Triple::thumbeb: {
555 // FIXME: Factor into subclasses.
556 llvm::Triple Triple = getTriple();
557 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
558 getTriple().getArch() == llvm::Triple::thumbeb;
560 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
561 // '-mbig-endian'/'-EB'.
562 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
563 options::OPT_mbig_endian)) {
564 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
567 // Thumb2 is the default for V7 on Darwin.
569 // FIXME: Thumb should just be another -target-feaure, not in the triple.
570 StringRef MCPU, MArch;
571 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
572 MCPU = A->getValue();
573 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
574 MArch = A->getValue();
576 Triple.isOSBinFormatMachO()
577 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
578 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
580 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
581 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
582 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
583 getTriple().isOSBinFormatMachO());
584 // FIXME: this is invalid for WindowsCE
585 if (getTriple().isOSWindows())
587 std::string ArchName;
593 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
594 // M-Class CPUs/architecture variants, which is not supported.
595 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
596 options::OPT_mno_thumb, ThumbDefault);
597 if (IsMProfile && ARMModeRequested) {
599 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
601 getDriver().Diag(diag::err_arch_unsupported_isa)
602 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
605 // Check to see if an explicit choice to use thumb has been made via
606 // -mthumb. For assembler files we must check for -mthumb in the options
607 // passed to the assembler via -Wa or -Xassembler.
608 bool IsThumb = false;
609 if (InputType != types::TY_PP_Asm)
610 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
613 // Ideally we would check for these flags in
614 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
615 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
618 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
619 for (StringRef Value : A->getValues()) {
620 if (Value == "-mthumb")
625 // Assembly files should start in ARM mode, unless arch is M-profile, or
626 // -mthumb has been passed explicitly to the assembler. Windows is always
628 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
630 ArchName = "thumbeb";
634 Triple.setArchName(ArchName + Suffix.str());
636 return Triple.getTriple();
641 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
642 types::ID InputType) const {
643 return ComputeLLVMTriple(Args, InputType);
646 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
647 ArgStringList &CC1Args) const {
648 // Each toolchain should provide the appropriate include flags.
651 void ToolChain::addClangTargetOptions(
652 const ArgList &DriverArgs, ArgStringList &CC1Args,
653 Action::OffloadKind DeviceOffloadKind) const {}
655 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
657 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
658 llvm::opt::ArgStringList &CmdArgs) const {
659 if (!needsProfileRT(Args)) return;
661 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
664 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
665 const ArgList &Args) const {
666 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
667 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
669 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
670 if (LibName == "compiler-rt")
671 return ToolChain::RLT_CompilerRT;
672 else if (LibName == "libgcc")
673 return ToolChain::RLT_Libgcc;
674 else if (LibName == "platform")
675 return GetDefaultRuntimeLibType();
678 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
680 return GetDefaultRuntimeLibType();
683 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
684 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
685 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
687 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
688 if (LibName == "libc++")
689 return ToolChain::CST_Libcxx;
690 else if (LibName == "libstdc++")
691 return ToolChain::CST_Libstdcxx;
692 else if (LibName == "platform")
693 return GetDefaultCXXStdlibType();
696 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
698 return GetDefaultCXXStdlibType();
701 /// Utility function to add a system include directory to CC1 arguments.
702 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
703 ArgStringList &CC1Args,
705 CC1Args.push_back("-internal-isystem");
706 CC1Args.push_back(DriverArgs.MakeArgString(Path));
709 /// Utility function to add a system include directory with extern "C"
710 /// semantics to CC1 arguments.
712 /// Note that this should be used rarely, and only for directories that
713 /// historically and for legacy reasons are treated as having implicit extern
714 /// "C" semantics. These semantics are *ignored* by and large today, but its
715 /// important to preserve the preprocessor changes resulting from the
717 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
718 ArgStringList &CC1Args,
720 CC1Args.push_back("-internal-externc-isystem");
721 CC1Args.push_back(DriverArgs.MakeArgString(Path));
724 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
725 ArgStringList &CC1Args,
727 if (llvm::sys::fs::exists(Path))
728 addExternCSystemInclude(DriverArgs, CC1Args, Path);
731 /// Utility function to add a list of system include directories to CC1.
732 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
733 ArgStringList &CC1Args,
734 ArrayRef<StringRef> Paths) {
735 for (const auto Path : Paths) {
736 CC1Args.push_back("-internal-isystem");
737 CC1Args.push_back(DriverArgs.MakeArgString(Path));
741 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
742 ArgStringList &CC1Args) const {
743 // Header search paths should be handled by each of the subclasses.
744 // Historically, they have not been, and instead have been handled inside of
745 // the CC1-layer frontend. As the logic is hoisted out, this generic function
746 // will slowly stop being called.
748 // While it is being called, replicate a bit of a hack to propagate the
749 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
750 // header search paths with it. Once all systems are overriding this
751 // function, the CC1 flag and this line can be removed.
752 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
755 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
756 return getDriver().CCCIsCXX() &&
757 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
758 options::OPT_nostdlibxx);
761 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
762 ArgStringList &CmdArgs) const {
763 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
764 "should not have called this");
765 CXXStdlibType Type = GetCXXStdlibType(Args);
768 case ToolChain::CST_Libcxx:
769 CmdArgs.push_back("-lc++");
772 case ToolChain::CST_Libstdcxx:
773 CmdArgs.push_back("-lstdc++");
778 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
779 ArgStringList &CmdArgs) const {
780 for (const auto &LibPath : getLibraryPaths())
781 if(LibPath.length() > 0)
782 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
784 for (const auto &LibPath : getFilePaths())
785 if(LibPath.length() > 0)
786 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
789 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
790 ArgStringList &CmdArgs) const {
791 CmdArgs.push_back("-lcc_kext");
794 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
795 ArgStringList &CmdArgs) const {
796 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
797 // (to keep the linker options consistent with gcc and clang itself).
798 if (!isOptimizationLevelFast(Args)) {
799 // Check if -ffast-math or -funsafe-math.
801 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
802 options::OPT_funsafe_math_optimizations,
803 options::OPT_fno_unsafe_math_optimizations);
805 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
806 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
809 // If crtfastmath.o exists add it to the arguments.
810 std::string Path = GetFilePath("crtfastmath.o");
811 if (Path == "crtfastmath.o") // Not found.
814 CmdArgs.push_back(Args.MakeArgString(Path));
818 SanitizerMask ToolChain::getSupportedSanitizers() const {
819 // Return sanitizers which don't require runtime support and are not
820 // platform dependent.
822 using namespace SanitizerKind;
824 SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
825 CFICastStrict | UnsignedIntegerOverflow |
826 ImplicitConversion | Nullability | LocalBounds;
827 if (getTriple().getArch() == llvm::Triple::x86 ||
828 getTriple().getArch() == llvm::Triple::x86_64 ||
829 getTriple().getArch() == llvm::Triple::arm ||
830 getTriple().getArch() == llvm::Triple::aarch64 ||
831 getTriple().getArch() == llvm::Triple::wasm32 ||
832 getTriple().getArch() == llvm::Triple::wasm64)
834 if (getTriple().getArch() == llvm::Triple::x86_64 ||
835 getTriple().getArch() == llvm::Triple::aarch64)
836 Res |= ShadowCallStack;
840 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
841 ArgStringList &CC1Args) const {}
843 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
844 ArgStringList &CC1Args) const {}
846 static VersionTuple separateMSVCFullVersion(unsigned Version) {
848 return VersionTuple(Version);
851 return VersionTuple(Version / 100, Version % 100);
853 unsigned Build = 0, Factor = 1;
854 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
855 Build = Build + (Version % 10) * Factor;
856 return VersionTuple(Version / 100, Version % 100, Build);
860 ToolChain::computeMSVCVersion(const Driver *D,
861 const llvm::opt::ArgList &Args) const {
862 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
863 const Arg *MSCompatibilityVersion =
864 Args.getLastArg(options::OPT_fms_compatibility_version);
866 if (MSCVersion && MSCompatibilityVersion) {
868 D->Diag(diag::err_drv_argument_not_allowed_with)
869 << MSCVersion->getAsString(Args)
870 << MSCompatibilityVersion->getAsString(Args);
871 return VersionTuple();
874 if (MSCompatibilityVersion) {
876 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
878 D->Diag(diag::err_drv_invalid_value)
879 << MSCompatibilityVersion->getAsString(Args)
880 << MSCompatibilityVersion->getValue();
887 unsigned Version = 0;
888 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
890 D->Diag(diag::err_drv_invalid_value)
891 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
893 return separateMSVCFullVersion(Version);
897 return VersionTuple();
900 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
901 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
902 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
903 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
904 const OptTable &Opts = getDriver().getOpts();
905 bool Modified = false;
907 // Handle -Xopenmp-target flags
908 for (auto *A : Args) {
909 // Exclude flags which may only apply to the host toolchain.
910 // Do not exclude flags when the host triple (AuxTriple)
911 // matches the current toolchain triple. If it is not present
912 // at all, target and host share a toolchain.
913 if (A->getOption().matches(options::OPT_m_Group)) {
914 if (SameTripleAsHost)
923 bool XOpenMPTargetNoTriple =
924 A->getOption().matches(options::OPT_Xopenmp_target);
926 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
927 // Passing device args: -Xopenmp-target=<triple> -opt=val.
928 if (A->getValue(0) == getTripleString())
929 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
932 } else if (XOpenMPTargetNoTriple) {
933 // Passing device args: -Xopenmp-target -opt=val.
934 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
940 // Parse the argument to -Xopenmp-target.
942 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
943 if (!XOpenMPTargetArg || Index > Prev + 1) {
944 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
945 << A->getAsString(Args);
948 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
949 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
950 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
953 XOpenMPTargetArg->setBaseArg(A);
954 A = XOpenMPTargetArg.release();
955 AllocatedArgs.push_back(A);