1 //===--- ToolChains.cpp - ToolChain Implementations -------------*- C++ -*-===//
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 "ToolChains.h"
11 #include "clang/Basic/ObjCRuntime.h"
12 #include "clang/Basic/Version.h"
13 #include "clang/Basic/VirtualFileSystem.h"
14 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/OptTable.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/ProfileData/InstrProf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/TargetParser.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cstdlib> // ::getenv
37 #include <system_error>
39 using namespace clang::driver;
40 using namespace clang::driver::toolchains;
41 using namespace clang;
42 using namespace llvm::opt;
44 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
45 : ToolChain(D, Triple, Args) {
46 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
47 getProgramPaths().push_back(getDriver().getInstalledDir());
48 if (getDriver().getInstalledDir() != getDriver().Dir)
49 getProgramPaths().push_back(getDriver().Dir);
52 /// Darwin - Darwin tool chain for i386 and x86_64.
53 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
54 : MachO(D, Triple, Args), TargetInitialized(false) {}
56 types::ID MachO::LookupTypeForExtension(const char *Ext) const {
57 types::ID Ty = types::lookupTypeForExtension(Ext);
59 // Darwin always preprocesses assembly files (unless -x is used explicitly).
60 if (Ty == types::TY_PP_Asm)
66 bool MachO::HasNativeLLVMSupport() const { return true; }
68 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
69 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
70 if (isTargetWatchOSBased())
71 return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
72 if (isTargetIOSBased())
73 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
75 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
76 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
79 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
80 bool Darwin::hasBlocksRuntime() const {
81 if (isTargetWatchOSBased())
83 else if (isTargetIOSBased())
84 return !isIPhoneOSVersionLT(3, 2);
86 assert(isTargetMacOS() && "unexpected darwin target");
87 return !isMacosxVersionLT(10, 6);
91 // This is just a MachO name translation routine and there's no
92 // way to join this into ARMTargetParser without breaking all
93 // other assumptions. Maybe MachO should consider standardising
94 // their nomenclature.
95 static const char *ArmMachOArchName(StringRef Arch) {
96 return llvm::StringSwitch<const char *>(Arch)
97 .Case("armv6k", "armv6")
98 .Case("armv6m", "armv6m")
99 .Case("armv5tej", "armv5")
100 .Case("xscale", "xscale")
101 .Case("armv4t", "armv4t")
102 .Case("armv7", "armv7")
103 .Cases("armv7a", "armv7-a", "armv7")
104 .Cases("armv7r", "armv7-r", "armv7")
105 .Cases("armv7em", "armv7e-m", "armv7em")
106 .Cases("armv7k", "armv7-k", "armv7k")
107 .Cases("armv7m", "armv7-m", "armv7m")
108 .Cases("armv7s", "armv7-s", "armv7s")
112 static const char *ArmMachOArchNameCPU(StringRef CPU) {
113 unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
114 if (ArchKind == llvm::ARM::AK_INVALID)
116 StringRef Arch = llvm::ARM::getArchName(ArchKind);
118 // FIXME: Make sure this MachO triple mangling is really necessary.
119 // ARMv5* normalises to ARMv5.
120 if (Arch.startswith("armv5"))
121 Arch = Arch.substr(0, 5);
122 // ARMv6*, except ARMv6M, normalises to ARMv6.
123 else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
124 Arch = Arch.substr(0, 5);
125 // ARMv7A normalises to ARMv7.
126 else if (Arch.endswith("v7a"))
127 Arch = Arch.substr(0, 5);
131 static bool isSoftFloatABI(const ArgList &Args) {
132 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
133 options::OPT_mfloat_abi_EQ);
137 return A->getOption().matches(options::OPT_msoft_float) ||
138 (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
139 A->getValue() == StringRef("soft"));
142 StringRef MachO::getMachOArchName(const ArgList &Args) const {
143 switch (getTriple().getArch()) {
145 return getDefaultUniversalArchName();
147 case llvm::Triple::aarch64:
150 case llvm::Triple::thumb:
151 case llvm::Triple::arm:
152 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
153 if (const char *Arch = ArmMachOArchName(A->getValue()))
156 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
157 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
168 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args,
169 types::ID InputType) const {
170 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
172 return Triple.getTriple();
175 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
176 types::ID InputType) const {
177 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
179 // If the target isn't initialized (e.g., an unknown Darwin platform, return
180 // the default triple).
181 if (!isTargetInitialized())
182 return Triple.getTriple();
185 if (isTargetWatchOSBased())
187 else if (isTargetTvOSBased())
189 else if (isTargetIOSBased())
193 Str += getTargetVersion().getAsString();
194 Triple.setOSName(Str);
196 return Triple.getTriple();
199 void Generic_ELF::anchor() {}
201 Tool *MachO::getTool(Action::ActionClass AC) const {
203 case Action::LipoJobClass:
205 Lipo.reset(new tools::darwin::Lipo(*this));
207 case Action::DsymutilJobClass:
209 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
210 return Dsymutil.get();
211 case Action::VerifyDebugInfoJobClass:
213 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
214 return VerifyDebug.get();
216 return ToolChain::getTool(AC);
220 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
222 Tool *MachO::buildAssembler() const {
223 return new tools::darwin::Assembler(*this);
226 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
228 : Darwin(D, Triple, Args) {}
230 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
231 // For modern targets, promote certain warnings to errors.
232 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
233 // Always enable -Wdeprecated-objc-isa-usage and promote it
235 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
236 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
238 // For iOS and watchOS, also error about implicit function declarations,
239 // as that can impact calling conventions.
240 if (!isTargetMacOS())
241 CC1Args.push_back("-Werror=implicit-function-declaration");
245 /// \brief Determine whether Objective-C automated reference counting is
247 static bool isObjCAutoRefCount(const ArgList &Args) {
248 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
251 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
252 ArgStringList &CmdArgs) const {
253 // Avoid linking compatibility stubs on i386 mac.
254 if (isTargetMacOS() && getArch() == llvm::Triple::x86)
257 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
259 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
260 runtime.hasSubscripting())
263 CmdArgs.push_back("-force_load");
264 SmallString<128> P(getDriver().ClangExecutable);
265 llvm::sys::path::remove_filename(P); // 'clang'
266 llvm::sys::path::remove_filename(P); // 'bin'
267 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
268 // Mash in the platform.
269 if (isTargetWatchOSSimulator())
270 P += "watchsimulator";
271 else if (isTargetWatchOS())
273 else if (isTargetTvOSSimulator())
274 P += "appletvsimulator";
275 else if (isTargetTvOS())
277 else if (isTargetIOSSimulator())
278 P += "iphonesimulator";
279 else if (isTargetIPhoneOS())
285 CmdArgs.push_back(Args.MakeArgString(P));
288 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
289 StringRef DarwinLibName, bool AlwaysLink,
290 bool IsEmbedded, bool AddRPath) const {
291 SmallString<128> Dir(getDriver().ResourceDir);
292 llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin");
294 SmallString<128> P(Dir);
295 llvm::sys::path::append(P, DarwinLibName);
297 // For now, allow missing resource libraries to support developers who may
298 // not have compiler-rt checked out or integrated into their build (unless
299 // we explicitly force linking with this library).
300 if (AlwaysLink || getVFS().exists(P))
301 CmdArgs.push_back(Args.MakeArgString(P));
303 // Adding the rpaths might negatively interact when other rpaths are involved,
304 // so we should make sure we add the rpaths last, after all user-specified
305 // rpaths. This is currently true from this place, but we need to be
306 // careful if this function is ever called before user's rpaths are emitted.
308 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
310 // Add @executable_path to rpath to support having the dylib copied with
312 CmdArgs.push_back("-rpath");
313 CmdArgs.push_back("@executable_path");
315 // Add the path to the resource dir to rpath to support using the dylib
316 // from the default location without copying.
317 CmdArgs.push_back("-rpath");
318 CmdArgs.push_back(Args.MakeArgString(Dir));
322 void Darwin::addProfileRTLibs(const ArgList &Args,
323 ArgStringList &CmdArgs) const {
324 if (!needsProfileRT(Args)) return;
326 // TODO: Clean this up once autoconf is gone
327 SmallString<128> P(getDriver().ResourceDir);
328 llvm::sys::path::append(P, "lib", "darwin");
329 const char *Library = "libclang_rt.profile_osx.a";
331 // Select the appropriate runtime library for the target.
332 if (isTargetWatchOS()) {
333 Library = "libclang_rt.profile_watchos.a";
334 } else if (isTargetWatchOSSimulator()) {
335 llvm::sys::path::append(P, "libclang_rt.profile_watchossim.a");
336 Library = getVFS().exists(P) ? "libclang_rt.profile_watchossim.a"
337 : "libclang_rt.profile_watchos.a";
338 } else if (isTargetTvOS()) {
339 Library = "libclang_rt.profile_tvos.a";
340 } else if (isTargetTvOSSimulator()) {
341 llvm::sys::path::append(P, "libclang_rt.profile_tvossim.a");
342 Library = getVFS().exists(P) ? "libclang_rt.profile_tvossim.a"
343 : "libclang_rt.profile_tvos.a";
344 } else if (isTargetIPhoneOS()) {
345 Library = "libclang_rt.profile_ios.a";
346 } else if (isTargetIOSSimulator()) {
347 llvm::sys::path::append(P, "libclang_rt.profile_iossim.a");
348 Library = getVFS().exists(P) ? "libclang_rt.profile_iossim.a"
349 : "libclang_rt.profile_ios.a";
351 assert(isTargetMacOS() && "unexpected non MacOS platform");
353 AddLinkRuntimeLib(Args, CmdArgs, Library,
354 /*AlwaysLink*/ true);
358 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
359 ArgStringList &CmdArgs,
360 StringRef Sanitizer) const {
361 if (!Args.hasArg(options::OPT_dynamiclib) &&
362 !Args.hasArg(options::OPT_bundle)) {
363 // Sanitizer runtime libraries requires C++.
364 AddCXXStdlibLibArgs(Args, CmdArgs);
366 // ASan is not supported on watchOS.
367 assert(isTargetMacOS() || isTargetIOSSimulator());
368 StringRef OS = isTargetMacOS() ? "osx" : "iossim";
371 (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(),
372 /*AlwaysLink*/ true, /*IsEmbedded*/ false,
375 if (GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) {
376 // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export
377 // all RTTI-related symbols that UBSan uses.
378 CmdArgs.push_back("-lc++abi");
382 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
383 ArgStringList &CmdArgs) const {
384 // Darwin only supports the compiler-rt based runtime libraries.
385 switch (GetRuntimeLibType(Args)) {
386 case ToolChain::RLT_CompilerRT:
389 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
390 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin";
394 // Darwin doesn't support real static executables, don't link any runtime
395 // libraries with -static.
396 if (Args.hasArg(options::OPT_static) ||
397 Args.hasArg(options::OPT_fapple_kext) ||
398 Args.hasArg(options::OPT_mkernel))
401 // Reject -static-libgcc for now, we can deal with this when and if someone
402 // cares. This is useful in situations where someone wants to statically link
403 // something like libstdc++, and needs its runtime support routines.
404 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
405 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
409 const SanitizerArgs &Sanitize = getSanitizerArgs();
410 if (Sanitize.needsAsanRt())
411 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
412 if (Sanitize.needsUbsanRt())
413 AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
414 if (Sanitize.needsTsanRt())
415 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
417 // Otherwise link libSystem, then the dynamic runtime library, and finally any
418 // target specific static runtime library.
419 CmdArgs.push_back("-lSystem");
421 // Select the dynamic runtime library and the target specific static library.
422 if (isTargetWatchOSBased()) {
423 // We currently always need a static runtime library for watchOS.
424 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
425 } else if (isTargetTvOSBased()) {
426 // We currently always need a static runtime library for tvOS.
427 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
428 } else if (isTargetIOSBased()) {
429 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
430 // it never went into the SDK.
431 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
432 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
433 getTriple().getArch() != llvm::Triple::aarch64)
434 CmdArgs.push_back("-lgcc_s.1");
436 // We currently always need a static runtime library for iOS.
437 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
439 assert(isTargetMacOS() && "unexpected non MacOS platform");
440 // The dynamic runtime library was merged with libSystem for 10.6 and
441 // beyond; only 10.4 and 10.5 need an additional runtime library.
442 if (isMacosxVersionLT(10, 5))
443 CmdArgs.push_back("-lgcc_s.10.4");
444 else if (isMacosxVersionLT(10, 6))
445 CmdArgs.push_back("-lgcc_s.10.5");
447 // For OS X, we thought we would only need a static runtime library when
448 // targeting 10.4, to provide versions of the static functions which were
449 // omitted from 10.4.dylib.
451 // Unfortunately, that turned out to not be true, because Darwin system
452 // headers can still use eprintf on i386, and it is not exported from
453 // libSystem. Therefore, we still must provide a runtime library just for
454 // the tiny tiny handful of projects that *might* use that symbol.
455 if (isMacosxVersionLT(10, 5)) {
456 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
458 if (getTriple().getArch() == llvm::Triple::x86)
459 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a");
460 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
465 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
466 const OptTable &Opts = getDriver().getOpts();
468 // Support allowing the SDKROOT environment variable used by xcrun and other
469 // Xcode tools to define the default sysroot, by making it the default for
471 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
472 // Warn if the path does not exist.
473 if (!getVFS().exists(A->getValue()))
474 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
476 if (char *env = ::getenv("SDKROOT")) {
477 // We only use this value as the default if it is an absolute path,
478 // exists, and it is not the root path.
479 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
480 StringRef(env) != "/") {
481 Args.append(Args.MakeSeparateArg(
482 nullptr, Opts.getOption(options::OPT_isysroot), env));
487 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
488 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ);
489 Arg *TvOSVersion = Args.getLastArg(options::OPT_mtvos_version_min_EQ);
490 Arg *WatchOSVersion = Args.getLastArg(options::OPT_mwatchos_version_min_EQ);
492 if (OSXVersion && (iOSVersion || TvOSVersion || WatchOSVersion)) {
493 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
494 << OSXVersion->getAsString(Args)
495 << (iOSVersion ? iOSVersion :
496 TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
497 iOSVersion = TvOSVersion = WatchOSVersion = nullptr;
498 } else if (iOSVersion && (TvOSVersion || WatchOSVersion)) {
499 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
500 << iOSVersion->getAsString(Args)
501 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
502 TvOSVersion = WatchOSVersion = nullptr;
503 } else if (TvOSVersion && WatchOSVersion) {
504 getDriver().Diag(diag::err_drv_argument_not_allowed_with)
505 << TvOSVersion->getAsString(Args)
506 << WatchOSVersion->getAsString(Args);
507 WatchOSVersion = nullptr;
508 } else if (!OSXVersion && !iOSVersion && !TvOSVersion && !WatchOSVersion) {
509 // If no deployment target was specified on the command line, check for
510 // environment defines.
511 std::string OSXTarget;
512 std::string iOSTarget;
513 std::string TvOSTarget;
514 std::string WatchOSTarget;
516 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
518 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
520 if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET"))
522 if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET"))
525 // If there is no command-line argument to specify the Target version and
526 // no environment variable defined, see if we can set the default based
528 if (OSXTarget.empty() && iOSTarget.empty() && WatchOSTarget.empty() &&
529 Args.hasArg(options::OPT_isysroot)) {
530 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
531 StringRef isysroot = A->getValue();
532 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
533 size_t BeginSDK = isysroot.rfind("SDKs/");
534 size_t EndSDK = isysroot.rfind(".sdk");
535 if (BeginSDK != StringRef::npos && EndSDK != StringRef::npos) {
536 StringRef SDK = isysroot.slice(BeginSDK + 5, EndSDK);
537 // Slice the version number out.
538 // Version number is between the first and the last number.
539 size_t StartVer = SDK.find_first_of("0123456789");
540 size_t EndVer = SDK.find_last_of("0123456789");
541 if (StartVer != StringRef::npos && EndVer > StartVer) {
542 StringRef Version = SDK.slice(StartVer, EndVer + 1);
543 if (SDK.startswith("iPhoneOS") ||
544 SDK.startswith("iPhoneSimulator"))
546 else if (SDK.startswith("MacOSX"))
548 else if (SDK.startswith("WatchOS") ||
549 SDK.startswith("WatchSimulator"))
550 WatchOSTarget = Version;
551 else if (SDK.startswith("AppleTVOS") ||
552 SDK.startswith("AppleTVSimulator"))
553 TvOSTarget = Version;
559 // If no OSX or iOS target has been specified, try to guess platform
560 // from arch name and compute the version from the triple.
561 if (OSXTarget.empty() && iOSTarget.empty() && TvOSTarget.empty() &&
562 WatchOSTarget.empty()) {
563 StringRef MachOArchName = getMachOArchName(Args);
564 unsigned Major, Minor, Micro;
565 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
566 MachOArchName == "arm64") {
567 getTriple().getiOSVersion(Major, Minor, Micro);
568 llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
570 } else if (MachOArchName == "armv7k") {
571 getTriple().getWatchOSVersion(Major, Minor, Micro);
572 llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.'
574 } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
575 MachOArchName != "armv7em") {
576 if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
577 getDriver().Diag(diag::err_drv_invalid_darwin_version)
578 << getTriple().getOSName();
580 llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
585 // Do not allow conflicts with the watchOS target.
586 if (!WatchOSTarget.empty() && (!iOSTarget.empty() || !TvOSTarget.empty())) {
587 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
588 << "WATCHOS_DEPLOYMENT_TARGET"
589 << (!iOSTarget.empty() ? "IPHONEOS_DEPLOYMENT_TARGET" :
590 "TVOS_DEPLOYMENT_TARGET");
593 // Do not allow conflicts with the tvOS target.
594 if (!TvOSTarget.empty() && !iOSTarget.empty()) {
595 getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
596 << "TVOS_DEPLOYMENT_TARGET"
597 << "IPHONEOS_DEPLOYMENT_TARGET";
600 // Allow conflicts among OSX and iOS for historical reasons, but choose the
602 if (!OSXTarget.empty() && (!iOSTarget.empty() ||
603 !WatchOSTarget.empty() ||
604 !TvOSTarget.empty())) {
605 if (getTriple().getArch() == llvm::Triple::arm ||
606 getTriple().getArch() == llvm::Triple::aarch64 ||
607 getTriple().getArch() == llvm::Triple::thumb)
610 iOSTarget = WatchOSTarget = TvOSTarget = "";
613 if (!OSXTarget.empty()) {
614 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
615 OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
616 Args.append(OSXVersion);
617 } else if (!iOSTarget.empty()) {
618 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
619 iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
620 Args.append(iOSVersion);
621 } else if (!TvOSTarget.empty()) {
622 const Option O = Opts.getOption(options::OPT_mtvos_version_min_EQ);
623 TvOSVersion = Args.MakeJoinedArg(nullptr, O, TvOSTarget);
624 Args.append(TvOSVersion);
625 } else if (!WatchOSTarget.empty()) {
626 const Option O = Opts.getOption(options::OPT_mwatchos_version_min_EQ);
627 WatchOSVersion = Args.MakeJoinedArg(nullptr, O, WatchOSTarget);
628 Args.append(WatchOSVersion);
632 DarwinPlatformKind Platform;
637 else if (TvOSVersion)
639 else if (WatchOSVersion)
642 llvm_unreachable("Unable to infer Darwin variant");
644 // Set the tool chain target information.
645 unsigned Major, Minor, Micro;
647 if (Platform == MacOS) {
648 assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) &&
649 "Unknown target platform!");
650 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
652 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
653 getDriver().Diag(diag::err_drv_invalid_version_number)
654 << OSXVersion->getAsString(Args);
655 } else if (Platform == IPhoneOS) {
656 assert(iOSVersion && "Unknown target platform!");
657 if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
659 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
660 getDriver().Diag(diag::err_drv_invalid_version_number)
661 << iOSVersion->getAsString(Args);
662 } else if (Platform == TvOS) {
663 if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor,
664 Micro, HadExtra) || HadExtra ||
665 Major >= 10 || Minor >= 100 || Micro >= 100)
666 getDriver().Diag(diag::err_drv_invalid_version_number)
667 << TvOSVersion->getAsString(Args);
668 } else if (Platform == WatchOS) {
669 if (!Driver::GetReleaseVersion(WatchOSVersion->getValue(), Major, Minor,
670 Micro, HadExtra) || HadExtra ||
671 Major >= 10 || Minor >= 100 || Micro >= 100)
672 getDriver().Diag(diag::err_drv_invalid_version_number)
673 << WatchOSVersion->getAsString(Args);
675 llvm_unreachable("unknown kind of Darwin platform");
677 // Recognize iOS targets with an x86 architecture as the iOS simulator.
678 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
679 getTriple().getArch() == llvm::Triple::x86_64))
680 Platform = IPhoneOSSimulator;
681 if (TvOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
682 getTriple().getArch() == llvm::Triple::x86_64))
683 Platform = TvOSSimulator;
684 if (WatchOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
685 getTriple().getArch() == llvm::Triple::x86_64))
686 Platform = WatchOSSimulator;
688 setTarget(Platform, Major, Minor, Micro);
691 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
692 ArgStringList &CmdArgs) const {
693 CXXStdlibType Type = GetCXXStdlibType(Args);
696 case ToolChain::CST_Libcxx:
697 CmdArgs.push_back("-lc++");
700 case ToolChain::CST_Libstdcxx:
701 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
702 // it was previously found in the gcc lib dir. However, for all the Darwin
703 // platforms we care about it was -lstdc++.6, so we search for that
704 // explicitly if we can't see an obvious -lstdc++ candidate.
706 // Check in the sysroot first.
707 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
708 SmallString<128> P(A->getValue());
709 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
711 if (!getVFS().exists(P)) {
712 llvm::sys::path::remove_filename(P);
713 llvm::sys::path::append(P, "libstdc++.6.dylib");
714 if (getVFS().exists(P)) {
715 CmdArgs.push_back(Args.MakeArgString(P));
721 // Otherwise, look in the root.
722 // FIXME: This should be removed someday when we don't have to care about
723 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
724 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
725 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
726 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
730 // Otherwise, let the linker search.
731 CmdArgs.push_back("-lstdc++");
736 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
737 ArgStringList &CmdArgs) const {
739 // For Darwin platforms, use the compiler-rt-based support library
740 // instead of the gcc-provided one (which is also incidentally
741 // only present in the gcc lib dir, which makes it hard to find).
743 SmallString<128> P(getDriver().ResourceDir);
744 llvm::sys::path::append(P, "lib", "darwin");
746 // Use the newer cc_kext for iOS ARM after 6.0.
747 if (isTargetWatchOS()) {
748 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
749 } else if (isTargetTvOS()) {
750 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
751 } else if (isTargetIPhoneOS()) {
752 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
754 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
757 // For now, allow missing resource libraries to support developers who may
758 // not have compiler-rt checked out or integrated into their build.
759 if (getVFS().exists(P))
760 CmdArgs.push_back(Args.MakeArgString(P));
763 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
764 const char *BoundArch) const {
765 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
766 const OptTable &Opts = getDriver().getOpts();
768 // FIXME: We really want to get out of the tool chain level argument
769 // translation business, as it makes the driver functionality much
770 // more opaque. For now, we follow gcc closely solely for the
771 // purpose of easily achieving feature parity & testability. Once we
772 // have something that works, we should reevaluate each translation
773 // and try to push it down into tool specific logic.
775 for (Arg *A : Args) {
776 if (A->getOption().matches(options::OPT_Xarch__)) {
777 // Skip this argument unless the architecture matches either the toolchain
778 // triple arch, or the arch being bound.
779 llvm::Triple::ArchType XarchArch =
780 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
781 if (!(XarchArch == getArch() ||
784 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
787 Arg *OriginalArg = A;
788 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
789 unsigned Prev = Index;
790 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
792 // If the argument parsing failed or more than one argument was
793 // consumed, the -Xarch_ argument's parameter tried to consume
794 // extra arguments. Emit an error and ignore.
796 // We also want to disallow any options which would alter the
797 // driver behavior; that isn't going to work in our model. We
798 // use isDriverOption() as an approximation, although things
799 // like -O4 are going to slip through.
800 if (!XarchArg || Index > Prev + 1) {
801 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
802 << A->getAsString(Args);
804 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
805 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
806 << A->getAsString(Args);
810 XarchArg->setBaseArg(A);
812 A = XarchArg.release();
813 DAL->AddSynthesizedArg(A);
815 // Linker input arguments require custom handling. The problem is that we
816 // have already constructed the phase actions, so we can not treat them as
817 // "input arguments".
818 if (A->getOption().hasFlag(options::LinkerInput)) {
819 // Convert the argument into individual Zlinker_input_args.
820 for (const char *Value : A->getValues()) {
822 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
828 // Sob. These is strictly gcc compatible for the time being. Apple
829 // gcc translates options twice, which means that self-expanding
830 // options add duplicates.
831 switch ((options::ID)A->getOption().getID()) {
836 case options::OPT_mkernel:
837 case options::OPT_fapple_kext:
839 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
842 case options::OPT_dependency_file:
843 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
846 case options::OPT_gfull:
847 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
849 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
852 case options::OPT_gused:
853 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
855 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
858 case options::OPT_shared:
859 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
862 case options::OPT_fconstant_cfstrings:
863 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
866 case options::OPT_fno_constant_cfstrings:
867 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
870 case options::OPT_Wnonportable_cfstrings:
872 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
875 case options::OPT_Wno_nonportable_cfstrings:
877 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
880 case options::OPT_fpascal_strings:
881 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
884 case options::OPT_fno_pascal_strings:
885 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
890 if (getTriple().getArch() == llvm::Triple::x86 ||
891 getTriple().getArch() == llvm::Triple::x86_64)
892 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
893 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
896 // Add the arch options based on the particular spelling of -arch, to match
897 // how the driver driver works.
899 StringRef Name = BoundArch;
900 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
901 const Option MArch = Opts.getOption(options::OPT_march_EQ);
903 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
904 // which defines the list of which architectures we accept.
907 else if (Name == "ppc601")
908 DAL->AddJoinedArg(nullptr, MCpu, "601");
909 else if (Name == "ppc603")
910 DAL->AddJoinedArg(nullptr, MCpu, "603");
911 else if (Name == "ppc604")
912 DAL->AddJoinedArg(nullptr, MCpu, "604");
913 else if (Name == "ppc604e")
914 DAL->AddJoinedArg(nullptr, MCpu, "604e");
915 else if (Name == "ppc750")
916 DAL->AddJoinedArg(nullptr, MCpu, "750");
917 else if (Name == "ppc7400")
918 DAL->AddJoinedArg(nullptr, MCpu, "7400");
919 else if (Name == "ppc7450")
920 DAL->AddJoinedArg(nullptr, MCpu, "7450");
921 else if (Name == "ppc970")
922 DAL->AddJoinedArg(nullptr, MCpu, "970");
924 else if (Name == "ppc64" || Name == "ppc64le")
925 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
927 else if (Name == "i386")
929 else if (Name == "i486")
930 DAL->AddJoinedArg(nullptr, MArch, "i486");
931 else if (Name == "i586")
932 DAL->AddJoinedArg(nullptr, MArch, "i586");
933 else if (Name == "i686")
934 DAL->AddJoinedArg(nullptr, MArch, "i686");
935 else if (Name == "pentium")
936 DAL->AddJoinedArg(nullptr, MArch, "pentium");
937 else if (Name == "pentium2")
938 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
939 else if (Name == "pentpro")
940 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
941 else if (Name == "pentIIm3")
942 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
944 else if (Name == "x86_64")
945 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
946 else if (Name == "x86_64h") {
947 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
948 DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
951 else if (Name == "arm")
952 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
953 else if (Name == "armv4t")
954 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
955 else if (Name == "armv5")
956 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
957 else if (Name == "xscale")
958 DAL->AddJoinedArg(nullptr, MArch, "xscale");
959 else if (Name == "armv6")
960 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
961 else if (Name == "armv6m")
962 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
963 else if (Name == "armv7")
964 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
965 else if (Name == "armv7em")
966 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
967 else if (Name == "armv7k")
968 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
969 else if (Name == "armv7m")
970 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
971 else if (Name == "armv7s")
972 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
978 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
979 ArgStringList &CmdArgs) const {
980 // Embedded targets are simple at the moment, not supporting sanitizers and
981 // with different libraries for each member of the product { static, PIC } x
982 // { hard-float, soft-float }
983 llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
985 (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
988 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
990 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
993 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args,
994 const char *BoundArch) const {
995 // First get the generic Apple args, before moving onto Darwin-specific ones.
996 DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch);
997 const OptTable &Opts = getDriver().getOpts();
999 // If no architecture is bound, none of the translations here are relevant.
1003 // Add an explicit version min argument for the deployment target. We do this
1004 // after argument translation because -Xarch_ arguments may add a version min
1006 AddDeploymentTarget(*DAL);
1008 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
1009 // FIXME: It would be far better to avoid inserting those -static arguments,
1010 // but we can't check the deployment target in the translation code until
1012 if (isTargetWatchOSBased() ||
1013 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
1014 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
1017 if (A->getOption().getID() != options::OPT_mkernel &&
1018 A->getOption().getID() != options::OPT_fapple_kext)
1020 assert(it != ie && "unexpected argument translation");
1022 assert(A->getOption().getID() == options::OPT_static &&
1023 "missing expected -static argument");
1024 it = DAL->getArgs().erase(it);
1028 // Default to use libc++ on OS X 10.9+ and iOS 7+.
1029 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
1030 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
1031 isTargetWatchOSBased()) &&
1032 !Args.getLastArg(options::OPT_stdlib_EQ))
1033 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
1036 // Validate the C++ standard library choice.
1037 CXXStdlibType Type = GetCXXStdlibType(*DAL);
1038 if (Type == ToolChain::CST_Libcxx) {
1039 // Check whether the target provides libc++.
1042 // Complain about targeting iOS < 5.0 in any way.
1043 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
1046 if (where != StringRef()) {
1047 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
1054 bool MachO::IsUnwindTablesDefault() const {
1055 return getArch() == llvm::Triple::x86_64;
1058 bool MachO::UseDwarfDebugFlags() const {
1059 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
1060 return S[0] != '\0';
1064 bool Darwin::UseSjLjExceptions(const ArgList &Args) const {
1065 // Darwin uses SjLj exceptions on ARM.
1066 if (getTriple().getArch() != llvm::Triple::arm &&
1067 getTriple().getArch() != llvm::Triple::thumb)
1070 // Only watchOS uses the new DWARF/Compact unwinding method.
1071 return !isTargetWatchOS();
1074 bool MachO::isPICDefault() const { return true; }
1076 bool MachO::isPIEDefault() const { return false; }
1078 bool MachO::isPICDefaultForced() const {
1079 return (getArch() == llvm::Triple::x86_64 ||
1080 getArch() == llvm::Triple::aarch64);
1083 bool MachO::SupportsProfiling() const {
1084 // Profiling instrumentation is only supported on x86.
1085 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
1088 void Darwin::addMinVersionArgs(const ArgList &Args,
1089 ArgStringList &CmdArgs) const {
1090 VersionTuple TargetVersion = getTargetVersion();
1092 if (isTargetWatchOS())
1093 CmdArgs.push_back("-watchos_version_min");
1094 else if (isTargetWatchOSSimulator())
1095 CmdArgs.push_back("-watchos_simulator_version_min");
1096 else if (isTargetTvOS())
1097 CmdArgs.push_back("-tvos_version_min");
1098 else if (isTargetTvOSSimulator())
1099 CmdArgs.push_back("-tvos_simulator_version_min");
1100 else if (isTargetIOSSimulator())
1101 CmdArgs.push_back("-ios_simulator_version_min");
1102 else if (isTargetIOSBased())
1103 CmdArgs.push_back("-iphoneos_version_min");
1105 assert(isTargetMacOS() && "unexpected target");
1106 CmdArgs.push_back("-macosx_version_min");
1109 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
1112 void Darwin::addStartObjectFileArgs(const ArgList &Args,
1113 ArgStringList &CmdArgs) const {
1114 // Derived from startfile spec.
1115 if (Args.hasArg(options::OPT_dynamiclib)) {
1116 // Derived from darwin_dylib1 spec.
1117 if (isTargetWatchOSBased()) {
1118 ; // watchOS does not need dylib1.o.
1119 } else if (isTargetIOSSimulator()) {
1120 ; // iOS simulator does not need dylib1.o.
1121 } else if (isTargetIPhoneOS()) {
1122 if (isIPhoneOSVersionLT(3, 1))
1123 CmdArgs.push_back("-ldylib1.o");
1125 if (isMacosxVersionLT(10, 5))
1126 CmdArgs.push_back("-ldylib1.o");
1127 else if (isMacosxVersionLT(10, 6))
1128 CmdArgs.push_back("-ldylib1.10.5.o");
1131 if (Args.hasArg(options::OPT_bundle)) {
1132 if (!Args.hasArg(options::OPT_static)) {
1133 // Derived from darwin_bundle1 spec.
1134 if (isTargetWatchOSBased()) {
1135 ; // watchOS does not need bundle1.o.
1136 } else if (isTargetIOSSimulator()) {
1137 ; // iOS simulator does not need bundle1.o.
1138 } else if (isTargetIPhoneOS()) {
1139 if (isIPhoneOSVersionLT(3, 1))
1140 CmdArgs.push_back("-lbundle1.o");
1142 if (isMacosxVersionLT(10, 6))
1143 CmdArgs.push_back("-lbundle1.o");
1147 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1148 if (Args.hasArg(options::OPT_static) ||
1149 Args.hasArg(options::OPT_object) ||
1150 Args.hasArg(options::OPT_preload)) {
1151 CmdArgs.push_back("-lgcrt0.o");
1153 CmdArgs.push_back("-lgcrt1.o");
1155 // darwin_crt2 spec is empty.
1157 // By default on OS X 10.8 and later, we don't link with a crt1.o
1158 // file and the linker knows to use _main as the entry point. But,
1159 // when compiling with -pg, we need to link with the gcrt1.o file,
1160 // so pass the -no_new_main option to tell the linker to use the
1161 // "start" symbol as the entry point.
1162 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1163 CmdArgs.push_back("-no_new_main");
1165 if (Args.hasArg(options::OPT_static) ||
1166 Args.hasArg(options::OPT_object) ||
1167 Args.hasArg(options::OPT_preload)) {
1168 CmdArgs.push_back("-lcrt0.o");
1170 // Derived from darwin_crt1 spec.
1171 if (isTargetWatchOSBased()) {
1172 ; // watchOS does not need crt1.o.
1173 } else if (isTargetIOSSimulator()) {
1174 ; // iOS simulator does not need crt1.o.
1175 } else if (isTargetIPhoneOS()) {
1176 if (getArch() == llvm::Triple::aarch64)
1177 ; // iOS does not need any crt1 files for arm64
1178 else if (isIPhoneOSVersionLT(3, 1))
1179 CmdArgs.push_back("-lcrt1.o");
1180 else if (isIPhoneOSVersionLT(6, 0))
1181 CmdArgs.push_back("-lcrt1.3.1.o");
1183 if (isMacosxVersionLT(10, 5))
1184 CmdArgs.push_back("-lcrt1.o");
1185 else if (isMacosxVersionLT(10, 6))
1186 CmdArgs.push_back("-lcrt1.10.5.o");
1187 else if (isMacosxVersionLT(10, 8))
1188 CmdArgs.push_back("-lcrt1.10.6.o");
1190 // darwin_crt2 spec is empty.
1197 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1198 !isTargetWatchOS() &&
1199 isMacosxVersionLT(10, 5)) {
1200 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1201 CmdArgs.push_back(Str);
1205 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1207 void Darwin::CheckObjCARC() const {
1208 if (isTargetIOSBased() || isTargetWatchOSBased() ||
1209 (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1211 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1214 SanitizerMask Darwin::getSupportedSanitizers() const {
1215 SanitizerMask Res = ToolChain::getSupportedSanitizers();
1216 if (isTargetMacOS() || isTargetIOSSimulator())
1217 Res |= SanitizerKind::Address;
1218 if (isTargetMacOS()) {
1219 if (!isMacosxVersionLT(10, 9))
1220 Res |= SanitizerKind::Vptr;
1221 Res |= SanitizerKind::SafeStack;
1222 Res |= SanitizerKind::Thread;
1227 /// Generic_GCC - A tool chain using the 'gcc' command to perform
1228 /// all subcommands; this relies on gcc translating the majority of
1229 /// command line options.
1231 /// \brief Parse a GCCVersion object out of a string of text.
1233 /// This is the primary means of forming GCCVersion objects.
1235 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
1236 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1237 std::pair<StringRef, StringRef> First = VersionText.split('.');
1238 std::pair<StringRef, StringRef> Second = First.second.split('.');
1240 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""};
1241 if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0)
1243 GoodVersion.MajorStr = First.first.str();
1244 if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0)
1246 GoodVersion.MinorStr = Second.first.str();
1248 // First look for a number prefix and parse that if present. Otherwise just
1249 // stash the entire patch string in the suffix, and leave the number
1250 // unspecified. This covers versions strings such as:
1256 // And retains any patch number it finds.
1257 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str();
1258 if (!PatchText.empty()) {
1259 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) {
1260 // Try to parse the number and any suffix.
1261 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) ||
1262 GoodVersion.Patch < 0)
1264 GoodVersion.PatchSuffix = PatchText.substr(EndNumber);
1271 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
1272 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor,
1274 StringRef RHSPatchSuffix) const {
1275 if (Major != RHSMajor)
1276 return Major < RHSMajor;
1277 if (Minor != RHSMinor)
1278 return Minor < RHSMinor;
1279 if (Patch != RHSPatch) {
1280 // Note that versions without a specified patch sort higher than those with
1287 // Otherwise just sort on the patch itself.
1288 return Patch < RHSPatch;
1290 if (PatchSuffix != RHSPatchSuffix) {
1291 // Sort empty suffixes higher.
1292 if (RHSPatchSuffix.empty())
1294 if (PatchSuffix.empty())
1297 // Provide a lexicographic sort to make this a total ordering.
1298 return PatchSuffix < RHSPatchSuffix;
1301 // The versions are equal.
1305 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) {
1306 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain);
1308 return A->getValue();
1309 return GCC_INSTALL_PREFIX;
1312 /// \brief Initialize a GCCInstallationDetector from the driver.
1314 /// This performs all of the autodetection and sets up the various paths.
1315 /// Once constructed, a GCCInstallationDetector is essentially immutable.
1317 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
1318 /// should instead pull the target out of the driver. This is currently
1319 /// necessary because the driver doesn't store the final version of the target
1321 void Generic_GCC::GCCInstallationDetector::init(
1322 const llvm::Triple &TargetTriple, const ArgList &Args,
1323 ArrayRef<std::string> ExtraTripleAliases) {
1324 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit()
1325 ? TargetTriple.get64BitArchVariant()
1326 : TargetTriple.get32BitArchVariant();
1327 // The library directories which may contain GCC installations.
1328 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs;
1329 // The compatible GCC triples for this particular architecture.
1330 SmallVector<StringRef, 16> CandidateTripleAliases;
1331 SmallVector<StringRef, 16> CandidateBiarchTripleAliases;
1332 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs,
1333 CandidateTripleAliases, CandidateBiarchLibDirs,
1334 CandidateBiarchTripleAliases);
1336 // Compute the set of prefixes for our search.
1337 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
1338 D.PrefixDirs.end());
1340 StringRef GCCToolchainDir = getGCCToolchainDir(Args);
1341 if (GCCToolchainDir != "") {
1342 if (GCCToolchainDir.back() == '/')
1343 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the /
1345 Prefixes.push_back(GCCToolchainDir);
1347 // If we have a SysRoot, try that first.
1348 if (!D.SysRoot.empty()) {
1349 Prefixes.push_back(D.SysRoot);
1350 Prefixes.push_back(D.SysRoot + "/usr");
1353 // Then look for gcc installed alongside clang.
1354 Prefixes.push_back(D.InstalledDir + "/..");
1356 // And finally in /usr.
1357 if (D.SysRoot.empty())
1358 Prefixes.push_back("/usr");
1361 // Loop over the various components which exist and select the best GCC
1362 // installation available. GCC installs are ranked by version number.
1363 Version = GCCVersion::Parse("0.0.0");
1364 for (const std::string &Prefix : Prefixes) {
1365 if (!D.getVFS().exists(Prefix))
1367 for (StringRef Suffix : CandidateLibDirs) {
1368 const std::string LibDir = Prefix + Suffix.str();
1369 if (!D.getVFS().exists(LibDir))
1371 for (StringRef Candidate : ExtraTripleAliases) // Try these first.
1372 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1373 for (StringRef Candidate : CandidateTripleAliases)
1374 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate);
1376 for (StringRef Suffix : CandidateBiarchLibDirs) {
1377 const std::string LibDir = Prefix + Suffix.str();
1378 if (!D.getVFS().exists(LibDir))
1380 for (StringRef Candidate : CandidateBiarchTripleAliases)
1381 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate,
1382 /*NeedsBiarchSuffix=*/ true);
1387 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const {
1388 for (const auto &InstallPath : CandidateGCCInstallPaths)
1389 OS << "Found candidate GCC installation: " << InstallPath << "\n";
1391 if (!GCCInstallPath.empty())
1392 OS << "Selected GCC installation: " << GCCInstallPath << "\n";
1394 for (const auto &Multilib : Multilibs)
1395 OS << "Candidate multilib: " << Multilib << "\n";
1397 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault())
1398 OS << "Selected multilib: " << SelectedMultilib << "\n";
1401 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const {
1402 if (BiarchSibling.hasValue()) {
1403 M = BiarchSibling.getValue();
1409 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
1410 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple,
1411 SmallVectorImpl<StringRef> &LibDirs,
1412 SmallVectorImpl<StringRef> &TripleAliases,
1413 SmallVectorImpl<StringRef> &BiarchLibDirs,
1414 SmallVectorImpl<StringRef> &BiarchTripleAliases) {
1415 // Declare a bunch of static data sets that we'll select between below. These
1416 // are specifically designed to always refer to string literals to avoid any
1417 // lifetime or initialization issues.
1418 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
1419 static const char *const AArch64Triples[] = {
1420 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
1421 "aarch64-redhat-linux"};
1422 static const char *const AArch64beLibDirs[] = {"/lib"};
1423 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
1424 "aarch64_be-linux-gnu"};
1426 static const char *const ARMLibDirs[] = {"/lib"};
1427 static const char *const ARMTriples[] = {"arm-linux-gnueabi",
1428 "arm-linux-androideabi"};
1429 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
1430 "armv7hl-redhat-linux-gnueabi"};
1431 static const char *const ARMebLibDirs[] = {"/lib"};
1432 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
1433 "armeb-linux-androideabi"};
1434 static const char *const ARMebHFTriples[] = {
1435 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
1437 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
1438 static const char *const X86_64Triples[] = {
1439 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu",
1440 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E",
1441 "x86_64-redhat-linux", "x86_64-suse-linux",
1442 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
1443 "x86_64-slackware-linux", "x86_64-linux-android",
1444 "x86_64-unknown-linux"};
1445 static const char *const X32LibDirs[] = {"/libx32"};
1446 static const char *const X86LibDirs[] = {"/lib32", "/lib"};
1447 static const char *const X86Triples[] = {
1448 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu",
1449 "i386-linux-gnu", "i386-redhat-linux6E", "i686-redhat-linux",
1450 "i586-redhat-linux", "i386-redhat-linux", "i586-suse-linux",
1451 "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
1454 static const char *const MIPSLibDirs[] = {"/lib"};
1455 static const char *const MIPSTriples[] = {"mips-linux-gnu", "mips-mti-linux",
1456 "mips-mti-linux-gnu",
1457 "mips-img-linux-gnu"};
1458 static const char *const MIPSELLibDirs[] = {"/lib"};
1459 static const char *const MIPSELTriples[] = {
1460 "mipsel-linux-gnu", "mipsel-linux-android", "mips-img-linux-gnu"};
1462 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"};
1463 static const char *const MIPS64Triples[] = {
1464 "mips64-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1465 "mips64-linux-gnuabi64"};
1466 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"};
1467 static const char *const MIPS64ELTriples[] = {
1468 "mips64el-linux-gnu", "mips-mti-linux-gnu", "mips-img-linux-gnu",
1469 "mips64el-linux-android", "mips64el-linux-gnuabi64"};
1471 static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
1472 static const char *const PPCTriples[] = {
1473 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
1474 "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
1475 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
1476 static const char *const PPC64Triples[] = {
1477 "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
1478 "powerpc64-suse-linux", "ppc64-redhat-linux"};
1479 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"};
1480 static const char *const PPC64LETriples[] = {
1481 "powerpc64le-linux-gnu", "powerpc64le-unknown-linux-gnu",
1482 "powerpc64le-suse-linux", "ppc64le-redhat-linux"};
1484 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"};
1485 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu",
1486 "sparcv8-linux-gnu"};
1487 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"};
1488 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu",
1489 "sparcv9-linux-gnu"};
1491 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"};
1492 static const char *const SystemZTriples[] = {
1493 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu",
1494 "s390x-suse-linux", "s390x-redhat-linux"};
1497 static const char *const SolarisSPARCLibDirs[] = {"/gcc"};
1498 static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11",
1499 "i386-pc-solaris2.11"};
1504 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
1505 LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs));
1506 TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples));
1510 switch (TargetTriple.getArch()) {
1511 case llvm::Triple::aarch64:
1512 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1513 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1514 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs));
1515 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples));
1517 case llvm::Triple::aarch64_be:
1518 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1519 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1520 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs));
1521 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples));
1523 case llvm::Triple::arm:
1524 case llvm::Triple::thumb:
1525 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs));
1526 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1527 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples));
1529 TripleAliases.append(begin(ARMTriples), end(ARMTriples));
1532 case llvm::Triple::armeb:
1533 case llvm::Triple::thumbeb:
1534 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs));
1535 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) {
1536 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples));
1538 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
1541 case llvm::Triple::x86_64:
1542 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1543 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1544 // x32 is always available when x86_64 is available, so adding it as
1545 // secondary arch with x86_64 triples
1546 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) {
1547 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs));
1548 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1550 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1551 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples));
1554 case llvm::Triple::x86:
1555 LibDirs.append(begin(X86LibDirs), end(X86LibDirs));
1556 TripleAliases.append(begin(X86Triples), end(X86Triples));
1557 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
1558 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
1560 case llvm::Triple::mips:
1561 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1562 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1563 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1564 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1566 case llvm::Triple::mipsel:
1567 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1568 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1569 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1570 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1571 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1573 case llvm::Triple::mips64:
1574 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs));
1575 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples));
1576 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs));
1577 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1579 case llvm::Triple::mips64el:
1580 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs));
1581 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples));
1582 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs));
1583 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples));
1584 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples));
1586 case llvm::Triple::ppc:
1587 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1588 TripleAliases.append(begin(PPCTriples), end(PPCTriples));
1589 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1590 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1592 case llvm::Triple::ppc64:
1593 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs));
1594 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples));
1595 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs));
1596 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples));
1598 case llvm::Triple::ppc64le:
1599 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs));
1600 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples));
1602 case llvm::Triple::sparc:
1603 case llvm::Triple::sparcel:
1604 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1605 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1606 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1607 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1609 case llvm::Triple::sparcv9:
1610 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs));
1611 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples));
1612 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs));
1613 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples));
1615 case llvm::Triple::systemz:
1616 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs));
1617 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples));
1620 // By default, just rely on the standard lib directories and the original
1625 // Always append the drivers target triple to the end, in case it doesn't
1626 // match any of our aliases.
1627 TripleAliases.push_back(TargetTriple.str());
1629 // Also include the multiarch variant if it's different.
1630 if (TargetTriple.str() != BiarchTriple.str())
1631 BiarchTripleAliases.push_back(BiarchTriple.str());
1634 // \brief -- try common CUDA installation paths looking for files we need for
1635 // CUDA compilation.
1637 void Generic_GCC::CudaInstallationDetector::init(
1638 const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args) {
1639 SmallVector<std::string, 4> CudaPathCandidates;
1641 if (Args.hasArg(options::OPT_cuda_path_EQ))
1642 CudaPathCandidates.push_back(
1643 Args.getLastArgValue(options::OPT_cuda_path_EQ));
1645 CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda");
1646 CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.5");
1647 CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-7.0");
1650 for (const auto &CudaPath : CudaPathCandidates) {
1651 if (CudaPath.empty() || !D.getVFS().exists(CudaPath))
1654 CudaInstallPath = CudaPath;
1655 CudaIncludePath = CudaInstallPath + "/include";
1656 CudaLibDevicePath = CudaInstallPath + "/nvvm/libdevice";
1658 CudaInstallPath + (TargetTriple.isArch64Bit() ? "/lib64" : "/lib");
1660 if (!(D.getVFS().exists(CudaIncludePath) &&
1661 D.getVFS().exists(CudaLibPath) &&
1662 D.getVFS().exists(CudaLibDevicePath)))
1666 for (llvm::sys::fs::directory_iterator LI(CudaLibDevicePath, EC), LE;
1667 !EC && LI != LE; LI = LI.increment(EC)) {
1668 StringRef FilePath = LI->path();
1669 StringRef FileName = llvm::sys::path::filename(FilePath);
1670 // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc
1671 const StringRef LibDeviceName = "libdevice.";
1672 if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
1674 StringRef GpuArch = FileName.slice(
1675 LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
1676 CudaLibDeviceMap[GpuArch] = FilePath.str();
1677 // Insert map entries for specifc devices with this compute capability.
1678 if (GpuArch == "compute_20") {
1679 CudaLibDeviceMap["sm_20"] = FilePath;
1680 CudaLibDeviceMap["sm_21"] = FilePath;
1681 } else if (GpuArch == "compute_30") {
1682 CudaLibDeviceMap["sm_30"] = FilePath;
1683 CudaLibDeviceMap["sm_32"] = FilePath;
1684 } else if (GpuArch == "compute_35") {
1685 CudaLibDeviceMap["sm_35"] = FilePath;
1686 CudaLibDeviceMap["sm_37"] = FilePath;
1695 void Generic_GCC::CudaInstallationDetector::print(raw_ostream &OS) const {
1697 OS << "Found CUDA installation: " << CudaInstallPath << "\n";
1701 // Filter to remove Multilibs that don't exist as a suffix to Path
1702 class FilterNonExistent {
1704 vfs::FileSystem &VFS;
1707 FilterNonExistent(StringRef Base, vfs::FileSystem &VFS)
1708 : Base(Base), VFS(VFS) {}
1709 bool operator()(const Multilib &M) {
1710 return !VFS.exists(Base + M.gccSuffix() + "/crtbegin.o");
1713 } // end anonymous namespace
1715 static void addMultilibFlag(bool Enabled, const char *const Flag,
1716 std::vector<std::string> &Flags) {
1718 Flags.push_back(std::string("+") + Flag);
1720 Flags.push_back(std::string("-") + Flag);
1723 static bool isMipsArch(llvm::Triple::ArchType Arch) {
1724 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
1725 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1728 static bool isMips32(llvm::Triple::ArchType Arch) {
1729 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel;
1732 static bool isMips64(llvm::Triple::ArchType Arch) {
1733 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el;
1736 static bool isMipsEL(llvm::Triple::ArchType Arch) {
1737 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el;
1740 static bool isMips16(const ArgList &Args) {
1741 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16);
1742 return A && A->getOption().matches(options::OPT_mips16);
1745 static bool isMicroMips(const ArgList &Args) {
1746 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips);
1747 return A && A->getOption().matches(options::OPT_mmicromips);
1751 struct DetectedMultilibs {
1752 /// The set of multilibs that the detected installation supports.
1753 MultilibSet Multilibs;
1755 /// The primary multilib appropriate for the given flags.
1756 Multilib SelectedMultilib;
1758 /// On Biarch systems, this corresponds to the default multilib when
1759 /// targeting the non-default multilib. Otherwise, it is empty.
1760 llvm::Optional<Multilib> BiarchSibling;
1762 } // end anonymous namespace
1764 static Multilib makeMultilib(StringRef commonSuffix) {
1765 return Multilib(commonSuffix, commonSuffix, commonSuffix);
1768 static bool findMIPSMultilibs(const Driver &D, const llvm::Triple &TargetTriple,
1769 StringRef Path, const ArgList &Args,
1770 DetectedMultilibs &Result) {
1771 // Some MIPS toolchains put libraries and object files compiled
1772 // using different options in to the sub-directoris which names
1773 // reflects the flags used for compilation. For example sysroot
1774 // directory might looks like the following examples:
1777 // /lib <= crt*.o files compiled with '-mips32'
1780 // /lib <= crt*.o files compiled with '-mips16'
1783 // /lib <= crt*.o files compiled with '-mips16 -EL'
1788 // /lib <= crt*.o files compiled with '-mips32r2'
1791 // /lib <= crt*.o files compiled with '-mips32r2 -mips16'
1794 // /lib <= crt*.o files compiled with '-mips32'
1796 FilterNonExistent NonExistent(Path, D.getVFS());
1798 // Check for FSF toolchain multilibs
1799 MultilibSet FSFMipsMultilibs;
1801 auto MArchMips32 = makeMultilib("/mips32")
1804 .flag("-mmicromips")
1805 .flag("+march=mips32");
1807 auto MArchMicroMips = makeMultilib("/micromips")
1810 .flag("+mmicromips");
1812 auto MArchMips64r2 = makeMultilib("/mips64r2")
1815 .flag("+march=mips64r2");
1817 auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag(
1820 auto MArchDefault = makeMultilib("")
1823 .flag("-mmicromips")
1824 .flag("+march=mips32r2");
1826 auto Mips16 = makeMultilib("/mips16").flag("+mips16");
1828 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1831 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1833 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1835 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1837 auto SoftFloat = makeMultilib("/sof").flag("+msoft-float");
1839 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1843 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64,
1847 .FilterOut("/mips64/mips16")
1848 .FilterOut("/mips64r2/mips16")
1849 .FilterOut("/micromips/mips16")
1851 .FilterOut("/micromips/64")
1852 .FilterOut("/mips32/64")
1854 .FilterOut("/mips16/64")
1855 .Either(BigEndian, LittleEndian)
1858 .FilterOut(".*sof/nan2008")
1859 .FilterOut(NonExistent)
1860 .setIncludeDirsCallback([](StringRef InstallDir,
1861 StringRef TripleStr, const Multilib &M) {
1862 std::vector<std::string> Dirs;
1863 Dirs.push_back((InstallDir + "/include").str());
1864 std::string SysRootInc =
1865 InstallDir.str() + "/../../../../sysroot";
1866 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1867 Dirs.push_back(SysRootInc + "/uclibc/usr/include");
1869 Dirs.push_back(SysRootInc + "/usr/include");
1874 // Check for Musl toolchain multilibs
1875 MultilibSet MuslMipsMultilibs;
1877 auto MArchMipsR2 = makeMultilib("")
1878 .osSuffix("/mips-r2-hard-musl")
1881 .flag("+march=mips32r2");
1883 auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl")
1886 .flag("+march=mips32r2");
1888 MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2);
1890 // Specify the callback that computes the include directories.
1891 MuslMipsMultilibs.setIncludeDirsCallback([](
1892 StringRef InstallDir, StringRef TripleStr, const Multilib &M) {
1893 std::vector<std::string> Dirs;
1895 (InstallDir + "/../sysroot" + M.osSuffix() + "/usr/include").str());
1900 // Check for Code Sourcery toolchain multilibs
1901 MultilibSet CSMipsMultilibs;
1903 auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16");
1905 auto MArchMicroMips =
1906 makeMultilib("/micromips").flag("+m32").flag("+mmicromips");
1908 auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips");
1910 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc");
1912 auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float");
1914 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008");
1917 makeMultilib("").flag("-msoft-float").flag("-mnan=2008");
1919 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL");
1921 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1923 // Note that this one's osSuffix is ""
1924 auto MAbi64 = makeMultilib("")
1926 .includeSuffix("/64")
1933 .Either(MArchMips16, MArchMicroMips, MArchDefault)
1935 .Either(SoftFloat, Nan2008, DefaultFloat)
1936 .FilterOut("/micromips/nan2008")
1937 .FilterOut("/mips16/nan2008")
1938 .Either(BigEndian, LittleEndian)
1940 .FilterOut("/mips16.*/64")
1941 .FilterOut("/micromips.*/64")
1942 .FilterOut(NonExistent)
1943 .setIncludeDirsCallback([](StringRef InstallDir,
1944 StringRef TripleStr, const Multilib &M) {
1945 std::vector<std::string> Dirs;
1946 Dirs.push_back((InstallDir + "/include").str());
1947 std::string SysRootInc =
1948 InstallDir.str() + "/../../../../" + TripleStr.str();
1949 if (StringRef(M.includeSuffix()).startswith("/uclibc"))
1950 Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include");
1952 Dirs.push_back(SysRootInc + "/libc/usr/include");
1957 MultilibSet AndroidMipsMultilibs =
1959 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2"))
1960 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6"))
1961 .FilterOut(NonExistent);
1963 MultilibSet DebianMipsMultilibs;
1966 Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32");
1968 Multilib M64 = Multilib()
1970 .includeSuffix("/64")
1975 Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32");
1977 DebianMipsMultilibs =
1978 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent);
1981 MultilibSet ImgMultilibs;
1983 auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32");
1985 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB");
1988 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32");
1994 .Maybe(LittleEndian)
1995 .FilterOut(NonExistent)
1996 .setIncludeDirsCallback([](StringRef InstallDir,
1997 StringRef TripleStr, const Multilib &M) {
1998 std::vector<std::string> Dirs;
1999 Dirs.push_back((InstallDir + "/include").str());
2001 (InstallDir + "/../../../../sysroot/usr/include").str());
2008 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName);
2010 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2012 Multilib::flags_list Flags;
2013 addMultilibFlag(isMips32(TargetArch), "m32", Flags);
2014 addMultilibFlag(isMips64(TargetArch), "m64", Flags);
2015 addMultilibFlag(isMips16(Args), "mips16", Flags);
2016 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags);
2017 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" ||
2018 CPUName == "mips32r5" || CPUName == "p5600",
2019 "march=mips32r2", Flags);
2020 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags);
2021 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags);
2022 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" ||
2023 CPUName == "mips64r5" || CPUName == "octeon",
2024 "march=mips64r2", Flags);
2025 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags);
2026 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags);
2027 addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008",
2029 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags);
2030 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags);
2031 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags);
2032 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags);
2033 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags);
2034 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags);
2036 if (TargetTriple.isAndroid()) {
2037 // Select Android toolchain. It's the only choice in that case.
2038 if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2039 Result.Multilibs = AndroidMipsMultilibs;
2045 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies &&
2046 TargetTriple.getOS() == llvm::Triple::Linux &&
2047 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment) {
2048 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilib)) {
2049 Result.Multilibs = MuslMipsMultilibs;
2055 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies &&
2056 TargetTriple.getOS() == llvm::Triple::Linux &&
2057 TargetTriple.getEnvironment() == llvm::Triple::GNU) {
2058 // Select mips-img-linux-gnu toolchain.
2059 if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) {
2060 Result.Multilibs = ImgMultilibs;
2066 // Sort candidates. Toolchain that best meets the directories goes first.
2067 // Then select the first toolchains matches command line flags.
2068 MultilibSet *candidates[] = {&DebianMipsMultilibs, &FSFMipsMultilibs,
2071 std::begin(candidates), std::end(candidates),
2072 [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); });
2073 for (const auto &candidate : candidates) {
2074 if (candidate->select(Flags, Result.SelectedMultilib)) {
2075 if (candidate == &DebianMipsMultilibs)
2076 Result.BiarchSibling = Multilib();
2077 Result.Multilibs = *candidate;
2083 // Fallback to the regular toolchain-tree structure.
2085 Result.Multilibs.push_back(Default);
2086 Result.Multilibs.FilterOut(NonExistent);
2088 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) {
2089 Result.BiarchSibling = Multilib();
2097 static bool findBiarchMultilibs(const Driver &D,
2098 const llvm::Triple &TargetTriple,
2099 StringRef Path, const ArgList &Args,
2100 bool NeedsBiarchSuffix,
2101 DetectedMultilibs &Result) {
2102 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
2103 // in what would normally be GCCInstallPath and put the 64-bit
2104 // libs in a subdirectory named 64. The simple logic we follow is that
2105 // *if* there is a subdirectory of the right name with crtbegin.o in it,
2106 // we use that. If not, and if not a biarch triple alias, we look for
2107 // crtbegin.o without the subdirectory.
2110 Multilib Alt64 = Multilib()
2112 .includeSuffix("/64")
2116 Multilib Alt32 = Multilib()
2118 .includeSuffix("/32")
2122 Multilib Altx32 = Multilib()
2124 .includeSuffix("/x32")
2129 FilterNonExistent NonExistent(Path, D.getVFS());
2131 // Determine default multilib from: 32, 64, x32
2132 // Also handle cases such as 64 on 32, 32 on 64, etc.
2133 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN;
2134 const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32;
2135 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32))
2137 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32))
2139 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64))
2142 if (TargetTriple.isArch32Bit())
2143 Want = NeedsBiarchSuffix ? WANT64 : WANT32;
2145 Want = NeedsBiarchSuffix ? WANT64 : WANTX32;
2147 Want = NeedsBiarchSuffix ? WANT32 : WANT64;
2151 Default.flag("+m32").flag("-m64").flag("-mx32");
2152 else if (Want == WANT64)
2153 Default.flag("-m32").flag("+m64").flag("-mx32");
2154 else if (Want == WANTX32)
2155 Default.flag("-m32").flag("-m64").flag("+mx32");
2159 Result.Multilibs.push_back(Default);
2160 Result.Multilibs.push_back(Alt64);
2161 Result.Multilibs.push_back(Alt32);
2162 Result.Multilibs.push_back(Altx32);
2164 Result.Multilibs.FilterOut(NonExistent);
2166 Multilib::flags_list Flags;
2167 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags);
2168 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags);
2169 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags);
2171 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib))
2174 if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 ||
2175 Result.SelectedMultilib == Altx32)
2176 Result.BiarchSibling = Default;
2181 void Generic_GCC::GCCInstallationDetector::scanLibDirForGCCTripleSolaris(
2182 const llvm::Triple &TargetArch, const llvm::opt::ArgList &Args,
2183 const std::string &LibDir, StringRef CandidateTriple,
2184 bool NeedsBiarchSuffix) {
2185 // Solaris is a special case. The GCC installation is under
2186 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/, so we
2187 // need to iterate twice.
2189 for (vfs::directory_iterator LI = D.getVFS().dir_begin(LibDir, EC), LE;
2190 !EC && LI != LE; LI = LI.increment(EC)) {
2191 StringRef VersionText = llvm::sys::path::filename(LI->getName());
2192 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2194 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2195 if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2196 continue; // Saw this path before; no need to look at it again.
2197 if (CandidateVersion.isOlderThan(4, 1, 1))
2199 if (CandidateVersion <= Version)
2203 LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str();
2204 if (!D.getVFS().exists(GCCInstallPath))
2207 // If we make it here there has to be at least one GCC version, let's just
2208 // use the latest one.
2209 std::error_code EEC;
2210 for (vfs::directory_iterator
2211 LLI = D.getVFS().dir_begin(GCCInstallPath, EEC),
2213 !EEC && LLI != LLE; LLI = LLI.increment(EEC)) {
2215 StringRef SubVersionText = llvm::sys::path::filename(LLI->getName());
2216 GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText);
2218 if (CandidateSubVersion > Version)
2219 Version = CandidateSubVersion;
2222 GCCTriple.setTriple(CandidateTriple);
2224 GCCInstallPath += "/" + Version.Text;
2225 GCCParentLibPath = GCCInstallPath + "/../../../../";
2231 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
2232 const llvm::Triple &TargetTriple, const ArgList &Args,
2233 const std::string &LibDir, StringRef CandidateTriple,
2234 bool NeedsBiarchSuffix) {
2235 llvm::Triple::ArchType TargetArch = TargetTriple.getArch();
2236 // There are various different suffixes involving the triple we
2237 // check for. We also record what is necessary to walk from each back
2238 // up to the lib directory. Specifically, the number of "up" steps
2239 // in the second half of each row is 1 + the number of path separators
2240 // in the first half.
2241 const std::string LibAndInstallSuffixes[][2] = {
2242 {"/gcc/" + CandidateTriple.str(), "/../../.."},
2244 // Debian puts cross-compilers in gcc-cross
2245 {"/gcc-cross/" + CandidateTriple.str(), "/../../.."},
2247 {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
2250 // The Freescale PPC SDK has the gcc libraries in
2251 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well.
2252 {"/" + CandidateTriple.str(), "/../.."},
2254 // Ubuntu has a strange mis-matched pair of triples that this happens to
2256 // FIXME: It may be worthwhile to generalize this and look for a second
2258 {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}};
2260 if (TargetTriple.getOS() == llvm::Triple::Solaris) {
2261 scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple,
2266 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
2267 const unsigned NumLibSuffixes = (llvm::array_lengthof(LibAndInstallSuffixes) -
2268 (TargetArch != llvm::Triple::x86));
2269 for (unsigned i = 0; i < NumLibSuffixes; ++i) {
2270 StringRef LibSuffix = LibAndInstallSuffixes[i][0];
2272 for (vfs::directory_iterator
2273 LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC),
2275 !EC && LI != LE; LI = LI.increment(EC)) {
2276 StringRef VersionText = llvm::sys::path::filename(LI->getName());
2277 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText);
2278 if (CandidateVersion.Major != -1) // Filter obviously bad entries.
2279 if (!CandidateGCCInstallPaths.insert(LI->getName()).second)
2280 continue; // Saw this path before; no need to look at it again.
2281 if (CandidateVersion.isOlderThan(4, 1, 1))
2283 if (CandidateVersion <= Version)
2286 DetectedMultilibs Detected;
2288 // Debian mips multilibs behave more like the rest of the biarch ones,
2289 // so handle them there
2290 if (isMipsArch(TargetArch)) {
2291 if (!findMIPSMultilibs(D, TargetTriple, LI->getName(), Args, Detected))
2293 } else if (!findBiarchMultilibs(D, TargetTriple, LI->getName(), Args,
2294 NeedsBiarchSuffix, Detected)) {
2298 Multilibs = Detected.Multilibs;
2299 SelectedMultilib = Detected.SelectedMultilib;
2300 BiarchSibling = Detected.BiarchSibling;
2301 Version = CandidateVersion;
2302 GCCTriple.setTriple(CandidateTriple);
2303 // FIXME: We hack together the directory name here instead of
2304 // using LI to ensure stable path separators across Windows and
2307 LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str();
2308 GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1];
2314 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple,
2315 const ArgList &Args)
2316 : ToolChain(D, Triple, Args), GCCInstallation(D), CudaInstallation(D) {
2317 getProgramPaths().push_back(getDriver().getInstalledDir());
2318 if (getDriver().getInstalledDir() != getDriver().Dir)
2319 getProgramPaths().push_back(getDriver().Dir);
2322 Generic_GCC::~Generic_GCC() {}
2324 Tool *Generic_GCC::getTool(Action::ActionClass AC) const {
2326 case Action::PreprocessJobClass:
2328 Preprocess.reset(new tools::gcc::Preprocessor(*this));
2329 return Preprocess.get();
2330 case Action::CompileJobClass:
2332 Compile.reset(new tools::gcc::Compiler(*this));
2333 return Compile.get();
2335 return ToolChain::getTool(AC);
2339 Tool *Generic_GCC::buildAssembler() const {
2340 return new tools::gnutools::Assembler(*this);
2343 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); }
2345 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const {
2346 // Print the information about how we detected the GCC installation.
2347 GCCInstallation.print(OS);
2348 CudaInstallation.print(OS);
2351 bool Generic_GCC::IsUnwindTablesDefault() const {
2352 return getArch() == llvm::Triple::x86_64;
2355 bool Generic_GCC::isPICDefault() const {
2356 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2359 bool Generic_GCC::isPIEDefault() const { return false; }
2361 bool Generic_GCC::isPICDefaultForced() const {
2362 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows();
2365 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
2366 switch (getTriple().getArch()) {
2367 case llvm::Triple::x86:
2368 case llvm::Triple::x86_64:
2369 case llvm::Triple::aarch64:
2370 case llvm::Triple::aarch64_be:
2371 case llvm::Triple::arm:
2372 case llvm::Triple::armeb:
2373 case llvm::Triple::bpfel:
2374 case llvm::Triple::bpfeb:
2375 case llvm::Triple::thumb:
2376 case llvm::Triple::thumbeb:
2377 case llvm::Triple::ppc:
2378 case llvm::Triple::ppc64:
2379 case llvm::Triple::ppc64le:
2380 case llvm::Triple::systemz:
2387 /// \brief Helper to add the variant paths of a libstdc++ installation.
2388 bool Generic_GCC::addLibStdCXXIncludePaths(
2389 Twine Base, Twine Suffix, StringRef GCCTriple, StringRef GCCMultiarchTriple,
2390 StringRef TargetMultiarchTriple, Twine IncludeSuffix,
2391 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2392 if (!getVFS().exists(Base + Suffix))
2395 addSystemInclude(DriverArgs, CC1Args, Base + Suffix);
2397 // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If
2398 // that path exists or we have neither a GCC nor target multiarch triple, use
2399 // this vanilla search path.
2400 if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) ||
2401 getVFS().exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) {
2402 addSystemInclude(DriverArgs, CC1Args,
2403 Base + Suffix + "/" + GCCTriple + IncludeSuffix);
2405 // Otherwise try to use multiarch naming schemes which have normalized the
2406 // triples and put the triple before the suffix.
2408 // GCC surprisingly uses *both* the GCC triple with a multilib suffix and
2409 // the target triple, so we support that here.
2410 addSystemInclude(DriverArgs, CC1Args,
2411 Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix);
2412 addSystemInclude(DriverArgs, CC1Args,
2413 Base + "/" + TargetMultiarchTriple + Suffix);
2416 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward");
2421 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs,
2422 ArgStringList &CC1Args) const {
2423 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion();
2424 bool UseInitArrayDefault =
2425 getTriple().getArch() == llvm::Triple::aarch64 ||
2426 getTriple().getArch() == llvm::Triple::aarch64_be ||
2427 (getTriple().getOS() == llvm::Triple::Linux &&
2428 (!V.isOlderThan(4, 7, 0) || getTriple().isAndroid())) ||
2429 getTriple().getOS() == llvm::Triple::NaCl ||
2430 (getTriple().getVendor() == llvm::Triple::MipsTechnologies &&
2431 !getTriple().hasEnvironment());
2433 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
2434 options::OPT_fno_use_init_array, UseInitArrayDefault))
2435 CC1Args.push_back("-fuse-init-array");
2439 MipsLLVMToolChain::MipsLLVMToolChain(const Driver &D,
2440 const llvm::Triple &Triple,
2441 const ArgList &Args)
2442 : Linux(D, Triple, Args) {
2443 // Select the correct multilib according to the given arguments.
2444 DetectedMultilibs Result;
2445 findMIPSMultilibs(D, Triple, "", Args, Result);
2446 Multilibs = Result.Multilibs;
2447 SelectedMultilib = Result.SelectedMultilib;
2449 // Find out the library suffix based on the ABI.
2450 LibSuffix = tools::mips::getMipsABILibSuffix(Args, Triple);
2451 getFilePaths().clear();
2452 getFilePaths().push_back(computeSysRoot() + "/usr/lib" + LibSuffix);
2454 // Use LLD by default.
2455 DefaultLinker = "lld";
2458 void MipsLLVMToolChain::AddClangSystemIncludeArgs(
2459 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2460 if (DriverArgs.hasArg(options::OPT_nostdinc))
2463 const Driver &D = getDriver();
2465 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2466 SmallString<128> P(D.ResourceDir);
2467 llvm::sys::path::append(P, "include");
2468 addSystemInclude(DriverArgs, CC1Args, P);
2471 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2474 const auto &Callback = Multilibs.includeDirsCallback();
2476 const auto IncludePaths =
2477 Callback(D.getInstalledDir(), getTripleString(), SelectedMultilib);
2478 for (const auto &Path : IncludePaths)
2479 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
2483 Tool *MipsLLVMToolChain::buildLinker() const {
2484 return new tools::gnutools::Linker(*this);
2487 std::string MipsLLVMToolChain::computeSysRoot() const {
2488 if (!getDriver().SysRoot.empty())
2489 return getDriver().SysRoot + SelectedMultilib.osSuffix();
2491 const std::string InstalledDir(getDriver().getInstalledDir());
2492 std::string SysRootPath =
2493 InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix();
2494 if (llvm::sys::fs::exists(SysRootPath))
2497 return std::string();
2500 ToolChain::CXXStdlibType
2501 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const {
2502 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2504 StringRef Value = A->getValue();
2505 if (Value != "libc++")
2506 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
2507 << A->getAsString(Args);
2510 return ToolChain::CST_Libcxx;
2513 void MipsLLVMToolChain::AddClangCXXStdlibIncludeArgs(
2514 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2515 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2516 DriverArgs.hasArg(options::OPT_nostdincxx))
2519 assert((GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) &&
2520 "Only -lc++ (aka libcxx) is suported in this toolchain.");
2522 const auto &Callback = Multilibs.includeDirsCallback();
2524 const auto IncludePaths = Callback(getDriver().getInstalledDir(),
2525 getTripleString(), SelectedMultilib);
2526 for (const auto &Path : IncludePaths) {
2527 if (llvm::sys::fs::exists(Path + "/c++/v1")) {
2528 addSystemInclude(DriverArgs, CC1Args, Path + "/c++/v1");
2535 void MipsLLVMToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
2536 ArgStringList &CmdArgs) const {
2537 assert((GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) &&
2538 "Only -lc++ (aka libxx) is suported in this toolchain.");
2540 CmdArgs.push_back("-lc++");
2541 CmdArgs.push_back("-lc++abi");
2542 CmdArgs.push_back("-lunwind");
2545 std::string MipsLLVMToolChain::getCompilerRT(const ArgList &Args,
2546 StringRef Component,
2547 bool Shared) const {
2548 SmallString<128> Path(getDriver().ResourceDir);
2549 llvm::sys::path::append(Path, SelectedMultilib.osSuffix(), "lib" + LibSuffix,
2551 llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" +
2552 "mips" + (Shared ? ".so" : ".a")));
2556 /// Hexagon Toolchain
2558 std::string HexagonToolChain::getHexagonTargetDir(
2559 const std::string &InstalledDir,
2560 const SmallVectorImpl<std::string> &PrefixDirs) const {
2561 std::string InstallRelDir;
2562 const Driver &D = getDriver();
2564 // Locate the rest of the toolchain ...
2565 for (auto &I : PrefixDirs)
2566 if (D.getVFS().exists(I))
2569 if (getVFS().exists(InstallRelDir = InstalledDir + "/../target"))
2570 return InstallRelDir;
2572 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/target";
2573 if (getVFS().exists(PrefixRelDir))
2574 return PrefixRelDir;
2576 return InstallRelDir;
2580 Optional<unsigned> HexagonToolChain::getSmallDataThreshold(
2581 const ArgList &Args) {
2583 if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ,
2584 options::OPT_msmall_data_threshold_EQ)) {
2586 } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2587 options::OPT_fPIC)) {
2592 if (!Gn.getAsInteger(10, G))
2599 void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args,
2600 ToolChain::path_list &LibPaths) const {
2601 const Driver &D = getDriver();
2603 //----------------------------------------------------------------------------
2605 //----------------------------------------------------------------------------
2606 for (Arg *A : Args.filtered(options::OPT_L))
2607 for (const char *Value : A->getValues())
2608 LibPaths.push_back(Value);
2610 //----------------------------------------------------------------------------
2611 // Other standard paths
2612 //----------------------------------------------------------------------------
2613 std::vector<std::string> RootDirs;
2614 std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(),
2615 std::back_inserter(RootDirs));
2617 std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2619 if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end())
2620 RootDirs.push_back(TargetDir);
2622 bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC);
2623 // Assume G0 with -shared.
2624 bool HasG0 = Args.hasArg(options::OPT_shared);
2625 if (auto G = getSmallDataThreshold(Args))
2626 HasG0 = G.getValue() == 0;
2628 const std::string CpuVer = GetTargetCPUVersion(Args).str();
2629 for (auto &Dir : RootDirs) {
2630 std::string LibDir = Dir + "/hexagon/lib";
2631 std::string LibDirCpu = LibDir + '/' + CpuVer;
2634 LibPaths.push_back(LibDirCpu + "/G0/pic");
2635 LibPaths.push_back(LibDirCpu + "/G0");
2637 LibPaths.push_back(LibDirCpu);
2638 LibPaths.push_back(LibDir);
2642 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple,
2643 const llvm::opt::ArgList &Args)
2644 : Linux(D, Triple, Args) {
2645 const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2648 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to
2650 const std::string BinDir(TargetDir + "/bin");
2651 if (D.getVFS().exists(BinDir))
2652 getProgramPaths().push_back(BinDir);
2654 ToolChain::path_list &LibPaths = getFilePaths();
2656 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets
2657 // 'elf' OS type, so the Linux paths are not appropriate. When we actually
2658 // support 'linux' we'll need to fix this up
2660 getHexagonLibraryPaths(Args, LibPaths);
2663 HexagonToolChain::~HexagonToolChain() {}
2665 Tool *HexagonToolChain::buildAssembler() const {
2666 return new tools::hexagon::Assembler(*this);
2669 Tool *HexagonToolChain::buildLinker() const {
2670 return new tools::hexagon::Linker(*this);
2673 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2674 ArgStringList &CC1Args) const {
2675 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
2676 DriverArgs.hasArg(options::OPT_nostdlibinc))
2679 const Driver &D = getDriver();
2680 std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(),
2682 addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include");
2685 void HexagonToolChain::AddClangCXXStdlibIncludeArgs(
2686 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
2687 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2688 DriverArgs.hasArg(options::OPT_nostdincxx))
2691 const Driver &D = getDriver();
2692 std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs);
2693 addSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include/c++");
2696 ToolChain::CXXStdlibType
2697 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const {
2698 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
2700 return ToolChain::CST_Libstdcxx;
2702 StringRef Value = A->getValue();
2703 if (Value != "libstdc++")
2704 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2706 return ToolChain::CST_Libstdcxx;
2710 // Returns the default CPU for Hexagon. This is the default compilation target
2711 // if no Hexagon processor is selected at the command-line.
2713 const StringRef HexagonToolChain::GetDefaultCPU() {
2714 return "hexagonv60";
2717 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) {
2718 Arg *CpuArg = nullptr;
2720 for (auto &A : Args) {
2721 if (A->getOption().matches(options::OPT_mcpu_EQ)) {
2727 StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU();
2728 if (CPU.startswith("hexagon"))
2729 return CPU.substr(sizeof("hexagon") - 1);
2734 /// AMDGPU Toolchain
2735 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
2736 const ArgList &Args)
2737 : Generic_ELF(D, Triple, Args) { }
2739 Tool *AMDGPUToolChain::buildLinker() const {
2740 return new tools::amdgpu::Linker(*this);
2745 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple,
2746 const ArgList &Args)
2747 : Generic_ELF(D, Triple, Args) {
2749 // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the
2750 // default paths, and must instead only use the paths provided
2751 // with this toolchain based on architecture.
2752 path_list &file_paths = getFilePaths();
2753 path_list &prog_paths = getProgramPaths();
2758 // Path for library files (libc.a, ...)
2759 std::string FilePath(getDriver().Dir + "/../");
2761 // Path for tools (clang, ld, etc..)
2762 std::string ProgPath(getDriver().Dir + "/../");
2764 // Path for toolchain libraries (libgcc.a, ...)
2765 std::string ToolPath(getDriver().ResourceDir + "/lib/");
2767 switch (Triple.getArch()) {
2768 case llvm::Triple::x86:
2769 file_paths.push_back(FilePath + "x86_64-nacl/lib32");
2770 file_paths.push_back(FilePath + "i686-nacl/usr/lib");
2771 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2772 file_paths.push_back(ToolPath + "i686-nacl");
2774 case llvm::Triple::x86_64:
2775 file_paths.push_back(FilePath + "x86_64-nacl/lib");
2776 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib");
2777 prog_paths.push_back(ProgPath + "x86_64-nacl/bin");
2778 file_paths.push_back(ToolPath + "x86_64-nacl");
2780 case llvm::Triple::arm:
2781 file_paths.push_back(FilePath + "arm-nacl/lib");
2782 file_paths.push_back(FilePath + "arm-nacl/usr/lib");
2783 prog_paths.push_back(ProgPath + "arm-nacl/bin");
2784 file_paths.push_back(ToolPath + "arm-nacl");
2786 case llvm::Triple::mipsel:
2787 file_paths.push_back(FilePath + "mipsel-nacl/lib");
2788 file_paths.push_back(FilePath + "mipsel-nacl/usr/lib");
2789 prog_paths.push_back(ProgPath + "bin");
2790 file_paths.push_back(ToolPath + "mipsel-nacl");
2796 NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s");
2799 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
2800 ArgStringList &CC1Args) const {
2801 const Driver &D = getDriver();
2802 if (DriverArgs.hasArg(options::OPT_nostdinc))
2805 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
2806 SmallString<128> P(D.ResourceDir);
2807 llvm::sys::path::append(P, "include");
2808 addSystemInclude(DriverArgs, CC1Args, P.str());
2811 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
2814 SmallString<128> P(D.Dir + "/../");
2815 switch (getTriple().getArch()) {
2816 case llvm::Triple::x86:
2817 // x86 is special because multilib style uses x86_64-nacl/include for libc
2818 // headers but the SDK wants i686-nacl/usr/include. The other architectures
2819 // have the same substring.
2820 llvm::sys::path::append(P, "i686-nacl/usr/include");
2821 addSystemInclude(DriverArgs, CC1Args, P.str());
2822 llvm::sys::path::remove_filename(P);
2823 llvm::sys::path::remove_filename(P);
2824 llvm::sys::path::remove_filename(P);
2825 llvm::sys::path::append(P, "x86_64-nacl/include");
2826 addSystemInclude(DriverArgs, CC1Args, P.str());
2828 case llvm::Triple::arm:
2829 llvm::sys::path::append(P, "arm-nacl/usr/include");
2831 case llvm::Triple::x86_64:
2832 llvm::sys::path::append(P, "x86_64-nacl/usr/include");
2834 case llvm::Triple::mipsel:
2835 llvm::sys::path::append(P, "mipsel-nacl/usr/include");
2841 addSystemInclude(DriverArgs, CC1Args, P.str());
2842 llvm::sys::path::remove_filename(P);
2843 llvm::sys::path::remove_filename(P);
2844 llvm::sys::path::append(P, "include");
2845 addSystemInclude(DriverArgs, CC1Args, P.str());
2848 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
2849 ArgStringList &CmdArgs) const {
2850 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2851 // if the value is libc++, and emits an error for other values.
2852 GetCXXStdlibType(Args);
2853 CmdArgs.push_back("-lc++");
2856 void NaClToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2857 ArgStringList &CC1Args) const {
2858 const Driver &D = getDriver();
2859 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
2860 DriverArgs.hasArg(options::OPT_nostdincxx))
2863 // Check for -stdlib= flags. We only support libc++ but this consumes the arg
2864 // if the value is libc++, and emits an error for other values.
2865 GetCXXStdlibType(DriverArgs);
2867 SmallString<128> P(D.Dir + "/../");
2868 switch (getTriple().getArch()) {
2869 case llvm::Triple::arm:
2870 llvm::sys::path::append(P, "arm-nacl/include/c++/v1");
2871 addSystemInclude(DriverArgs, CC1Args, P.str());
2873 case llvm::Triple::x86:
2874 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2875 addSystemInclude(DriverArgs, CC1Args, P.str());
2877 case llvm::Triple::x86_64:
2878 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1");
2879 addSystemInclude(DriverArgs, CC1Args, P.str());
2881 case llvm::Triple::mipsel:
2882 llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1");
2883 addSystemInclude(DriverArgs, CC1Args, P.str());
2890 ToolChain::CXXStdlibType
2891 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const {
2892 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
2893 StringRef Value = A->getValue();
2894 if (Value == "libc++")
2895 return ToolChain::CST_Libcxx;
2896 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
2899 return ToolChain::CST_Libcxx;
2903 NaClToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
2904 types::ID InputType) const {
2905 llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType));
2906 if (TheTriple.getArch() == llvm::Triple::arm &&
2907 TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment)
2908 TheTriple.setEnvironment(llvm::Triple::GNUEABIHF);
2909 return TheTriple.getTriple();
2912 Tool *NaClToolChain::buildLinker() const {
2913 return new tools::nacltools::Linker(*this);
2916 Tool *NaClToolChain::buildAssembler() const {
2917 if (getTriple().getArch() == llvm::Triple::arm)
2918 return new tools::nacltools::AssemblerARM(*this);
2919 return new tools::gnutools::Assembler(*this);
2923 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
2924 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
2925 /// Currently does not support anything else but compilation.
2927 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple,
2928 const ArgList &Args)
2929 : ToolChain(D, Triple, Args) {
2930 // Path mangling to find libexec
2931 std::string Path(getDriver().Dir);
2933 Path += "/../libexec";
2934 getProgramPaths().push_back(Path);
2937 TCEToolChain::~TCEToolChain() {}
2939 bool TCEToolChain::IsMathErrnoDefault() const { return true; }
2941 bool TCEToolChain::isPICDefault() const { return false; }
2943 bool TCEToolChain::isPIEDefault() const { return false; }
2945 bool TCEToolChain::isPICDefaultForced() const { return false; }
2947 // CloudABI - CloudABI tool chain which can call ld(1) directly.
2949 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple,
2950 const ArgList &Args)
2951 : Generic_ELF(D, Triple, Args) {
2952 SmallString<128> P(getDriver().Dir);
2953 llvm::sys::path::append(P, "..", getTriple().str(), "lib");
2954 getFilePaths().push_back(P.str());
2957 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
2958 ArgStringList &CC1Args) const {
2959 if (DriverArgs.hasArg(options::OPT_nostdlibinc) &&
2960 DriverArgs.hasArg(options::OPT_nostdincxx))
2963 SmallString<128> P(getDriver().Dir);
2964 llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1");
2965 addSystemInclude(DriverArgs, CC1Args, P.str());
2968 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args,
2969 ArgStringList &CmdArgs) const {
2970 CmdArgs.push_back("-lc++");
2971 CmdArgs.push_back("-lc++abi");
2972 CmdArgs.push_back("-lunwind");
2975 Tool *CloudABI::buildLinker() const {
2976 return new tools::cloudabi::Linker(*this);
2979 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
2981 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
2982 const ArgList &Args)
2983 : Generic_ELF(D, Triple, Args) {
2984 getFilePaths().push_back(getDriver().Dir + "/../lib");
2985 getFilePaths().push_back("/usr/lib");
2988 Tool *OpenBSD::buildAssembler() const {
2989 return new tools::openbsd::Assembler(*this);
2992 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
2994 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly.
2996 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
2997 : Generic_ELF(D, Triple, Args) {
2998 getFilePaths().push_back(getDriver().Dir + "/../lib");
2999 getFilePaths().push_back("/usr/lib");
3002 Tool *Bitrig::buildAssembler() const {
3003 return new tools::bitrig::Assembler(*this);
3006 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); }
3008 ToolChain::CXXStdlibType Bitrig::GetCXXStdlibType(const ArgList &Args) const {
3009 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3010 StringRef Value = A->getValue();
3011 if (Value == "libstdc++")
3012 return ToolChain::CST_Libstdcxx;
3013 if (Value == "libc++")
3014 return ToolChain::CST_Libcxx;
3016 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3018 return ToolChain::CST_Libcxx;
3021 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3022 ArgStringList &CC1Args) const {
3023 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3024 DriverArgs.hasArg(options::OPT_nostdincxx))
3027 switch (GetCXXStdlibType(DriverArgs)) {
3028 case ToolChain::CST_Libcxx:
3029 addSystemInclude(DriverArgs, CC1Args,
3030 getDriver().SysRoot + "/usr/include/c++/v1");
3032 case ToolChain::CST_Libstdcxx:
3033 addSystemInclude(DriverArgs, CC1Args,
3034 getDriver().SysRoot + "/usr/include/c++/stdc++");
3035 addSystemInclude(DriverArgs, CC1Args,
3036 getDriver().SysRoot + "/usr/include/c++/stdc++/backward");
3038 StringRef Triple = getTriple().str();
3039 if (Triple.startswith("amd64"))
3040 addSystemInclude(DriverArgs, CC1Args,
3041 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" +
3044 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot +
3045 "/usr/include/c++/stdc++/" +
3051 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args,
3052 ArgStringList &CmdArgs) const {
3053 switch (GetCXXStdlibType(Args)) {
3054 case ToolChain::CST_Libcxx:
3055 CmdArgs.push_back("-lc++");
3056 CmdArgs.push_back("-lc++abi");
3057 CmdArgs.push_back("-lpthread");
3059 case ToolChain::CST_Libstdcxx:
3060 CmdArgs.push_back("-lstdc++");
3065 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
3067 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
3068 const ArgList &Args)
3069 : Generic_ELF(D, Triple, Args) {
3071 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
3072 // back to '/usr/lib' if it doesn't exist.
3073 if ((Triple.getArch() == llvm::Triple::x86 ||
3074 Triple.getArch() == llvm::Triple::ppc) &&
3075 D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o"))
3076 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32");
3078 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib");
3081 ToolChain::CXXStdlibType FreeBSD::GetCXXStdlibType(const ArgList &Args) const {
3082 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3083 StringRef Value = A->getValue();
3084 if (Value == "libstdc++")
3085 return ToolChain::CST_Libstdcxx;
3086 if (Value == "libc++")
3087 return ToolChain::CST_Libcxx;
3089 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3091 if (getTriple().getOSMajorVersion() >= 10)
3092 return ToolChain::CST_Libcxx;
3093 return ToolChain::CST_Libstdcxx;
3096 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3097 ArgStringList &CC1Args) const {
3098 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3099 DriverArgs.hasArg(options::OPT_nostdincxx))
3102 switch (GetCXXStdlibType(DriverArgs)) {
3103 case ToolChain::CST_Libcxx:
3104 addSystemInclude(DriverArgs, CC1Args,
3105 getDriver().SysRoot + "/usr/include/c++/v1");
3107 case ToolChain::CST_Libstdcxx:
3108 addSystemInclude(DriverArgs, CC1Args,
3109 getDriver().SysRoot + "/usr/include/c++/4.2");
3110 addSystemInclude(DriverArgs, CC1Args,
3111 getDriver().SysRoot + "/usr/include/c++/4.2/backward");
3116 Tool *FreeBSD::buildAssembler() const {
3117 return new tools::freebsd::Assembler(*this);
3120 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
3122 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const {
3123 // FreeBSD uses SjLj exceptions on ARM oabi.
3124 switch (getTriple().getEnvironment()) {
3125 case llvm::Triple::GNUEABIHF:
3126 case llvm::Triple::GNUEABI:
3127 case llvm::Triple::EABI:
3131 return (getTriple().getArch() == llvm::Triple::arm ||
3132 getTriple().getArch() == llvm::Triple::thumb);
3136 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
3138 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
3140 SanitizerMask FreeBSD::getSupportedSanitizers() const {
3141 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
3142 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3143 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
3144 getTriple().getArch() == llvm::Triple::mips64el;
3145 SanitizerMask Res = ToolChain::getSupportedSanitizers();
3146 Res |= SanitizerKind::Address;
3147 Res |= SanitizerKind::Vptr;
3148 if (IsX86_64 || IsMIPS64) {
3149 Res |= SanitizerKind::Leak;
3150 Res |= SanitizerKind::Thread;
3152 if (IsX86 || IsX86_64) {
3153 Res |= SanitizerKind::SafeStack;
3158 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
3160 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3161 : Generic_ELF(D, Triple, Args) {
3163 if (getDriver().UseStdLib) {
3164 // When targeting a 32-bit platform, try the special directory used on
3165 // 64-bit hosts, and only fall back to the main library directory if that
3167 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure
3168 // what all logic is needed to emulate the '=' prefix here.
3169 switch (Triple.getArch()) {
3170 case llvm::Triple::x86:
3171 getFilePaths().push_back("=/usr/lib/i386");
3173 case llvm::Triple::arm:
3174 case llvm::Triple::armeb:
3175 case llvm::Triple::thumb:
3176 case llvm::Triple::thumbeb:
3177 switch (Triple.getEnvironment()) {
3178 case llvm::Triple::EABI:
3179 case llvm::Triple::GNUEABI:
3180 getFilePaths().push_back("=/usr/lib/eabi");
3182 case llvm::Triple::EABIHF:
3183 case llvm::Triple::GNUEABIHF:
3184 getFilePaths().push_back("=/usr/lib/eabihf");
3187 getFilePaths().push_back("=/usr/lib/oabi");
3191 case llvm::Triple::mips64:
3192 case llvm::Triple::mips64el:
3193 if (tools::mips::hasMipsAbiArg(Args, "o32"))
3194 getFilePaths().push_back("=/usr/lib/o32");
3195 else if (tools::mips::hasMipsAbiArg(Args, "64"))
3196 getFilePaths().push_back("=/usr/lib/64");
3198 case llvm::Triple::ppc:
3199 getFilePaths().push_back("=/usr/lib/powerpc");
3201 case llvm::Triple::sparc:
3202 getFilePaths().push_back("=/usr/lib/sparc");
3208 getFilePaths().push_back("=/usr/lib");
3212 Tool *NetBSD::buildAssembler() const {
3213 return new tools::netbsd::Assembler(*this);
3216 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); }
3218 ToolChain::CXXStdlibType NetBSD::GetCXXStdlibType(const ArgList &Args) const {
3219 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
3220 StringRef Value = A->getValue();
3221 if (Value == "libstdc++")
3222 return ToolChain::CST_Libstdcxx;
3223 if (Value == "libc++")
3224 return ToolChain::CST_Libcxx;
3226 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
3229 unsigned Major, Minor, Micro;
3230 getTriple().getOSVersion(Major, Minor, Micro);
3231 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
3232 switch (getArch()) {
3233 case llvm::Triple::aarch64:
3234 case llvm::Triple::arm:
3235 case llvm::Triple::armeb:
3236 case llvm::Triple::thumb:
3237 case llvm::Triple::thumbeb:
3238 case llvm::Triple::ppc:
3239 case llvm::Triple::ppc64:
3240 case llvm::Triple::ppc64le:
3241 case llvm::Triple::x86:
3242 case llvm::Triple::x86_64:
3243 return ToolChain::CST_Libcxx;
3248 return ToolChain::CST_Libstdcxx;
3251 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3252 ArgStringList &CC1Args) const {
3253 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3254 DriverArgs.hasArg(options::OPT_nostdincxx))
3257 switch (GetCXXStdlibType(DriverArgs)) {
3258 case ToolChain::CST_Libcxx:
3259 addSystemInclude(DriverArgs, CC1Args,
3260 getDriver().SysRoot + "/usr/include/c++/");
3262 case ToolChain::CST_Libstdcxx:
3263 addSystemInclude(DriverArgs, CC1Args,
3264 getDriver().SysRoot + "/usr/include/g++");
3265 addSystemInclude(DriverArgs, CC1Args,
3266 getDriver().SysRoot + "/usr/include/g++/backward");
3271 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
3273 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3274 : Generic_ELF(D, Triple, Args) {
3275 getFilePaths().push_back(getDriver().Dir + "/../lib");
3276 getFilePaths().push_back("/usr/lib");
3279 Tool *Minix::buildAssembler() const {
3280 return new tools::minix::Assembler(*this);
3283 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); }
3285 static void addPathIfExists(const Driver &D, const Twine &Path,
3286 ToolChain::path_list &Paths) {
3287 if (D.getVFS().exists(Path))
3288 Paths.push_back(Path.str());
3291 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
3293 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
3294 const ArgList &Args)
3295 : Generic_GCC(D, Triple, Args) {
3297 GCCInstallation.init(Triple, Args);
3299 path_list &Paths = getFilePaths();
3300 if (GCCInstallation.isValid())
3301 addPathIfExists(D, GCCInstallation.getInstallPath(), Paths);
3303 addPathIfExists(D, getDriver().getInstalledDir(), Paths);
3304 if (getDriver().getInstalledDir() != getDriver().Dir)
3305 addPathIfExists(D, getDriver().Dir, Paths);
3307 addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths);
3309 std::string LibPath = "/usr/lib/";
3310 switch (Triple.getArch()) {
3311 case llvm::Triple::x86:
3312 case llvm::Triple::sparc:
3314 case llvm::Triple::x86_64:
3315 LibPath += "amd64/";
3317 case llvm::Triple::sparcv9:
3318 LibPath += "sparcv9/";
3321 llvm_unreachable("Unsupported architecture");
3324 addPathIfExists(D, getDriver().SysRoot + LibPath, Paths);
3327 Tool *Solaris::buildAssembler() const {
3328 return new tools::solaris::Assembler(*this);
3331 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
3333 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
3334 ArgStringList &CC1Args) const {
3335 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
3336 DriverArgs.hasArg(options::OPT_nostdincxx))
3339 // Include the support directory for things like xlocale and fudged system
3341 addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris");
3343 if (GCCInstallation.isValid()) {
3344 GCCVersion Version = GCCInstallation.getVersion();
3345 addSystemInclude(DriverArgs, CC1Args,
3346 getDriver().SysRoot + "/usr/gcc/" +
3347 Version.MajorStr + "." +
3349 "/include/c++/" + Version.Text);
3350 addSystemInclude(DriverArgs, CC1Args,
3351 getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr +
3352 "." + Version.MinorStr + "/include/c++/" +
3353 Version.Text + "/" +
3354 GCCInstallation.getTriple().str());
3358 /// Distribution (very bare-bones at the moment).
3361 // NB: Releases of a particular Linux distro should be kept together
3362 // in this enum, because some tests are done by integer comparison against
3363 // the first and last known member in the family, e.g. IsRedHat().
3397 static bool IsRedhat(enum Distro Distro) {
3398 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7);
3401 static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; }
3403 static bool IsDebian(enum Distro Distro) {
3404 return Distro >= DebianLenny && Distro <= DebianStretch;
3407 static bool IsUbuntu(enum Distro Distro) {
3408 return Distro >= UbuntuHardy && Distro <= UbuntuXenial;
3411 static Distro DetectDistro(const Driver &D, llvm::Triple::ArchType Arch) {
3412 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
3413 llvm::MemoryBuffer::getFile("/etc/lsb-release");
3415 StringRef Data = File.get()->getBuffer();
3416 SmallVector<StringRef, 16> Lines;
3417 Data.split(Lines, "\n");
3418 Distro Version = UnknownDistro;
3419 for (StringRef Line : Lines)
3420 if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
3421 Version = llvm::StringSwitch<Distro>(Line.substr(17))
3422 .Case("hardy", UbuntuHardy)
3423 .Case("intrepid", UbuntuIntrepid)
3424 .Case("jaunty", UbuntuJaunty)
3425 .Case("karmic", UbuntuKarmic)
3426 .Case("lucid", UbuntuLucid)
3427 .Case("maverick", UbuntuMaverick)
3428 .Case("natty", UbuntuNatty)
3429 .Case("oneiric", UbuntuOneiric)
3430 .Case("precise", UbuntuPrecise)
3431 .Case("quantal", UbuntuQuantal)
3432 .Case("raring", UbuntuRaring)
3433 .Case("saucy", UbuntuSaucy)
3434 .Case("trusty", UbuntuTrusty)
3435 .Case("utopic", UbuntuUtopic)
3436 .Case("vivid", UbuntuVivid)
3437 .Case("wily", UbuntuWily)
3438 .Case("xenial", UbuntuXenial)
3439 .Default(UnknownDistro);
3443 File = llvm::MemoryBuffer::getFile("/etc/redhat-release");
3445 StringRef Data = File.get()->getBuffer();
3446 if (Data.startswith("Fedora release"))
3448 if (Data.startswith("Red Hat Enterprise Linux") ||
3449 Data.startswith("CentOS")) {
3450 if (Data.find("release 7") != StringRef::npos)
3452 else if (Data.find("release 6") != StringRef::npos)
3454 else if (Data.find("release 5") != StringRef::npos)
3456 else if (Data.find("release 4") != StringRef::npos)
3459 return UnknownDistro;
3462 File = llvm::MemoryBuffer::getFile("/etc/debian_version");
3464 StringRef Data = File.get()->getBuffer();
3467 else if (Data.startswith("squeeze/sid") || Data[0] == '6')
3468 return DebianSqueeze;
3469 else if (Data.startswith("wheezy/sid") || Data[0] == '7')
3470 return DebianWheezy;
3471 else if (Data.startswith("jessie/sid") || Data[0] == '8')
3472 return DebianJessie;
3473 else if (Data.startswith("stretch/sid") || Data[0] == '9')
3474 return DebianStretch;
3475 return UnknownDistro;
3478 if (D.getVFS().exists("/etc/SuSE-release"))
3481 if (D.getVFS().exists("/etc/exherbo-release"))
3484 if (D.getVFS().exists("/etc/arch-release"))
3487 return UnknownDistro;
3490 /// \brief Get our best guess at the multiarch triple for a target.
3492 /// Debian-based systems are starting to use a multiarch setup where they use
3493 /// a target-triple directory in the library and header search paths.
3494 /// Unfortunately, this triple does not align with the vanilla target triple,
3495 /// so we provide a rough mapping here.
3496 static std::string getMultiarchTriple(const Driver &D,
3497 const llvm::Triple &TargetTriple,
3498 StringRef SysRoot) {
3499 llvm::Triple::EnvironmentType TargetEnvironment =
3500 TargetTriple.getEnvironment();
3502 // For most architectures, just use whatever we have rather than trying to be
3504 switch (TargetTriple.getArch()) {
3508 // We use the existence of '/lib/<triple>' as a directory to detect some
3509 // common linux triples that don't quite match the Clang triple for both
3510 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
3511 // regardless of what the actual target triple is.
3512 case llvm::Triple::arm:
3513 case llvm::Triple::thumb:
3514 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3515 if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
3516 return "arm-linux-gnueabihf";
3518 if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
3519 return "arm-linux-gnueabi";
3522 case llvm::Triple::armeb:
3523 case llvm::Triple::thumbeb:
3524 if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
3525 if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
3526 return "armeb-linux-gnueabihf";
3528 if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
3529 return "armeb-linux-gnueabi";
3532 case llvm::Triple::x86:
3533 if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
3534 return "i386-linux-gnu";
3536 case llvm::Triple::x86_64:
3537 // We don't want this for x32, otherwise it will match x86_64 libs
3538 if (TargetEnvironment != llvm::Triple::GNUX32 &&
3539 D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
3540 return "x86_64-linux-gnu";
3542 case llvm::Triple::aarch64:
3543 if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
3544 return "aarch64-linux-gnu";
3546 case llvm::Triple::aarch64_be:
3547 if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
3548 return "aarch64_be-linux-gnu";
3550 case llvm::Triple::mips:
3551 if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu"))
3552 return "mips-linux-gnu";
3554 case llvm::Triple::mipsel:
3555 if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu"))
3556 return "mipsel-linux-gnu";
3558 case llvm::Triple::mips64:
3559 if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
3560 return "mips64-linux-gnu";
3561 if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64"))
3562 return "mips64-linux-gnuabi64";
3564 case llvm::Triple::mips64el:
3565 if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
3566 return "mips64el-linux-gnu";
3567 if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64"))
3568 return "mips64el-linux-gnuabi64";
3570 case llvm::Triple::ppc:
3571 if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
3572 return "powerpc-linux-gnuspe";
3573 if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
3574 return "powerpc-linux-gnu";
3576 case llvm::Triple::ppc64:
3577 if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
3578 return "powerpc64-linux-gnu";
3580 case llvm::Triple::ppc64le:
3581 if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
3582 return "powerpc64le-linux-gnu";
3584 case llvm::Triple::sparc:
3585 if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
3586 return "sparc-linux-gnu";
3588 case llvm::Triple::sparcv9:
3589 if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
3590 return "sparc64-linux-gnu";
3592 case llvm::Triple::systemz:
3593 if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
3594 return "s390x-linux-gnu";
3597 return TargetTriple.str();
3600 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
3601 if (isMipsArch(Triple.getArch())) {
3602 // lib32 directory has a special meaning on MIPS targets.
3603 // It contains N32 ABI binaries. Use this folder if produce
3604 // code for N32 ABI only.
3605 if (tools::mips::hasMipsAbiArg(Args, "n32"))
3607 return Triple.isArch32Bit() ? "lib" : "lib64";
3610 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and
3611 // using that variant while targeting other architectures causes problems
3612 // because the libraries are laid out in shared system roots that can't cope
3613 // with a 'lib32' library search path being considered. So we only enable
3614 // them when we know we may need it.
3616 // FIXME: This is a bit of a hack. We should really unify this code for
3617 // reasoning about oslibdir spellings with the lib dir spellings in the
3618 // GCCInstallationDetector, but that is a more significant refactoring.
3619 if (Triple.getArch() == llvm::Triple::x86 ||
3620 Triple.getArch() == llvm::Triple::ppc)
3623 if (Triple.getArch() == llvm::Triple::x86_64 &&
3624 Triple.getEnvironment() == llvm::Triple::GNUX32)
3627 return Triple.isArch32Bit() ? "lib" : "lib64";
3630 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
3631 : Generic_ELF(D, Triple, Args) {
3632 GCCInstallation.init(Triple, Args);
3633 CudaInstallation.init(Triple, Args);
3634 Multilibs = GCCInstallation.getMultilibs();
3635 llvm::Triple::ArchType Arch = Triple.getArch();
3636 std::string SysRoot = computeSysRoot();
3638 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
3639 // least) put various tools in a triple-prefixed directory off of the parent
3640 // of the GCC installation. We use the GCC triple here to ensure that we end
3641 // up with tools that support the same amount of cross compiling as the
3642 // detected GCC installation. For example, if we find a GCC installation
3643 // targeting x86_64, but it is a bi-arch GCC installation, it can also be
3644 // used to target i386.
3645 // FIXME: This seems unlikely to be Linux-specific.
3646 ToolChain::path_list &PPaths = getProgramPaths();
3647 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
3648 GCCInstallation.getTriple().str() + "/bin")
3651 Distro Distro = DetectDistro(D, Arch);
3653 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) {
3654 ExtraOpts.push_back("-z");
3655 ExtraOpts.push_back("relro");
3658 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
3659 ExtraOpts.push_back("-X");
3661 const bool IsAndroid = Triple.isAndroid();
3662 const bool IsMips = isMipsArch(Arch);
3664 if (IsMips && !SysRoot.empty())
3665 ExtraOpts.push_back("--sysroot=" + SysRoot);
3667 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
3668 // and the MIPS ABI require .dynsym to be sorted in different ways.
3669 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
3670 // ABI requires a mapping between the GOT and the symbol table.
3671 // Android loader does not support .gnu.hash.
3672 if (!IsMips && !IsAndroid) {
3673 if (IsRedhat(Distro) || IsOpenSUSE(Distro) ||
3674 (IsUbuntu(Distro) && Distro >= UbuntuMaverick))
3675 ExtraOpts.push_back("--hash-style=gnu");
3677 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid ||
3678 Distro == UbuntuJaunty || Distro == UbuntuKarmic)
3679 ExtraOpts.push_back("--hash-style=both");
3682 if (IsRedhat(Distro))
3683 ExtraOpts.push_back("--no-add-needed");
3685 if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) ||
3686 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) ||
3687 (IsUbuntu(Distro) && Distro >= UbuntuKarmic))
3688 ExtraOpts.push_back("--build-id");
3690 if (IsOpenSUSE(Distro))
3691 ExtraOpts.push_back("--enable-new-dtags");
3693 // The selection of paths to try here is designed to match the patterns which
3694 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
3695 // This was determined by running GCC in a fake filesystem, creating all
3696 // possible permutations of these directories, and seeing which ones it added
3697 // to the link paths.
3698 path_list &Paths = getFilePaths();
3700 const std::string OSLibDir = getOSLibDir(Triple, Args);
3701 const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
3703 // Add the multilib suffixed paths where they are available.
3704 if (GCCInstallation.isValid()) {
3705 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3706 const std::string &LibPath = GCCInstallation.getParentLibPath();
3707 const Multilib &Multilib = GCCInstallation.getMultilib();
3709 // Sourcery CodeBench MIPS toolchain holds some libraries under
3710 // a biarch-like suffix of the GCC installation.
3711 addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(),
3714 // GCC cross compiling toolchains will install target libraries which ship
3715 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
3716 // any part of the GCC installation in
3717 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
3718 // debatable, but is the reality today. We need to search this tree even
3719 // when we have a sysroot somewhere else. It is the responsibility of
3720 // whomever is doing the cross build targeting a sysroot using a GCC
3721 // installation that is *not* within the system root to ensure two things:
3723 // 1) Any DSOs that are linked in from this tree or from the install path
3724 // above must be present on the system root and found via an
3725 // appropriate rpath.
3726 // 2) There must not be libraries installed into
3727 // <prefix>/<triple>/<libdir> unless they should be preferred over
3728 // those within the system root.
3730 // Note that this matches the GCC behavior. See the below comment for where
3731 // Clang diverges from GCC's behavior.
3732 addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
3733 OSLibDir + Multilib.osSuffix(),
3736 // If the GCC installation we found is inside of the sysroot, we want to
3737 // prefer libraries installed in the parent prefix of the GCC installation.
3738 // It is important to *not* use these paths when the GCC installation is
3739 // outside of the system root as that can pick up unintended libraries.
3740 // This usually happens when there is an external cross compiler on the
3741 // host system, and a more minimal sysroot available that is the target of
3742 // the cross. Note that GCC does include some of these directories in some
3743 // configurations but this seems somewhere between questionable and simply
3745 if (StringRef(LibPath).startswith(SysRoot)) {
3746 addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
3747 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
3751 // Similar to the logic for GCC above, if we currently running Clang inside
3752 // of the requested system root, add its parent library paths to
3754 // FIXME: It's not clear whether we should use the driver's installed
3755 // directory ('Dir' below) or the ResourceDir.
3756 if (StringRef(D.Dir).startswith(SysRoot)) {
3757 addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
3758 addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
3761 addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
3762 addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
3763 addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
3764 addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
3766 // Try walking via the GCC triple path in case of biarch or multiarch GCC
3767 // installations with strange symlinks.
3768 if (GCCInstallation.isValid()) {
3770 SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
3771 "/../../" + OSLibDir,
3774 // Add the 'other' biarch variant path
3775 Multilib BiarchSibling;
3776 if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
3777 addPathIfExists(D, GCCInstallation.getInstallPath() +
3778 BiarchSibling.gccSuffix(),
3782 // See comments above on the multilib variant for details of why this is
3783 // included even from outside the sysroot.
3784 const std::string &LibPath = GCCInstallation.getParentLibPath();
3785 const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
3786 const Multilib &Multilib = GCCInstallation.getMultilib();
3787 addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
3788 Multilib.osSuffix(),
3791 // See comments above on the multilib variant for details of why this is
3792 // only included from within the sysroot.
3793 if (StringRef(LibPath).startswith(SysRoot))
3794 addPathIfExists(D, LibPath, Paths);
3797 // Similar to the logic for GCC above, if we are currently running Clang
3798 // inside of the requested system root, add its parent library path to those
3800 // FIXME: It's not clear whether we should use the driver's installed
3801 // directory ('Dir' below) or the ResourceDir.
3802 if (StringRef(D.Dir).startswith(SysRoot))
3803 addPathIfExists(D, D.Dir + "/../lib", Paths);
3805 addPathIfExists(D, SysRoot + "/lib", Paths);
3806 addPathIfExists(D, SysRoot + "/usr/lib", Paths);
3809 bool Linux::HasNativeLLVMSupport() const { return true; }
3811 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
3813 Tool *Linux::buildAssembler() const {
3814 return new tools::gnutools::Assembler(*this);
3817 std::string Linux::computeSysRoot() const {
3818 if (!getDriver().SysRoot.empty())
3819 return getDriver().SysRoot;
3821 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
3822 return std::string();
3824 // Standalone MIPS toolchains use different names for sysroot folder
3825 // and put it into different places. Here we try to check some known
3828 const StringRef InstallDir = GCCInstallation.getInstallPath();
3829 const StringRef TripleStr = GCCInstallation.getTriple().str();
3830 const Multilib &Multilib = GCCInstallation.getMultilib();
3833 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
3836 if (getVFS().exists(Path))
3839 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
3841 if (getVFS().exists(Path))
3844 return std::string();
3847 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
3848 ArgStringList &CC1Args) const {
3849 const Driver &D = getDriver();
3850 std::string SysRoot = computeSysRoot();
3852 if (DriverArgs.hasArg(options::OPT_nostdinc))
3855 if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
3856 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
3858 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
3859 SmallString<128> P(D.ResourceDir);
3860 llvm::sys::path::append(P, "include");
3861 addSystemInclude(DriverArgs, CC1Args, P);
3864 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
3867 // Check for configure-time C include directories.
3868 StringRef CIncludeDirs(C_INCLUDE_DIRS);
3869 if (CIncludeDirs != "") {
3870 SmallVector<StringRef, 5> dirs;
3871 CIncludeDirs.split(dirs, ":");
3872 for (StringRef dir : dirs) {
3874 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
3875 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
3880 // Lacking those, try to detect the correct set of system includes for the
3883 // Add include directories specific to the selected multilib set and multilib.
3884 if (GCCInstallation.isValid()) {
3885 const auto &Callback = Multilibs.includeDirsCallback();
3887 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(),
3888 GCCInstallation.getTriple().str(),
3889 GCCInstallation.getMultilib());
3890 for (const auto &Path : IncludePaths)
3891 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path);
3895 // Implement generic Debian multiarch support.
3896 const StringRef X86_64MultiarchIncludeDirs[] = {
3897 "/usr/include/x86_64-linux-gnu",
3899 // FIXME: These are older forms of multiarch. It's not clear that they're
3900 // in use in any released version of Debian, so we should consider
3902 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
3903 const StringRef X86MultiarchIncludeDirs[] = {
3904 "/usr/include/i386-linux-gnu",
3906 // FIXME: These are older forms of multiarch. It's not clear that they're
3907 // in use in any released version of Debian, so we should consider
3909 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
3910 "/usr/include/i486-linux-gnu"};
3911 const StringRef AArch64MultiarchIncludeDirs[] = {
3912 "/usr/include/aarch64-linux-gnu"};
3913 const StringRef ARMMultiarchIncludeDirs[] = {
3914 "/usr/include/arm-linux-gnueabi"};
3915 const StringRef ARMHFMultiarchIncludeDirs[] = {
3916 "/usr/include/arm-linux-gnueabihf"};
3917 const StringRef ARMEBMultiarchIncludeDirs[] = {
3918 "/usr/include/armeb-linux-gnueabi"};
3919 const StringRef ARMEBHFMultiarchIncludeDirs[] = {
3920 "/usr/include/armeb-linux-gnueabihf"};
3921 const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
3922 const StringRef MIPSELMultiarchIncludeDirs[] = {
3923 "/usr/include/mipsel-linux-gnu"};
3924 const StringRef MIPS64MultiarchIncludeDirs[] = {
3925 "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"};
3926 const StringRef MIPS64ELMultiarchIncludeDirs[] = {
3927 "/usr/include/mips64el-linux-gnu",
3928 "/usr/include/mips64el-linux-gnuabi64"};
3929 const StringRef PPCMultiarchIncludeDirs[] = {
3930 "/usr/include/powerpc-linux-gnu"};
3931 const StringRef PPC64MultiarchIncludeDirs[] = {
3932 "/usr/include/powerpc64-linux-gnu"};
3933 const StringRef PPC64LEMultiarchIncludeDirs[] = {
3934 "/usr/include/powerpc64le-linux-gnu"};
3935 const StringRef SparcMultiarchIncludeDirs[] = {
3936 "/usr/include/sparc-linux-gnu"};
3937 const StringRef Sparc64MultiarchIncludeDirs[] = {
3938 "/usr/include/sparc64-linux-gnu"};
3939 const StringRef SYSTEMZMultiarchIncludeDirs[] = {
3940 "/usr/include/s390x-linux-gnu"};
3941 ArrayRef<StringRef> MultiarchIncludeDirs;
3942 switch (getTriple().getArch()) {
3943 case llvm::Triple::x86_64:
3944 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
3946 case llvm::Triple::x86:
3947 MultiarchIncludeDirs = X86MultiarchIncludeDirs;
3949 case llvm::Triple::aarch64:
3950 case llvm::Triple::aarch64_be:
3951 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
3953 case llvm::Triple::arm:
3954 case llvm::Triple::thumb:
3955 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3956 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
3958 MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
3960 case llvm::Triple::armeb:
3961 case llvm::Triple::thumbeb:
3962 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
3963 MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
3965 MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
3967 case llvm::Triple::mips:
3968 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
3970 case llvm::Triple::mipsel:
3971 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
3973 case llvm::Triple::mips64:
3974 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
3976 case llvm::Triple::mips64el:
3977 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
3979 case llvm::Triple::ppc:
3980 MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
3982 case llvm::Triple::ppc64:
3983 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
3985 case llvm::Triple::ppc64le:
3986 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
3988 case llvm::Triple::sparc:
3989 MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
3991 case llvm::Triple::sparcv9:
3992 MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
3994 case llvm::Triple::systemz:
3995 MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
4000 for (StringRef Dir : MultiarchIncludeDirs) {
4001 if (D.getVFS().exists(SysRoot + Dir)) {
4002 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
4007 if (getTriple().getOS() == llvm::Triple::RTEMS)
4010 // Add an include of '/include' directly. This isn't provided by default by
4011 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
4012 // add even when Clang is acting as-if it were a system compiler.
4013 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
4015 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
4019 static std::string DetectLibcxxIncludePath(StringRef base) {
4022 std::string MaxVersionString = "";
4023 for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
4024 LI = LI.increment(EC)) {
4025 StringRef VersionText = llvm::sys::path::filename(LI->path());
4027 if (VersionText[0] == 'v' &&
4028 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
4029 if (Version > MaxVersion) {
4030 MaxVersion = Version;
4031 MaxVersionString = VersionText;
4035 return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
4038 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
4039 ArgStringList &CC1Args) const {
4040 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4041 DriverArgs.hasArg(options::OPT_nostdincxx))
4044 // Check if libc++ has been enabled and provide its include paths if so.
4045 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) {
4046 const std::string LibCXXIncludePathCandidates[] = {
4047 DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
4049 // We also check the system as for a long time this is the only place
4051 // FIXME: We should really remove this. It doesn't make any sense.
4052 DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++")};
4053 for (const auto &IncludePath : LibCXXIncludePathCandidates) {
4054 if (IncludePath.empty() || !getVFS().exists(IncludePath))
4056 // Add the first candidate that exists.
4057 addSystemInclude(DriverArgs, CC1Args, IncludePath);
4063 // We need a detected GCC installation on Linux to provide libstdc++'s
4064 // headers. We handled the libc++ case above.
4065 if (!GCCInstallation.isValid())
4068 // By default, look for the C++ headers in an include directory adjacent to
4069 // the lib directory of the GCC installation. Note that this is expect to be
4070 // equivalent to '/usr/include/c++/X.Y' in almost all cases.
4071 StringRef LibDir = GCCInstallation.getParentLibPath();
4072 StringRef InstallDir = GCCInstallation.getInstallPath();
4073 StringRef TripleStr = GCCInstallation.getTriple().str();
4074 const Multilib &Multilib = GCCInstallation.getMultilib();
4075 const std::string GCCMultiarchTriple = getMultiarchTriple(
4076 getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
4077 const std::string TargetMultiarchTriple =
4078 getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
4079 const GCCVersion &Version = GCCInstallation.getVersion();
4081 // The primary search for libstdc++ supports multiarch variants.
4082 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
4083 "/c++/" + Version.Text, TripleStr,
4084 GCCMultiarchTriple, TargetMultiarchTriple,
4085 Multilib.includeSuffix(), DriverArgs, CC1Args))
4088 // Otherwise, fall back on a bunch of options which don't use multiarch
4089 // layouts for simplicity.
4090 const std::string LibStdCXXIncludePathCandidates[] = {
4091 // Gentoo is weird and places its headers inside the GCC install,
4092 // so if the first attempt to find the headers fails, try these patterns.
4093 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
4095 InstallDir.str() + "/include/g++-v" + Version.MajorStr,
4096 // Android standalone toolchain has C++ headers in yet another place.
4097 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4098 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
4099 // without a subdirectory corresponding to the gcc version.
4100 LibDir.str() + "/../include/c++",
4103 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
4104 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
4105 /*GCCMultiarchTriple*/ "",
4106 /*TargetMultiarchTriple*/ "",
4107 Multilib.includeSuffix(), DriverArgs, CC1Args))
4112 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
4113 ArgStringList &CC1Args) const {
4114 if (DriverArgs.hasArg(options::OPT_nocudainc))
4117 if (CudaInstallation.isValid()) {
4118 addSystemInclude(DriverArgs, CC1Args, CudaInstallation.getIncludePath());
4119 CC1Args.push_back("-include");
4120 CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
4124 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
4126 SanitizerMask Linux::getSupportedSanitizers() const {
4127 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
4128 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4129 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 ||
4130 getTriple().getArch() == llvm::Triple::mips64el;
4131 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
4132 getTriple().getArch() == llvm::Triple::ppc64le;
4133 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
4134 getTriple().getArch() == llvm::Triple::aarch64_be;
4135 SanitizerMask Res = ToolChain::getSupportedSanitizers();
4136 Res |= SanitizerKind::Address;
4137 Res |= SanitizerKind::KernelAddress;
4138 Res |= SanitizerKind::Vptr;
4139 Res |= SanitizerKind::SafeStack;
4140 if (IsX86_64 || IsMIPS64 || IsAArch64)
4141 Res |= SanitizerKind::DataFlow;
4142 if (IsX86_64 || IsMIPS64 || IsAArch64)
4143 Res |= SanitizerKind::Leak;
4144 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
4145 Res |= SanitizerKind::Thread;
4146 if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64)
4147 Res |= SanitizerKind::Memory;
4148 if (IsX86 || IsX86_64) {
4149 Res |= SanitizerKind::Function;
4154 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
4155 llvm::opt::ArgStringList &CmdArgs) const {
4156 if (!needsProfileRT(Args)) return;
4158 // Add linker option -u__llvm_runtime_variable to cause runtime
4159 // initialization module to be linked in.
4160 if (!Args.hasArg(options::OPT_coverage))
4161 CmdArgs.push_back(Args.MakeArgString(
4162 Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
4163 ToolChain::addProfileRTLibs(Args, CmdArgs);
4166 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
4168 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple,
4169 const ArgList &Args)
4170 : Generic_ELF(D, Triple, Args) {
4172 // Path mangling to find libexec
4173 getProgramPaths().push_back(getDriver().getInstalledDir());
4174 if (getDriver().getInstalledDir() != getDriver().Dir)
4175 getProgramPaths().push_back(getDriver().Dir);
4177 getFilePaths().push_back(getDriver().Dir + "/../lib");
4178 getFilePaths().push_back("/usr/lib");
4179 getFilePaths().push_back("/usr/lib/gcc50");
4182 Tool *DragonFly::buildAssembler() const {
4183 return new tools::dragonfly::Assembler(*this);
4186 Tool *DragonFly::buildLinker() const {
4187 return new tools::dragonfly::Linker(*this);
4190 /// Stub for CUDA toolchain. At the moment we don't have assembler or
4191 /// linker and need toolchain mainly to propagate device-side options
4194 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
4195 const ArgList &Args)
4196 : Linux(D, Triple, Args) {}
4199 CudaToolChain::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
4200 llvm::opt::ArgStringList &CC1Args) const {
4201 Linux::addClangTargetOptions(DriverArgs, CC1Args);
4202 CC1Args.push_back("-fcuda-is-device");
4204 if (DriverArgs.hasArg(options::OPT_nocudalib))
4207 std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(
4208 DriverArgs.getLastArgValue(options::OPT_march_EQ));
4209 if (!LibDeviceFile.empty()) {
4210 CC1Args.push_back("-mlink-cuda-bitcode");
4211 CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
4213 // Libdevice in CUDA-7.0 requires PTX version that's more recent
4214 // than LLVM defaults to. Use PTX4.2 which is the PTX version that
4215 // came with CUDA-7.0.
4216 CC1Args.push_back("-target-feature");
4217 CC1Args.push_back("+ptx42");
4221 llvm::opt::DerivedArgList *
4222 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
4223 const char *BoundArch) const {
4224 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
4225 const OptTable &Opts = getDriver().getOpts();
4227 for (Arg *A : Args) {
4228 if (A->getOption().matches(options::OPT_Xarch__)) {
4229 // Skip this argument unless the architecture matches BoundArch
4230 if (A->getValue(0) != StringRef(BoundArch))
4233 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
4234 unsigned Prev = Index;
4235 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
4237 // If the argument parsing failed or more than one argument was
4238 // consumed, the -Xarch_ argument's parameter tried to consume
4239 // extra arguments. Emit an error and ignore.
4241 // We also want to disallow any options which would alter the
4242 // driver behavior; that isn't going to work in our model. We
4243 // use isDriverOption() as an approximation, although things
4244 // like -O4 are going to slip through.
4245 if (!XarchArg || Index > Prev + 1) {
4246 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
4247 << A->getAsString(Args);
4249 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
4250 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
4251 << A->getAsString(Args);
4254 XarchArg->setBaseArg(A);
4255 A = XarchArg.release();
4256 DAL->AddSynthesizedArg(A);
4261 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
4265 /// XCore tool chain
4266 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple,
4267 const ArgList &Args)
4268 : ToolChain(D, Triple, Args) {
4269 // ProgramPaths are found via 'PATH' environment variable.
4272 Tool *XCoreToolChain::buildAssembler() const {
4273 return new tools::XCore::Assembler(*this);
4276 Tool *XCoreToolChain::buildLinker() const {
4277 return new tools::XCore::Linker(*this);
4280 bool XCoreToolChain::isPICDefault() const { return false; }
4282 bool XCoreToolChain::isPIEDefault() const { return false; }
4284 bool XCoreToolChain::isPICDefaultForced() const { return false; }
4286 bool XCoreToolChain::SupportsProfiling() const { return false; }
4288 bool XCoreToolChain::hasBlocksRuntime() const { return false; }
4290 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4291 ArgStringList &CC1Args) const {
4292 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
4293 DriverArgs.hasArg(options::OPT_nostdlibinc))
4295 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) {
4296 SmallVector<StringRef, 4> Dirs;
4297 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
4298 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
4299 ArrayRef<StringRef> DirVec(Dirs);
4300 addSystemIncludes(DriverArgs, CC1Args, DirVec);
4304 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs,
4305 ArgStringList &CC1Args) const {
4306 CC1Args.push_back("-nostdsysteminc");
4309 void XCoreToolChain::AddClangCXXStdlibIncludeArgs(
4310 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
4311 if (DriverArgs.hasArg(options::OPT_nostdinc) ||
4312 DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4313 DriverArgs.hasArg(options::OPT_nostdincxx))
4315 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) {
4316 SmallVector<StringRef, 4> Dirs;
4317 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
4318 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr));
4319 ArrayRef<StringRef> DirVec(Dirs);
4320 addSystemIncludes(DriverArgs, CC1Args, DirVec);
4324 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
4325 ArgStringList &CmdArgs) const {
4326 // We don't output any lib args. This is handled by xcc.
4329 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple,
4330 const ArgList &Args)
4331 : Generic_GCC(D, Triple, Args) {
4332 // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use
4333 // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple.
4334 // This won't work to find gcc. Instead we give the installation detector an
4335 // extra triple, which is preferable to further hacks of the logic that at
4336 // present is based solely on getArch(). In particular, it would be wrong to
4337 // choose the myriad installation when targeting a non-myriad sparc install.
4338 switch (Triple.getArch()) {
4340 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4342 case llvm::Triple::sparc:
4343 case llvm::Triple::sparcel:
4344 case llvm::Triple::shave:
4345 GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"});
4348 if (GCCInstallation.isValid()) {
4349 // The contents of LibDir are independent of the version of gcc.
4350 // This contains libc, libg (a superset of libc), libm, libstdc++, libssp.
4351 SmallString<128> LibDir(GCCInstallation.getParentLibPath());
4352 if (Triple.getArch() == llvm::Triple::sparcel)
4353 llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib/le");
4355 llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib");
4356 addPathIfExists(D, LibDir, getFilePaths());
4358 // This directory contains crt{i,n,begin,end}.o as well as libgcc.
4359 // These files are tied to a particular version of gcc.
4360 SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath());
4361 // There are actually 4 choices: {le,be} x {fpu,nofpu}
4362 // but as this toolchain is for LEON sparc, it can assume FPU.
4363 if (Triple.getArch() == llvm::Triple::sparcel)
4364 llvm::sys::path::append(CompilerSupportDir, "le");
4365 addPathIfExists(D, CompilerSupportDir, getFilePaths());
4369 MyriadToolChain::~MyriadToolChain() {}
4371 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
4372 ArgStringList &CC1Args) const {
4373 if (!DriverArgs.hasArg(options::OPT_nostdinc))
4374 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include");
4377 void MyriadToolChain::AddClangCXXStdlibIncludeArgs(
4378 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
4379 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
4380 DriverArgs.hasArg(options::OPT_nostdincxx))
4383 // Only libstdc++, for now.
4384 StringRef LibDir = GCCInstallation.getParentLibPath();
4385 const GCCVersion &Version = GCCInstallation.getVersion();
4386 StringRef TripleStr = GCCInstallation.getTriple().str();
4387 const Multilib &Multilib = GCCInstallation.getMultilib();
4389 addLibStdCXXIncludePaths(
4390 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
4391 "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args);
4394 // MyriadToolChain handles several triples:
4395 // {shave,sparc{,el}}-myriad-{rtems,unknown}-elf
4396 Tool *MyriadToolChain::SelectTool(const JobAction &JA) const {
4397 // The inherited method works fine if not targeting the SHAVE.
4398 if (!isShaveCompilation(getTriple()))
4399 return ToolChain::SelectTool(JA);
4400 switch (JA.getKind()) {
4401 case Action::PreprocessJobClass:
4402 case Action::CompileJobClass:
4404 Compiler.reset(new tools::SHAVE::Compiler(*this));
4405 return Compiler.get();
4406 case Action::AssembleJobClass:
4408 Assembler.reset(new tools::SHAVE::Assembler(*this));
4409 return Assembler.get();
4411 return ToolChain::getTool(JA.getKind());
4415 Tool *MyriadToolChain::buildLinker() const {
4416 return new tools::Myriad::Linker(*this);
4419 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple,
4420 const llvm::opt::ArgList &Args)
4421 : ToolChain(D, Triple, Args) {
4422 // Use LLD by default.
4423 DefaultLinker = "lld";
4426 bool WebAssembly::IsMathErrnoDefault() const { return false; }
4428 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; }
4430 bool WebAssembly::UseObjCMixedDispatch() const { return true; }
4432 bool WebAssembly::isPICDefault() const { return false; }
4434 bool WebAssembly::isPIEDefault() const { return false; }
4436 bool WebAssembly::isPICDefaultForced() const { return false; }
4438 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; }
4440 // TODO: Support Objective C stuff.
4441 bool WebAssembly::SupportsObjCGC() const { return false; }
4443 bool WebAssembly::hasBlocksRuntime() const { return false; }
4445 // TODO: Support profiling.
4446 bool WebAssembly::SupportsProfiling() const { return false; }
4448 bool WebAssembly::HasNativeLLVMSupport() const { return true; }
4450 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs,
4451 ArgStringList &CC1Args) const {
4452 if (DriverArgs.hasFlag(options::OPT_fuse_init_array,
4453 options::OPT_fno_use_init_array, true))
4454 CC1Args.push_back("-fuse-init-array");
4457 Tool *WebAssembly::buildLinker() const {
4458 return new tools::wasm::Linker(*this);
4461 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
4462 : Generic_ELF(D, Triple, Args) {
4463 if (Args.hasArg(options::OPT_static))
4464 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4";
4466 // Determine where to find the PS4 libraries. We use SCE_PS4_SDK_DIR
4467 // if it exists; otherwise use the driver's installation path, which
4468 // should be <SDK_DIR>/host_tools/bin.
4470 SmallString<512> PS4SDKDir;
4471 if (const char *EnvValue = getenv("SCE_PS4_SDK_DIR")) {
4472 if (!llvm::sys::fs::exists(EnvValue))
4473 getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue;
4474 PS4SDKDir = EnvValue;
4476 PS4SDKDir = getDriver().Dir;
4477 llvm::sys::path::append(PS4SDKDir, "/../../");
4480 // By default, the driver won't report a warning if it can't find
4481 // PS4's include or lib directories. This behavior could be changed if
4482 // -Weverything or -Winvalid-or-nonexistent-directory options are passed.
4483 // If -isysroot was passed, use that as the SDK base path.
4484 std::string PrefixDir;
4485 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4486 PrefixDir = A->getValue();
4487 if (!llvm::sys::fs::exists(PrefixDir))
4488 getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir;
4490 PrefixDir = PS4SDKDir.str();
4492 SmallString<512> PS4SDKIncludeDir(PrefixDir);
4493 llvm::sys::path::append(PS4SDKIncludeDir, "target/include");
4494 if (!Args.hasArg(options::OPT_nostdinc) &&
4495 !Args.hasArg(options::OPT_nostdlibinc) &&
4496 !Args.hasArg(options::OPT_isysroot) &&
4497 !Args.hasArg(options::OPT__sysroot_EQ) &&
4498 !llvm::sys::fs::exists(PS4SDKIncludeDir)) {
4499 getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
4500 << "PS4 system headers" << PS4SDKIncludeDir;
4503 SmallString<512> PS4SDKLibDir(PS4SDKDir);
4504 llvm::sys::path::append(PS4SDKLibDir, "target/lib");
4505 if (!Args.hasArg(options::OPT_nostdlib) &&
4506 !Args.hasArg(options::OPT_nodefaultlibs) &&
4507 !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) &&
4508 !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) &&
4509 !Args.hasArg(options::OPT_emit_ast) &&
4510 !llvm::sys::fs::exists(PS4SDKLibDir)) {
4511 getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected)
4512 << "PS4 system libraries" << PS4SDKLibDir;
4515 getFilePaths().push_back(PS4SDKLibDir.str());
4518 Tool *PS4CPU::buildAssembler() const {
4519 return new tools::PS4cpu::Assemble(*this);
4522 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); }
4524 bool PS4CPU::isPICDefault() const { return true; }
4526 bool PS4CPU::HasNativeLLVMSupport() const { return true; }
4528 SanitizerMask PS4CPU::getSupportedSanitizers() const {
4529 SanitizerMask Res = ToolChain::getSupportedSanitizers();
4530 Res |= SanitizerKind::Address;
4531 Res |= SanitizerKind::Vptr;