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 "ToolChains/CommonArgs.h"
12 #include "ToolChains/Arch/ARM.h"
13 #include "ToolChains/Clang.h"
14 #include "clang/Basic/ObjCRuntime.h"
15 #include "clang/Basic/VirtualFileSystem.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/Options.h"
21 #include "clang/Driver/SanitizerArgs.h"
22 #include "clang/Driver/XRayArgs.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/TargetParser.h"
33 #include "llvm/Support/TargetRegistry.h"
35 using namespace clang::driver;
36 using namespace clang::driver::tools;
37 using namespace clang;
39 using namespace llvm::opt;
41 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
42 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
43 options::OPT_fno_rtti, options::OPT_frtti);
46 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
47 const llvm::Triple &Triple,
48 const Arg *CachedRTTIArg) {
49 // Explicit rtti/no-rtti args
51 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
52 return ToolChain::RM_EnabledExplicitly;
54 return ToolChain::RM_DisabledExplicitly;
57 // -frtti is default, except for the PS4 CPU.
58 if (!Triple.isPS4CPU())
59 return ToolChain::RM_EnabledImplicitly;
61 // On the PS4, turning on c++ exceptions turns on rtti.
62 // We're assuming that, if we see -fexceptions, rtti gets turned on.
63 Arg *Exceptions = Args.getLastArgNoClaim(
64 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
65 options::OPT_fexceptions, options::OPT_fno_exceptions);
67 (Exceptions->getOption().matches(options::OPT_fexceptions) ||
68 Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
69 return ToolChain::RM_EnabledImplicitly;
71 return ToolChain::RM_DisabledImplicitly;
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 std::string CandidateLibPath = getArchSpecificLibPath();
80 if (getVFS().exists(CandidateLibPath))
81 getFilePaths().push_back(CandidateLibPath);
84 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
85 Triple.setEnvironment(Env);
86 if (EffectiveTriple != llvm::Triple())
87 EffectiveTriple.setEnvironment(Env);
90 ToolChain::~ToolChain() {
93 vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); }
95 bool ToolChain::useIntegratedAs() const {
96 return Args.hasFlag(options::OPT_fintegrated_as,
97 options::OPT_fno_integrated_as,
98 IsIntegratedAssemblerDefault());
101 bool ToolChain::useRelaxRelocations() const {
102 return ENABLE_X86_RELAX_RELOCATIONS;
105 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
106 if (!SanitizerArguments.get())
107 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
108 return *SanitizerArguments.get();
111 const XRayArgs& ToolChain::getXRayArgs() const {
112 if (!XRayArguments.get())
113 XRayArguments.reset(new XRayArgs(*this, Args));
114 return *XRayArguments.get();
118 struct DriverSuffix {
120 const char *ModeFlag;
123 const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
124 // A list of known driver suffixes. Suffixes are compared against the
125 // program name in order. If there is a match, the frontend type is updated as
126 // necessary by applying the ModeFlag.
127 static const DriverSuffix DriverSuffixes[] = {
129 {"clang++", "--driver-mode=g++"},
130 {"clang-c++", "--driver-mode=g++"},
131 {"clang-cc", nullptr},
132 {"clang-cpp", "--driver-mode=cpp"},
133 {"clang-g++", "--driver-mode=g++"},
134 {"clang-gcc", nullptr},
135 {"clang-cl", "--driver-mode=cl"},
137 {"cpp", "--driver-mode=cpp"},
138 {"cl", "--driver-mode=cl"},
139 {"++", "--driver-mode=g++"},
142 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
143 StringRef Suffix(DriverSuffixes[i].Suffix);
144 if (ProgName.endswith(Suffix)) {
145 Pos = ProgName.size() - Suffix.size();
146 return &DriverSuffixes[i];
152 /// Normalize the program name from argv[0] by stripping the file extension if
153 /// present and lower-casing the string on Windows.
154 std::string normalizeProgramName(llvm::StringRef Argv0) {
155 std::string ProgName = llvm::sys::path::stem(Argv0);
157 // Transform to lowercase for case insensitive file systems.
158 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
163 const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
164 // Try to infer frontend type and default target from the program name by
165 // comparing it against DriverSuffixes in order.
167 // If there is a match, the function tries to identify a target as prefix.
168 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
169 // prefix "x86_64-linux". If such a target prefix is found, it may be
170 // added via -target as implicit first argument.
171 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
174 // Try again after stripping any trailing version number:
175 // clang++3.5 -> clang++
176 ProgName = ProgName.rtrim("0123456789.");
177 DS = FindDriverSuffix(ProgName, Pos);
181 // Try again after stripping trailing -component.
182 // clang++-tot -> clang++
183 ProgName = ProgName.slice(0, ProgName.rfind('-'));
184 DS = FindDriverSuffix(ProgName, Pos);
188 } // anonymous namespace
191 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
192 std::string ProgName = normalizeProgramName(PN);
194 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
196 return ParsedClangName();
197 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
199 size_t LastComponent = ProgName.rfind('-', SuffixPos);
200 if (LastComponent == std::string::npos)
201 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
202 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
203 SuffixEnd - LastComponent - 1);
205 // Infer target from the prefix.
206 StringRef Prefix(ProgName);
207 Prefix = Prefix.slice(0, LastComponent);
208 std::string IgnoredError;
209 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
210 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
213 StringRef ToolChain::getDefaultUniversalArchName() const {
214 // In universal driver terms, the arch name accepted by -arch isn't exactly
215 // the same as the ones that appear in the triple. Roughly speaking, this is
216 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
217 // only interesting special case is powerpc.
218 switch (Triple.getArch()) {
219 case llvm::Triple::ppc:
221 case llvm::Triple::ppc64:
223 case llvm::Triple::ppc64le:
226 return Triple.getArchName();
230 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
231 return Input.getFilename();
234 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
238 Tool *ToolChain::getClang() const {
240 Clang.reset(new tools::Clang(*this));
244 Tool *ToolChain::buildAssembler() const {
245 return new tools::ClangAs(*this);
248 Tool *ToolChain::buildLinker() const {
249 llvm_unreachable("Linking is not supported by this toolchain");
252 Tool *ToolChain::getAssemble() const {
254 Assemble.reset(buildAssembler());
255 return Assemble.get();
258 Tool *ToolChain::getClangAs() const {
260 Assemble.reset(new tools::ClangAs(*this));
261 return Assemble.get();
264 Tool *ToolChain::getLink() const {
266 Link.reset(buildLinker());
270 Tool *ToolChain::getOffloadBundler() const {
272 OffloadBundler.reset(new tools::OffloadBundler(*this));
273 return OffloadBundler.get();
276 Tool *ToolChain::getTool(Action::ActionClass AC) const {
278 case Action::AssembleJobClass:
279 return getAssemble();
281 case Action::LinkJobClass:
284 case Action::InputClass:
285 case Action::BindArchClass:
286 case Action::OffloadClass:
287 case Action::LipoJobClass:
288 case Action::DsymutilJobClass:
289 case Action::VerifyDebugInfoJobClass:
290 llvm_unreachable("Invalid tool kind.");
292 case Action::CompileJobClass:
293 case Action::PrecompileJobClass:
294 case Action::PreprocessJobClass:
295 case Action::AnalyzeJobClass:
296 case Action::MigrateJobClass:
297 case Action::VerifyPCHJobClass:
298 case Action::BackendJobClass:
301 case Action::OffloadBundlingJobClass:
302 case Action::OffloadUnbundlingJobClass:
303 return getOffloadBundler();
306 llvm_unreachable("Invalid tool kind.");
309 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
310 const ArgList &Args) {
311 const llvm::Triple &Triple = TC.getTriple();
312 bool IsWindows = Triple.isOSWindows();
314 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
315 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
319 // For historic reasons, Android library is using i686 instead of i386.
320 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
323 return llvm::Triple::getArchTypeName(TC.getArch());
326 std::string ToolChain::getCompilerRTPath() const {
327 SmallString<128> Path(getDriver().ResourceDir);
328 if (Triple.isOSUnknown()) {
329 llvm::sys::path::append(Path, "lib");
331 StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS();
332 llvm::sys::path::append(Path, "lib", OSLibName);
337 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
339 const llvm::Triple &TT = getTriple();
340 const char *Env = TT.isAndroid() ? "-android" : "";
341 bool IsITANMSVCWindows =
342 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
344 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
345 const char *Prefix = IsITANMSVCWindows ? "" : "lib";
346 const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
347 : (IsITANMSVCWindows ? ".lib" : ".a");
349 SmallString<128> Path(getCompilerRTPath());
350 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
351 Arch + Env + Suffix);
355 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
358 return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
361 std::string ToolChain::getArchSpecificLibPath() const {
362 SmallString<128> Path(getDriver().ResourceDir);
363 StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS();
364 llvm::sys::path::append(Path, "lib", OSLibName,
365 llvm::Triple::getArchTypeName(getArch()));
369 bool ToolChain::needsProfileRT(const ArgList &Args) {
370 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
372 Args.hasArg(options::OPT_fprofile_generate) ||
373 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
374 Args.hasArg(options::OPT_fprofile_instr_generate) ||
375 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
376 Args.hasArg(options::OPT_fcreate_profile) ||
377 Args.hasArg(options::OPT_coverage))
383 Tool *ToolChain::SelectTool(const JobAction &JA) const {
384 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
385 Action::ActionClass AC = JA.getKind();
386 if (AC == Action::AssembleJobClass && useIntegratedAs())
391 std::string ToolChain::GetFilePath(const char *Name) const {
392 return D.GetFilePath(Name, *this);
395 std::string ToolChain::GetProgramPath(const char *Name) const {
396 return D.GetProgramPath(Name, *this);
399 std::string ToolChain::GetLinkerPath() const {
400 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
401 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
403 if (llvm::sys::path::is_absolute(UseLinker)) {
404 // If we're passed what looks like an absolute path, don't attempt to
405 // second-guess that.
406 if (llvm::sys::fs::exists(UseLinker))
408 } else if (UseLinker.empty() || UseLinker == "ld") {
409 // If we're passed -fuse-ld= with no argument, or with the argument ld,
410 // then use whatever the default system linker is.
411 return GetProgramPath(getDefaultLinker());
413 llvm::SmallString<8> LinkerName;
414 if (Triple.isOSDarwin())
415 LinkerName.append("ld64.");
417 LinkerName.append("ld.");
418 LinkerName.append(UseLinker);
420 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
421 if (llvm::sys::fs::exists(LinkerPath))
426 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
428 return GetProgramPath(getDefaultLinker());
431 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
432 return types::lookupTypeForExtension(Ext);
435 bool ToolChain::HasNativeLLVMSupport() const {
439 bool ToolChain::isCrossCompiling() const {
440 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
441 switch (HostTriple.getArch()) {
442 // The A32/T32/T16 instruction sets are not separate architectures in this
444 case llvm::Triple::arm:
445 case llvm::Triple::armeb:
446 case llvm::Triple::thumb:
447 case llvm::Triple::thumbeb:
448 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
449 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
451 return HostTriple.getArch() != getArch();
455 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
456 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
460 llvm::ExceptionHandling
461 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
462 if (Triple.isOSWindows() && Triple.getArch() != llvm::Triple::x86)
463 return llvm::ExceptionHandling::WinEH;
464 return llvm::ExceptionHandling::None;
467 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
468 if (Model == "single") {
469 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
470 return Triple.getArch() == llvm::Triple::arm ||
471 Triple.getArch() == llvm::Triple::armeb ||
472 Triple.getArch() == llvm::Triple::thumb ||
473 Triple.getArch() == llvm::Triple::thumbeb ||
474 Triple.getArch() == llvm::Triple::wasm32 ||
475 Triple.getArch() == llvm::Triple::wasm64;
476 } else if (Model == "posix")
482 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
483 types::ID InputType) const {
484 switch (getTriple().getArch()) {
486 return getTripleString();
488 case llvm::Triple::x86_64: {
489 llvm::Triple Triple = getTriple();
490 if (!Triple.isOSBinFormatMachO())
491 return getTripleString();
493 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
494 // x86_64h goes in the triple. Other -march options just use the
495 // vanilla triple we already have.
496 StringRef MArch = A->getValue();
497 if (MArch == "x86_64h")
498 Triple.setArchName(MArch);
500 return Triple.getTriple();
502 case llvm::Triple::aarch64: {
503 llvm::Triple Triple = getTriple();
504 if (!Triple.isOSBinFormatMachO())
505 return getTripleString();
507 // FIXME: older versions of ld64 expect the "arm64" component in the actual
508 // triple string and query it to determine whether an LTO file can be
509 // handled. Remove this when we don't care any more.
510 Triple.setArchName("arm64");
511 return Triple.getTriple();
513 case llvm::Triple::arm:
514 case llvm::Triple::armeb:
515 case llvm::Triple::thumb:
516 case llvm::Triple::thumbeb: {
517 // FIXME: Factor into subclasses.
518 llvm::Triple Triple = getTriple();
519 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
520 getTriple().getArch() == llvm::Triple::thumbeb;
522 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
523 // '-mbig-endian'/'-EB'.
524 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
525 options::OPT_mbig_endian)) {
526 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
529 // Thumb2 is the default for V7 on Darwin.
531 // FIXME: Thumb should just be another -target-feaure, not in the triple.
532 StringRef MCPU, MArch;
533 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
534 MCPU = A->getValue();
535 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
536 MArch = A->getValue();
538 Triple.isOSBinFormatMachO()
539 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
540 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
542 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
543 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
544 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
545 getTriple().isOSBinFormatMachO());
546 // FIXME: this is invalid for WindowsCE
547 if (getTriple().isOSWindows())
549 std::string ArchName;
555 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
556 // M-Class CPUs/architecture variants, which is not supported.
557 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
558 options::OPT_mno_thumb, ThumbDefault);
559 if (IsMProfile && ARMModeRequested) {
561 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
563 getDriver().Diag(diag::err_arch_unsupported_isa)
564 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
567 // Check to see if an explicit choice to use thumb has been made via
568 // -mthumb. For assembler files we must check for -mthumb in the options
569 // passed to the assember via -Wa or -Xassembler.
570 bool IsThumb = false;
571 if (InputType != types::TY_PP_Asm)
572 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
575 // Ideally we would check for these flags in
576 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
577 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
580 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
581 for (StringRef Value : A->getValues()) {
582 if (Value == "-mthumb")
587 // Assembly files should start in ARM mode, unless arch is M-profile, or
588 // -mthumb has been passed explicitly to the assembler. Windows is always
590 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
592 ArchName = "thumbeb";
596 Triple.setArchName(ArchName + Suffix.str());
598 return Triple.getTriple();
603 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
604 types::ID InputType) const {
605 return ComputeLLVMTriple(Args, InputType);
608 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
609 ArgStringList &CC1Args) const {
610 // Each toolchain should provide the appropriate include flags.
613 void ToolChain::addClangTargetOptions(
614 const ArgList &DriverArgs, ArgStringList &CC1Args,
615 Action::OffloadKind DeviceOffloadKind) const {}
617 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
619 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
620 llvm::opt::ArgStringList &CmdArgs) const {
621 if (!needsProfileRT(Args)) return;
623 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
626 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
627 const ArgList &Args) const {
628 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
629 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
631 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
632 if (LibName == "compiler-rt")
633 return ToolChain::RLT_CompilerRT;
634 else if (LibName == "libgcc")
635 return ToolChain::RLT_Libgcc;
636 else if (LibName == "platform")
637 return GetDefaultRuntimeLibType();
640 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
642 return GetDefaultRuntimeLibType();
645 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
646 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
647 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
649 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
650 if (LibName == "libc++")
651 return ToolChain::CST_Libcxx;
652 else if (LibName == "libstdc++")
653 return ToolChain::CST_Libstdcxx;
654 else if (LibName == "platform")
655 return GetDefaultCXXStdlibType();
658 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
660 return GetDefaultCXXStdlibType();
663 /// \brief Utility function to add a system include directory to CC1 arguments.
664 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
665 ArgStringList &CC1Args,
667 CC1Args.push_back("-internal-isystem");
668 CC1Args.push_back(DriverArgs.MakeArgString(Path));
671 /// \brief Utility function to add a system include directory with extern "C"
672 /// semantics to CC1 arguments.
674 /// Note that this should be used rarely, and only for directories that
675 /// historically and for legacy reasons are treated as having implicit extern
676 /// "C" semantics. These semantics are *ignored* by and large today, but its
677 /// important to preserve the preprocessor changes resulting from the
679 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
680 ArgStringList &CC1Args,
682 CC1Args.push_back("-internal-externc-isystem");
683 CC1Args.push_back(DriverArgs.MakeArgString(Path));
686 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
687 ArgStringList &CC1Args,
689 if (llvm::sys::fs::exists(Path))
690 addExternCSystemInclude(DriverArgs, CC1Args, Path);
693 /// \brief Utility function to add a list of system include directories to CC1.
694 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
695 ArgStringList &CC1Args,
696 ArrayRef<StringRef> Paths) {
697 for (StringRef Path : Paths) {
698 CC1Args.push_back("-internal-isystem");
699 CC1Args.push_back(DriverArgs.MakeArgString(Path));
703 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
704 ArgStringList &CC1Args) const {
705 // Header search paths should be handled by each of the subclasses.
706 // Historically, they have not been, and instead have been handled inside of
707 // the CC1-layer frontend. As the logic is hoisted out, this generic function
708 // will slowly stop being called.
710 // While it is being called, replicate a bit of a hack to propagate the
711 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
712 // header search paths with it. Once all systems are overriding this
713 // function, the CC1 flag and this line can be removed.
714 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
717 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
718 return getDriver().CCCIsCXX() &&
719 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
720 options::OPT_nostdlibxx);
723 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
724 ArgStringList &CmdArgs) const {
725 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
726 "should not have called this");
727 CXXStdlibType Type = GetCXXStdlibType(Args);
730 case ToolChain::CST_Libcxx:
731 CmdArgs.push_back("-lc++");
734 case ToolChain::CST_Libstdcxx:
735 CmdArgs.push_back("-lstdc++");
740 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
741 ArgStringList &CmdArgs) const {
742 for (const auto &LibPath : getFilePaths())
743 if(LibPath.length() > 0)
744 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
747 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
748 ArgStringList &CmdArgs) const {
749 CmdArgs.push_back("-lcc_kext");
752 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
753 ArgStringList &CmdArgs) const {
754 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
755 // (to keep the linker options consistent with gcc and clang itself).
756 if (!isOptimizationLevelFast(Args)) {
757 // Check if -ffast-math or -funsafe-math.
759 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
760 options::OPT_funsafe_math_optimizations,
761 options::OPT_fno_unsafe_math_optimizations);
763 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
764 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
767 // If crtfastmath.o exists add it to the arguments.
768 std::string Path = GetFilePath("crtfastmath.o");
769 if (Path == "crtfastmath.o") // Not found.
772 CmdArgs.push_back(Args.MakeArgString(Path));
776 SanitizerMask ToolChain::getSupportedSanitizers() const {
777 // Return sanitizers which don't require runtime support and are not
778 // platform dependent.
779 using namespace SanitizerKind;
780 SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
781 CFICastStrict | UnsignedIntegerOverflow | Nullability |
783 if (getTriple().getArch() == llvm::Triple::x86 ||
784 getTriple().getArch() == llvm::Triple::x86_64 ||
785 getTriple().getArch() == llvm::Triple::arm ||
786 getTriple().getArch() == llvm::Triple::aarch64 ||
787 getTriple().getArch() == llvm::Triple::wasm32 ||
788 getTriple().getArch() == llvm::Triple::wasm64)
793 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
794 ArgStringList &CC1Args) const {}
796 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
797 ArgStringList &CC1Args) const {}
799 static VersionTuple separateMSVCFullVersion(unsigned Version) {
801 return VersionTuple(Version);
804 return VersionTuple(Version / 100, Version % 100);
806 unsigned Build = 0, Factor = 1;
807 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
808 Build = Build + (Version % 10) * Factor;
809 return VersionTuple(Version / 100, Version % 100, Build);
813 ToolChain::computeMSVCVersion(const Driver *D,
814 const llvm::opt::ArgList &Args) const {
815 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
816 const Arg *MSCompatibilityVersion =
817 Args.getLastArg(options::OPT_fms_compatibility_version);
819 if (MSCVersion && MSCompatibilityVersion) {
821 D->Diag(diag::err_drv_argument_not_allowed_with)
822 << MSCVersion->getAsString(Args)
823 << MSCompatibilityVersion->getAsString(Args);
824 return VersionTuple();
827 if (MSCompatibilityVersion) {
829 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
831 D->Diag(diag::err_drv_invalid_value)
832 << MSCompatibilityVersion->getAsString(Args)
833 << MSCompatibilityVersion->getValue();
840 unsigned Version = 0;
841 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
843 D->Diag(diag::err_drv_invalid_value)
844 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
846 return separateMSVCFullVersion(Version);
850 return VersionTuple();
853 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
854 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
855 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
856 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
857 const OptTable &Opts = getDriver().getOpts();
858 bool Modified = false;
860 // Handle -Xopenmp-target flags
861 for (Arg *A : Args) {
862 // Exclude flags which may only apply to the host toolchain.
863 // Do not exclude flags when the host triple (AuxTriple)
864 // matches the current toolchain triple. If it is not present
865 // at all, target and host share a toolchain.
866 if (A->getOption().matches(options::OPT_m_Group)) {
867 if (SameTripleAsHost)
876 bool XOpenMPTargetNoTriple =
877 A->getOption().matches(options::OPT_Xopenmp_target);
879 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
880 // Passing device args: -Xopenmp-target=<triple> -opt=val.
881 if (A->getValue(0) == getTripleString())
882 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
885 } else if (XOpenMPTargetNoTriple) {
886 // Passing device args: -Xopenmp-target -opt=val.
887 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
893 // Parse the argument to -Xopenmp-target.
895 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
896 if (!XOpenMPTargetArg || Index > Prev + 1) {
897 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
898 << A->getAsString(Args);
901 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
902 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
903 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
906 XOpenMPTargetArg->setBaseArg(A);
907 A = XOpenMPTargetArg.release();
908 AllocatedArgs.push_back(A);