1 //===--- ToolChains.cpp - ToolChain Implementations -------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 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> 38 39 using namespace clang::driver; 40 using namespace clang::driver::toolchains; 41 using namespace clang; 42 using namespace llvm::opt; 43 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); 50 } 51 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) {} 55 56 types::ID MachO::LookupTypeForExtension(const char *Ext) const { 57 types::ID Ty = types::lookupTypeForExtension(Ext); 58 59 // Darwin always preprocesses assembly files (unless -x is used explicitly). 60 if (Ty == types::TY_PP_Asm) 61 return types::TY_Asm; 62 63 return Ty; 64 } 65 66 bool MachO::HasNativeLLVMSupport() const { return true; } 67 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); 74 if (isNonFragile) 75 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion); 76 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion); 77 } 78 79 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2. 80 bool Darwin::hasBlocksRuntime() const { 81 if (isTargetWatchOSBased()) 82 return true; 83 else if (isTargetIOSBased()) 84 return !isIPhoneOSVersionLT(3, 2); 85 else { 86 assert(isTargetMacOS() && "unexpected darwin target"); 87 return !isMacosxVersionLT(10, 6); 88 } 89 } 90 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") 109 .Default(nullptr); 110 } 111 112 static const char *ArmMachOArchNameCPU(StringRef CPU) { 113 unsigned ArchKind = llvm::ARM::parseCPUArch(CPU); 114 if (ArchKind == llvm::ARM::AK_INVALID) 115 return nullptr; 116 StringRef Arch = llvm::ARM::getArchName(ArchKind); 117 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); 128 return Arch.data(); 129 } 130 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); 134 if (!A) 135 return false; 136 137 return A->getOption().matches(options::OPT_msoft_float) || 138 (A->getOption().matches(options::OPT_mfloat_abi_EQ) && 139 A->getValue() == StringRef("soft")); 140 } 141 142 StringRef MachO::getMachOArchName(const ArgList &Args) const { 143 switch (getTriple().getArch()) { 144 default: 145 return getDefaultUniversalArchName(); 146 147 case llvm::Triple::aarch64: 148 return "arm64"; 149 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())) 154 return Arch; 155 156 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 157 if (const char *Arch = ArmMachOArchNameCPU(A->getValue())) 158 return Arch; 159 160 return "arm"; 161 } 162 } 163 164 Darwin::~Darwin() {} 165 166 MachO::~MachO() {} 167 168 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args, 169 types::ID InputType) const { 170 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); 171 172 return Triple.getTriple(); 173 } 174 175 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args, 176 types::ID InputType) const { 177 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); 178 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(); 183 184 SmallString<16> Str; 185 if (isTargetWatchOSBased()) 186 Str += "watchos"; 187 else if (isTargetTvOSBased()) 188 Str += "tvos"; 189 else if (isTargetIOSBased()) 190 Str += "ios"; 191 else 192 Str += "macosx"; 193 Str += getTargetVersion().getAsString(); 194 Triple.setOSName(Str); 195 196 return Triple.getTriple(); 197 } 198 199 void Generic_ELF::anchor() {} 200 201 Tool *MachO::getTool(Action::ActionClass AC) const { 202 switch (AC) { 203 case Action::LipoJobClass: 204 if (!Lipo) 205 Lipo.reset(new tools::darwin::Lipo(*this)); 206 return Lipo.get(); 207 case Action::DsymutilJobClass: 208 if (!Dsymutil) 209 Dsymutil.reset(new tools::darwin::Dsymutil(*this)); 210 return Dsymutil.get(); 211 case Action::VerifyDebugInfoJobClass: 212 if (!VerifyDebug) 213 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this)); 214 return VerifyDebug.get(); 215 default: 216 return ToolChain::getTool(AC); 217 } 218 } 219 220 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); } 221 222 Tool *MachO::buildAssembler() const { 223 return new tools::darwin::Assembler(*this); 224 } 225 226 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple, 227 const ArgList &Args) 228 : Darwin(D, Triple, Args) {} 229 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 234 // to an error. 235 CC1Args.push_back("-Wdeprecated-objc-isa-usage"); 236 CC1Args.push_back("-Werror=deprecated-objc-isa-usage"); 237 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"); 242 } 243 } 244 245 /// \brief Determine whether Objective-C automated reference counting is 246 /// enabled. 247 static bool isObjCAutoRefCount(const ArgList &Args) { 248 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 249 } 250 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) 255 return; 256 257 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true); 258 259 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) && 260 runtime.hasSubscripting()) 261 return; 262 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()) 272 P += "watchos"; 273 else if (isTargetTvOSSimulator()) 274 P += "appletvsimulator"; 275 else if (isTargetTvOS()) 276 P += "appletvos"; 277 else if (isTargetIOSSimulator()) 278 P += "iphonesimulator"; 279 else if (isTargetIPhoneOS()) 280 P += "iphoneos"; 281 else 282 P += "macosx"; 283 P += ".a"; 284 285 CmdArgs.push_back(Args.MakeArgString(P)); 286 } 287 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"); 293 294 SmallString<128> P(Dir); 295 llvm::sys::path::append(P, DarwinLibName); 296 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)); 302 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. 307 if (AddRPath) { 308 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library"); 309 310 // Add @executable_path to rpath to support having the dylib copied with 311 // the executable. 312 CmdArgs.push_back("-rpath"); 313 CmdArgs.push_back("@executable_path"); 314 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)); 319 } 320 } 321 322 void Darwin::addProfileRTLibs(const ArgList &Args, 323 ArgStringList &CmdArgs) const { 324 if (!needsProfileRT(Args)) return; 325 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"; 330 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"; 350 } else { 351 assert(isTargetMacOS() && "unexpected non MacOS platform"); 352 } 353 AddLinkRuntimeLib(Args, CmdArgs, Library, 354 /*AlwaysLink*/ true); 355 return; 356 } 357 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); 365 } 366 // ASan is not supported on watchOS. 367 assert(isTargetMacOS() || isTargetIOSSimulator()); 368 StringRef OS = isTargetMacOS() ? "osx" : "iossim"; 369 AddLinkRuntimeLib( 370 Args, CmdArgs, 371 (Twine("libclang_rt.") + Sanitizer + "_" + OS + "_dynamic.dylib").str(), 372 /*AlwaysLink*/ true, /*IsEmbedded*/ false, 373 /*AddRPath*/ true); 374 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"); 379 } 380 } 381 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: 387 break; 388 default: 389 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 390 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin"; 391 return; 392 } 393 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)) 399 return; 400 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); 406 return; 407 } 408 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"); 416 417 // Otherwise link libSystem, then the dynamic runtime library, and finally any 418 // target specific static runtime library. 419 CmdArgs.push_back("-lSystem"); 420 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"); 435 436 // We currently always need a static runtime library for iOS. 437 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a"); 438 } else { 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"); 446 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. 450 // 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"); 457 } else { 458 if (getTriple().getArch() == llvm::Triple::x86) 459 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a"); 460 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a"); 461 } 462 } 463 } 464 465 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { 466 const OptTable &Opts = getDriver().getOpts(); 467 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 470 // isysroot. 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(); 475 } else { 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)); 483 } 484 } 485 } 486 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); 491 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; 515 516 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET")) 517 OSXTarget = env; 518 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET")) 519 iOSTarget = env; 520 if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET")) 521 TvOSTarget = env; 522 if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET")) 523 WatchOSTarget = env; 524 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 527 // on -isysroot. 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")) 545 iOSTarget = Version; 546 else if (SDK.startswith("MacOSX")) 547 OSXTarget = Version; 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; 554 } 555 } 556 } 557 } 558 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 << '.' 569 << Micro; 570 } else if (MachOArchName == "armv7k") { 571 getTriple().getWatchOSVersion(Major, Minor, Micro); 572 llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.' 573 << Micro; 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(); 579 } 580 llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.' 581 << Micro; 582 } 583 } 584 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"); 591 } 592 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"; 598 } 599 600 // Allow conflicts among OSX and iOS for historical reasons, but choose the 601 // default platform. 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) 608 OSXTarget = ""; 609 else 610 iOSTarget = WatchOSTarget = TvOSTarget = ""; 611 } 612 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); 629 } 630 } 631 632 DarwinPlatformKind Platform; 633 if (OSXVersion) 634 Platform = MacOS; 635 else if (iOSVersion) 636 Platform = IPhoneOS; 637 else if (TvOSVersion) 638 Platform = TvOS; 639 else if (WatchOSVersion) 640 Platform = WatchOS; 641 else 642 llvm_unreachable("Unable to infer Darwin variant"); 643 644 // Set the tool chain target information. 645 unsigned Major, Minor, Micro; 646 bool HadExtra; 647 if (Platform == MacOS) { 648 assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) && 649 "Unknown target platform!"); 650 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro, 651 HadExtra) || 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, 658 HadExtra) || 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); 674 } else 675 llvm_unreachable("unknown kind of Darwin platform"); 676 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; 687 688 setTarget(Platform, Major, Minor, Micro); 689 } 690 691 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args, 692 ArgStringList &CmdArgs) const { 693 CXXStdlibType Type = GetCXXStdlibType(Args); 694 695 switch (Type) { 696 case ToolChain::CST_Libcxx: 697 CmdArgs.push_back("-lc++"); 698 break; 699 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. 705 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"); 710 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)); 716 return; 717 } 718 } 719 } 720 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"); 727 return; 728 } 729 730 // Otherwise, let the linker search. 731 CmdArgs.push_back("-lstdc++"); 732 break; 733 } 734 } 735 736 void DarwinClang::AddCCKextLibArgs(const ArgList &Args, 737 ArgStringList &CmdArgs) const { 738 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). 742 743 SmallString<128> P(getDriver().ResourceDir); 744 llvm::sys::path::append(P, "lib", "darwin"); 745 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"); 753 } else { 754 llvm::sys::path::append(P, "libclang_rt.cc_kext.a"); 755 } 756 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)); 761 } 762 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(); 767 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. 774 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() || 782 (BoundArch && 783 XarchArch == 784 tools::darwin::getArchTypeForMachOArchName(BoundArch)))) 785 continue; 786 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)); 791 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. 795 // 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); 803 continue; 804 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) { 805 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver) 806 << A->getAsString(Args); 807 continue; 808 } 809 810 XarchArg->setBaseArg(A); 811 812 A = XarchArg.release(); 813 DAL->AddSynthesizedArg(A); 814 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()) { 821 DAL->AddSeparateArg( 822 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value); 823 } 824 continue; 825 } 826 } 827 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()) { 832 default: 833 DAL->append(A); 834 break; 835 836 case options::OPT_mkernel: 837 case options::OPT_fapple_kext: 838 DAL->append(A); 839 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static)); 840 break; 841 842 case options::OPT_dependency_file: 843 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue()); 844 break; 845 846 case options::OPT_gfull: 847 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); 848 DAL->AddFlagArg( 849 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols)); 850 break; 851 852 case options::OPT_gused: 853 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); 854 DAL->AddFlagArg( 855 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols)); 856 break; 857 858 case options::OPT_shared: 859 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib)); 860 break; 861 862 case options::OPT_fconstant_cfstrings: 863 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings)); 864 break; 865 866 case options::OPT_fno_constant_cfstrings: 867 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings)); 868 break; 869 870 case options::OPT_Wnonportable_cfstrings: 871 DAL->AddFlagArg(A, 872 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings)); 873 break; 874 875 case options::OPT_Wno_nonportable_cfstrings: 876 DAL->AddFlagArg( 877 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings)); 878 break; 879 880 case options::OPT_fpascal_strings: 881 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings)); 882 break; 883 884 case options::OPT_fno_pascal_strings: 885 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings)); 886 break; 887 } 888 } 889 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), 894 "core2"); 895 896 // Add the arch options based on the particular spelling of -arch, to match 897 // how the driver driver works. 898 if (BoundArch) { 899 StringRef Name = BoundArch; 900 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ); 901 const Option MArch = Opts.getOption(options::OPT_march_EQ); 902 903 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch, 904 // which defines the list of which architectures we accept. 905 if (Name == "ppc") 906 ; 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"); 923 924 else if (Name == "ppc64" || Name == "ppc64le") 925 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64)); 926 927 else if (Name == "i386") 928 ; 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"); 943 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"); 949 } 950 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"); 973 } 974 975 return DAL; 976 } 977 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."); 984 CompilerRT += 985 (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard) 986 ? "hard" 987 : "soft"; 988 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a"; 989 990 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true); 991 } 992 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(); 998 999 // If no architecture is bound, none of the translations here are relevant. 1000 if (!BoundArch) 1001 return DAL; 1002 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 1005 // argument. 1006 AddDeploymentTarget(*DAL); 1007 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 1011 // it is set here. 1012 if (isTargetWatchOSBased() || 1013 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) { 1014 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) { 1015 Arg *A = *it; 1016 ++it; 1017 if (A->getOption().getID() != options::OPT_mkernel && 1018 A->getOption().getID() != options::OPT_fapple_kext) 1019 continue; 1020 assert(it != ie && "unexpected argument translation"); 1021 A = *it; 1022 assert(A->getOption().getID() == options::OPT_static && 1023 "missing expected -static argument"); 1024 it = DAL->getArgs().erase(it); 1025 } 1026 } 1027 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), 1034 "libc++"); 1035 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++. 1040 StringRef where; 1041 1042 // Complain about targeting iOS < 5.0 in any way. 1043 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0)) 1044 where = "iOS 5.0"; 1045 1046 if (where != StringRef()) { 1047 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where; 1048 } 1049 } 1050 1051 return DAL; 1052 } 1053 1054 bool MachO::IsUnwindTablesDefault() const { 1055 return getArch() == llvm::Triple::x86_64; 1056 } 1057 1058 bool MachO::UseDwarfDebugFlags() const { 1059 if (const char *S = ::getenv("RC_DEBUG_OPTIONS")) 1060 return S[0] != '\0'; 1061 return false; 1062 } 1063 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) 1068 return false; 1069 1070 // Only watchOS uses the new DWARF/Compact unwinding method. 1071 return !isTargetWatchOS(); 1072 } 1073 1074 bool MachO::isPICDefault() const { return true; } 1075 1076 bool MachO::isPIEDefault() const { return false; } 1077 1078 bool MachO::isPICDefaultForced() const { 1079 return (getArch() == llvm::Triple::x86_64 || 1080 getArch() == llvm::Triple::aarch64); 1081 } 1082 1083 bool MachO::SupportsProfiling() const { 1084 // Profiling instrumentation is only supported on x86. 1085 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64; 1086 } 1087 1088 void Darwin::addMinVersionArgs(const ArgList &Args, 1089 ArgStringList &CmdArgs) const { 1090 VersionTuple TargetVersion = getTargetVersion(); 1091 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"); 1104 else { 1105 assert(isTargetMacOS() && "unexpected target"); 1106 CmdArgs.push_back("-macosx_version_min"); 1107 } 1108 1109 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString())); 1110 } 1111 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"); 1124 } else { 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"); 1129 } 1130 } else { 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"); 1141 } else { 1142 if (isMacosxVersionLT(10, 6)) 1143 CmdArgs.push_back("-lbundle1.o"); 1144 } 1145 } 1146 } else { 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"); 1152 } else { 1153 CmdArgs.push_back("-lgcrt1.o"); 1154 1155 // darwin_crt2 spec is empty. 1156 } 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"); 1164 } else { 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"); 1169 } else { 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"); 1182 } else { 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"); 1189 1190 // darwin_crt2 spec is empty. 1191 } 1192 } 1193 } 1194 } 1195 } 1196 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); 1202 } 1203 } 1204 1205 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); } 1206 1207 void Darwin::CheckObjCARC() const { 1208 if (isTargetIOSBased() || isTargetWatchOSBased() || 1209 (isTargetMacOS() && !isMacosxVersionLT(10, 6))) 1210 return; 1211 getDriver().Diag(diag::err_arc_unsupported_on_toolchain); 1212 } 1213 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; 1223 } 1224 return Res; 1225 } 1226 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. 1230 1231 /// \brief Parse a GCCVersion object out of a string of text. 1232 /// 1233 /// This is the primary means of forming GCCVersion objects. 1234 /*static*/ 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('.'); 1239 1240 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""}; 1241 if (First.first.getAsInteger(10, GoodVersion.Major) || GoodVersion.Major < 0) 1242 return BadVersion; 1243 GoodVersion.MajorStr = First.first.str(); 1244 if (Second.first.getAsInteger(10, GoodVersion.Minor) || GoodVersion.Minor < 0) 1245 return BadVersion; 1246 GoodVersion.MinorStr = Second.first.str(); 1247 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: 1251 // 4.4 1252 // 4.4.0 1253 // 4.4.x 1254 // 4.4.2-rc4 1255 // 4.4.x-patched 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) 1263 return BadVersion; 1264 GoodVersion.PatchSuffix = PatchText.substr(EndNumber); 1265 } 1266 } 1267 1268 return GoodVersion; 1269 } 1270 1271 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering. 1272 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor, 1273 int RHSPatch, 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 1281 // a patch. 1282 if (RHSPatch == -1) 1283 return true; 1284 if (Patch == -1) 1285 return false; 1286 1287 // Otherwise just sort on the patch itself. 1288 return Patch < RHSPatch; 1289 } 1290 if (PatchSuffix != RHSPatchSuffix) { 1291 // Sort empty suffixes higher. 1292 if (RHSPatchSuffix.empty()) 1293 return true; 1294 if (PatchSuffix.empty()) 1295 return false; 1296 1297 // Provide a lexicographic sort to make this a total ordering. 1298 return PatchSuffix < RHSPatchSuffix; 1299 } 1300 1301 // The versions are equal. 1302 return false; 1303 } 1304 1305 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) { 1306 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain); 1307 if (A) 1308 return A->getValue(); 1309 return GCC_INSTALL_PREFIX; 1310 } 1311 1312 /// \brief Initialize a GCCInstallationDetector from the driver. 1313 /// 1314 /// This performs all of the autodetection and sets up the various paths. 1315 /// Once constructed, a GCCInstallationDetector is essentially immutable. 1316 /// 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 1320 /// triple. 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); 1335 1336 // Compute the set of prefixes for our search. 1337 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(), 1338 D.PrefixDirs.end()); 1339 1340 StringRef GCCToolchainDir = getGCCToolchainDir(Args); 1341 if (GCCToolchainDir != "") { 1342 if (GCCToolchainDir.back() == '/') 1343 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the / 1344 1345 Prefixes.push_back(GCCToolchainDir); 1346 } else { 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"); 1351 } 1352 1353 // Then look for gcc installed alongside clang. 1354 Prefixes.push_back(D.InstalledDir + "/.."); 1355 1356 // And finally in /usr. 1357 if (D.SysRoot.empty()) 1358 Prefixes.push_back("/usr"); 1359 } 1360 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)) 1366 continue; 1367 for (StringRef Suffix : CandidateLibDirs) { 1368 const std::string LibDir = Prefix + Suffix.str(); 1369 if (!D.getVFS().exists(LibDir)) 1370 continue; 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); 1375 } 1376 for (StringRef Suffix : CandidateBiarchLibDirs) { 1377 const std::string LibDir = Prefix + Suffix.str(); 1378 if (!D.getVFS().exists(LibDir)) 1379 continue; 1380 for (StringRef Candidate : CandidateBiarchTripleAliases) 1381 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, 1382 /*NeedsBiarchSuffix=*/ true); 1383 } 1384 } 1385 } 1386 1387 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const { 1388 for (const auto &InstallPath : CandidateGCCInstallPaths) 1389 OS << "Found candidate GCC installation: " << InstallPath << "\n"; 1390 1391 if (!GCCInstallPath.empty()) 1392 OS << "Selected GCC installation: " << GCCInstallPath << "\n"; 1393 1394 for (const auto &Multilib : Multilibs) 1395 OS << "Candidate multilib: " << Multilib << "\n"; 1396 1397 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault()) 1398 OS << "Selected multilib: " << SelectedMultilib << "\n"; 1399 } 1400 1401 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const { 1402 if (BiarchSibling.hasValue()) { 1403 M = BiarchSibling.getValue(); 1404 return true; 1405 } 1406 return false; 1407 } 1408 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"}; 1425 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"}; 1436 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", 1452 "i586-linux-gnu"}; 1453 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"}; 1461 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"}; 1470 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"}; 1483 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"}; 1490 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"}; 1495 1496 // Solaris. 1497 static const char *const SolarisSPARCLibDirs[] = {"/gcc"}; 1498 static const char *const SolarisSPARCTriples[] = {"sparc-sun-solaris2.11", 1499 "i386-pc-solaris2.11"}; 1500 1501 using std::begin; 1502 using std::end; 1503 1504 if (TargetTriple.getOS() == llvm::Triple::Solaris) { 1505 LibDirs.append(begin(SolarisSPARCLibDirs), end(SolarisSPARCLibDirs)); 1506 TripleAliases.append(begin(SolarisSPARCTriples), end(SolarisSPARCTriples)); 1507 return; 1508 } 1509 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)); 1516 break; 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)); 1522 break; 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)); 1528 } else { 1529 TripleAliases.append(begin(ARMTriples), end(ARMTriples)); 1530 } 1531 break; 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)); 1537 } else { 1538 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples)); 1539 } 1540 break; 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)); 1549 } else { 1550 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 1551 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples)); 1552 } 1553 break; 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)); 1559 break; 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)); 1565 break; 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)); 1572 break; 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)); 1578 break; 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)); 1585 break; 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)); 1591 break; 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)); 1597 break; 1598 case llvm::Triple::ppc64le: 1599 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs)); 1600 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples)); 1601 break; 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)); 1608 break; 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)); 1614 break; 1615 case llvm::Triple::systemz: 1616 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs)); 1617 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples)); 1618 break; 1619 default: 1620 // By default, just rely on the standard lib directories and the original 1621 // triple. 1622 break; 1623 } 1624 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()); 1628 1629 // Also include the multiarch variant if it's different. 1630 if (TargetTriple.str() != BiarchTriple.str()) 1631 BiarchTripleAliases.push_back(BiarchTriple.str()); 1632 } 1633 1634 // \brief -- try common CUDA installation paths looking for files we need for 1635 // CUDA compilation. 1636 1637 void Generic_GCC::CudaInstallationDetector::init( 1638 const llvm::Triple &TargetTriple, const llvm::opt::ArgList &Args) { 1639 SmallVector<std::string, 4> CudaPathCandidates; 1640 1641 if (Args.hasArg(options::OPT_cuda_path_EQ)) 1642 CudaPathCandidates.push_back( 1643 Args.getLastArgValue(options::OPT_cuda_path_EQ)); 1644 else { 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"); 1648 } 1649 1650 for (const auto &CudaPath : CudaPathCandidates) { 1651 if (CudaPath.empty() || !D.getVFS().exists(CudaPath)) 1652 continue; 1653 1654 CudaInstallPath = CudaPath; 1655 CudaIncludePath = CudaInstallPath + "/include"; 1656 CudaLibDevicePath = CudaInstallPath + "/nvvm/libdevice"; 1657 CudaLibPath = 1658 CudaInstallPath + (TargetTriple.isArch64Bit() ? "/lib64" : "/lib"); 1659 1660 if (!(D.getVFS().exists(CudaIncludePath) && 1661 D.getVFS().exists(CudaLibPath) && 1662 D.getVFS().exists(CudaLibDevicePath))) 1663 continue; 1664 1665 std::error_code EC; 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"))) 1673 continue; 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; 1687 } 1688 } 1689 1690 IsValid = true; 1691 break; 1692 } 1693 } 1694 1695 void Generic_GCC::CudaInstallationDetector::print(raw_ostream &OS) const { 1696 if (isValid()) 1697 OS << "Found CUDA installation: " << CudaInstallPath << "\n"; 1698 } 1699 1700 namespace { 1701 // Filter to remove Multilibs that don't exist as a suffix to Path 1702 class FilterNonExistent { 1703 StringRef Base; 1704 vfs::FileSystem &VFS; 1705 1706 public: 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"); 1711 } 1712 }; 1713 } // end anonymous namespace 1714 1715 static void addMultilibFlag(bool Enabled, const char *const Flag, 1716 std::vector<std::string> &Flags) { 1717 if (Enabled) 1718 Flags.push_back(std::string("+") + Flag); 1719 else 1720 Flags.push_back(std::string("-") + Flag); 1721 } 1722 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; 1726 } 1727 1728 static bool isMips32(llvm::Triple::ArchType Arch) { 1729 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel; 1730 } 1731 1732 static bool isMips64(llvm::Triple::ArchType Arch) { 1733 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el; 1734 } 1735 1736 static bool isMipsEL(llvm::Triple::ArchType Arch) { 1737 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el; 1738 } 1739 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); 1743 } 1744 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); 1748 } 1749 1750 namespace { 1751 struct DetectedMultilibs { 1752 /// The set of multilibs that the detected installation supports. 1753 MultilibSet Multilibs; 1754 1755 /// The primary multilib appropriate for the given flags. 1756 Multilib SelectedMultilib; 1757 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; 1761 }; 1762 } // end anonymous namespace 1763 1764 static Multilib makeMultilib(StringRef commonSuffix) { 1765 return Multilib(commonSuffix, commonSuffix, commonSuffix); 1766 } 1767 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: 1775 // 1776 // /usr 1777 // /lib <= crt*.o files compiled with '-mips32' 1778 // /mips16 1779 // /usr 1780 // /lib <= crt*.o files compiled with '-mips16' 1781 // /el 1782 // /usr 1783 // /lib <= crt*.o files compiled with '-mips16 -EL' 1784 // 1785 // or 1786 // 1787 // /usr 1788 // /lib <= crt*.o files compiled with '-mips32r2' 1789 // /mips16 1790 // /usr 1791 // /lib <= crt*.o files compiled with '-mips32r2 -mips16' 1792 // /mips32 1793 // /usr 1794 // /lib <= crt*.o files compiled with '-mips32' 1795 1796 FilterNonExistent NonExistent(Path, D.getVFS()); 1797 1798 // Check for FSF toolchain multilibs 1799 MultilibSet FSFMipsMultilibs; 1800 { 1801 auto MArchMips32 = makeMultilib("/mips32") 1802 .flag("+m32") 1803 .flag("-m64") 1804 .flag("-mmicromips") 1805 .flag("+march=mips32"); 1806 1807 auto MArchMicroMips = makeMultilib("/micromips") 1808 .flag("+m32") 1809 .flag("-m64") 1810 .flag("+mmicromips"); 1811 1812 auto MArchMips64r2 = makeMultilib("/mips64r2") 1813 .flag("-m32") 1814 .flag("+m64") 1815 .flag("+march=mips64r2"); 1816 1817 auto MArchMips64 = makeMultilib("/mips64").flag("-m32").flag("+m64").flag( 1818 "-march=mips64r2"); 1819 1820 auto MArchDefault = makeMultilib("") 1821 .flag("+m32") 1822 .flag("-m64") 1823 .flag("-mmicromips") 1824 .flag("+march=mips32r2"); 1825 1826 auto Mips16 = makeMultilib("/mips16").flag("+mips16"); 1827 1828 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc"); 1829 1830 auto MAbi64 = 1831 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32"); 1832 1833 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL"); 1834 1835 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB"); 1836 1837 auto SoftFloat = makeMultilib("/sof").flag("+msoft-float"); 1838 1839 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008"); 1840 1841 FSFMipsMultilibs = 1842 MultilibSet() 1843 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64, 1844 MArchDefault) 1845 .Maybe(UCLibc) 1846 .Maybe(Mips16) 1847 .FilterOut("/mips64/mips16") 1848 .FilterOut("/mips64r2/mips16") 1849 .FilterOut("/micromips/mips16") 1850 .Maybe(MAbi64) 1851 .FilterOut("/micromips/64") 1852 .FilterOut("/mips32/64") 1853 .FilterOut("^/64") 1854 .FilterOut("/mips16/64") 1855 .Either(BigEndian, LittleEndian) 1856 .Maybe(SoftFloat) 1857 .Maybe(Nan2008) 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"); 1868 else 1869 Dirs.push_back(SysRootInc + "/usr/include"); 1870 return Dirs; 1871 }); 1872 } 1873 1874 // Check for Musl toolchain multilibs 1875 MultilibSet MuslMipsMultilibs; 1876 { 1877 auto MArchMipsR2 = makeMultilib("") 1878 .osSuffix("/mips-r2-hard-musl") 1879 .flag("+EB") 1880 .flag("-EL") 1881 .flag("+march=mips32r2"); 1882 1883 auto MArchMipselR2 = makeMultilib("/mipsel-r2-hard-musl") 1884 .flag("-EB") 1885 .flag("+EL") 1886 .flag("+march=mips32r2"); 1887 1888 MuslMipsMultilibs = MultilibSet().Either(MArchMipsR2, MArchMipselR2); 1889 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; 1894 Dirs.push_back( 1895 (InstallDir + "/../sysroot" + M.osSuffix() + "/usr/include").str()); 1896 return Dirs; 1897 }); 1898 } 1899 1900 // Check for Code Sourcery toolchain multilibs 1901 MultilibSet CSMipsMultilibs; 1902 { 1903 auto MArchMips16 = makeMultilib("/mips16").flag("+m32").flag("+mips16"); 1904 1905 auto MArchMicroMips = 1906 makeMultilib("/micromips").flag("+m32").flag("+mmicromips"); 1907 1908 auto MArchDefault = makeMultilib("").flag("-mips16").flag("-mmicromips"); 1909 1910 auto UCLibc = makeMultilib("/uclibc").flag("+muclibc"); 1911 1912 auto SoftFloat = makeMultilib("/soft-float").flag("+msoft-float"); 1913 1914 auto Nan2008 = makeMultilib("/nan2008").flag("+mnan=2008"); 1915 1916 auto DefaultFloat = 1917 makeMultilib("").flag("-msoft-float").flag("-mnan=2008"); 1918 1919 auto BigEndian = makeMultilib("").flag("+EB").flag("-EL"); 1920 1921 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB"); 1922 1923 // Note that this one's osSuffix is "" 1924 auto MAbi64 = makeMultilib("") 1925 .gccSuffix("/64") 1926 .includeSuffix("/64") 1927 .flag("+mabi=n64") 1928 .flag("-mabi=n32") 1929 .flag("-m32"); 1930 1931 CSMipsMultilibs = 1932 MultilibSet() 1933 .Either(MArchMips16, MArchMicroMips, MArchDefault) 1934 .Maybe(UCLibc) 1935 .Either(SoftFloat, Nan2008, DefaultFloat) 1936 .FilterOut("/micromips/nan2008") 1937 .FilterOut("/mips16/nan2008") 1938 .Either(BigEndian, LittleEndian) 1939 .Maybe(MAbi64) 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"); 1951 else 1952 Dirs.push_back(SysRootInc + "/libc/usr/include"); 1953 return Dirs; 1954 }); 1955 } 1956 1957 MultilibSet AndroidMipsMultilibs = 1958 MultilibSet() 1959 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2")) 1960 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6")) 1961 .FilterOut(NonExistent); 1962 1963 MultilibSet DebianMipsMultilibs; 1964 { 1965 Multilib MAbiN32 = 1966 Multilib().gccSuffix("/n32").includeSuffix("/n32").flag("+mabi=n32"); 1967 1968 Multilib M64 = Multilib() 1969 .gccSuffix("/64") 1970 .includeSuffix("/64") 1971 .flag("+m64") 1972 .flag("-m32") 1973 .flag("-mabi=n32"); 1974 1975 Multilib M32 = Multilib().flag("-m64").flag("+m32").flag("-mabi=n32"); 1976 1977 DebianMipsMultilibs = 1978 MultilibSet().Either(M32, M64, MAbiN32).FilterOut(NonExistent); 1979 } 1980 1981 MultilibSet ImgMultilibs; 1982 { 1983 auto Mips64r6 = makeMultilib("/mips64r6").flag("+m64").flag("-m32"); 1984 1985 auto LittleEndian = makeMultilib("/el").flag("+EL").flag("-EB"); 1986 1987 auto MAbi64 = 1988 makeMultilib("/64").flag("+mabi=n64").flag("-mabi=n32").flag("-m32"); 1989 1990 ImgMultilibs = 1991 MultilibSet() 1992 .Maybe(Mips64r6) 1993 .Maybe(MAbi64) 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()); 2000 Dirs.push_back( 2001 (InstallDir + "/../../../../sysroot/usr/include").str()); 2002 return Dirs; 2003 }); 2004 } 2005 2006 StringRef CPUName; 2007 StringRef ABIName; 2008 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName); 2009 2010 llvm::Triple::ArchType TargetArch = TargetTriple.getArch(); 2011 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", 2028 Flags); 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); 2035 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; 2040 return true; 2041 } 2042 return false; 2043 } 2044 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; 2050 return true; 2051 } 2052 return false; 2053 } 2054 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; 2061 return true; 2062 } 2063 return false; 2064 } 2065 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, 2069 &CSMipsMultilibs}; 2070 std::sort( 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; 2078 return true; 2079 } 2080 } 2081 2082 { 2083 // Fallback to the regular toolchain-tree structure. 2084 Multilib Default; 2085 Result.Multilibs.push_back(Default); 2086 Result.Multilibs.FilterOut(NonExistent); 2087 2088 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) { 2089 Result.BiarchSibling = Multilib(); 2090 return true; 2091 } 2092 } 2093 2094 return false; 2095 } 2096 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. 2108 2109 Multilib Default; 2110 Multilib Alt64 = Multilib() 2111 .gccSuffix("/64") 2112 .includeSuffix("/64") 2113 .flag("-m32") 2114 .flag("+m64") 2115 .flag("-mx32"); 2116 Multilib Alt32 = Multilib() 2117 .gccSuffix("/32") 2118 .includeSuffix("/32") 2119 .flag("+m32") 2120 .flag("-m64") 2121 .flag("-mx32"); 2122 Multilib Altx32 = Multilib() 2123 .gccSuffix("/x32") 2124 .includeSuffix("/x32") 2125 .flag("-m32") 2126 .flag("-m64") 2127 .flag("+mx32"); 2128 2129 FilterNonExistent NonExistent(Path, D.getVFS()); 2130 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)) 2136 Want = WANT64; 2137 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32)) 2138 Want = WANT64; 2139 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64)) 2140 Want = WANT32; 2141 else { 2142 if (TargetTriple.isArch32Bit()) 2143 Want = NeedsBiarchSuffix ? WANT64 : WANT32; 2144 else if (IsX32) 2145 Want = NeedsBiarchSuffix ? WANT64 : WANTX32; 2146 else 2147 Want = NeedsBiarchSuffix ? WANT32 : WANT64; 2148 } 2149 2150 if (Want == WANT32) 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"); 2156 else 2157 return false; 2158 2159 Result.Multilibs.push_back(Default); 2160 Result.Multilibs.push_back(Alt64); 2161 Result.Multilibs.push_back(Alt32); 2162 Result.Multilibs.push_back(Altx32); 2163 2164 Result.Multilibs.FilterOut(NonExistent); 2165 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); 2170 2171 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib)) 2172 return false; 2173 2174 if (Result.SelectedMultilib == Alt64 || Result.SelectedMultilib == Alt32 || 2175 Result.SelectedMultilib == Altx32) 2176 Result.BiarchSibling = Default; 2177 2178 return true; 2179 } 2180 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. 2188 std::error_code EC; 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); 2193 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)) 2198 continue; 2199 if (CandidateVersion <= Version) 2200 continue; 2201 2202 GCCInstallPath = 2203 LibDir + "/" + VersionText.str() + "/lib/gcc/" + CandidateTriple.str(); 2204 if (!D.getVFS().exists(GCCInstallPath)) 2205 continue; 2206 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), 2212 LLE; 2213 !EEC && LLI != LLE; LLI = LLI.increment(EEC)) { 2214 2215 StringRef SubVersionText = llvm::sys::path::filename(LLI->getName()); 2216 GCCVersion CandidateSubVersion = GCCVersion::Parse(SubVersionText); 2217 2218 if (CandidateSubVersion > Version) 2219 Version = CandidateSubVersion; 2220 } 2221 2222 GCCTriple.setTriple(CandidateTriple); 2223 2224 GCCInstallPath += "/" + Version.Text; 2225 GCCParentLibPath = GCCInstallPath + "/../../../../"; 2226 2227 IsValid = true; 2228 } 2229 } 2230 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(), "/../../.."}, 2243 2244 // Debian puts cross-compilers in gcc-cross 2245 {"/gcc-cross/" + CandidateTriple.str(), "/../../.."}, 2246 2247 {"/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), 2248 "/../../../.."}, 2249 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(), "/../.."}, 2253 2254 // Ubuntu has a strange mis-matched pair of triples that this happens to 2255 // match. 2256 // FIXME: It may be worthwhile to generalize this and look for a second 2257 // triple. 2258 {"/i386-linux-gnu/gcc/" + CandidateTriple.str(), "/../../../.."}}; 2259 2260 if (TargetTriple.getOS() == llvm::Triple::Solaris) { 2261 scanLibDirForGCCTripleSolaris(TargetTriple, Args, LibDir, CandidateTriple, 2262 NeedsBiarchSuffix); 2263 return; 2264 } 2265 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]; 2271 std::error_code EC; 2272 for (vfs::directory_iterator 2273 LI = D.getVFS().dir_begin(LibDir + LibSuffix, EC), 2274 LE; 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)) 2282 continue; 2283 if (CandidateVersion <= Version) 2284 continue; 2285 2286 DetectedMultilibs Detected; 2287 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)) 2292 continue; 2293 } else if (!findBiarchMultilibs(D, TargetTriple, LI->getName(), Args, 2294 NeedsBiarchSuffix, Detected)) { 2295 continue; 2296 } 2297 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 2305 // Linux. 2306 GCCInstallPath = 2307 LibDir + LibAndInstallSuffixes[i][0] + "/" + VersionText.str(); 2308 GCCParentLibPath = GCCInstallPath + LibAndInstallSuffixes[i][1]; 2309 IsValid = true; 2310 } 2311 } 2312 } 2313 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); 2320 } 2321 2322 Generic_GCC::~Generic_GCC() {} 2323 2324 Tool *Generic_GCC::getTool(Action::ActionClass AC) const { 2325 switch (AC) { 2326 case Action::PreprocessJobClass: 2327 if (!Preprocess) 2328 Preprocess.reset(new tools::gcc::Preprocessor(*this)); 2329 return Preprocess.get(); 2330 case Action::CompileJobClass: 2331 if (!Compile) 2332 Compile.reset(new tools::gcc::Compiler(*this)); 2333 return Compile.get(); 2334 default: 2335 return ToolChain::getTool(AC); 2336 } 2337 } 2338 2339 Tool *Generic_GCC::buildAssembler() const { 2340 return new tools::gnutools::Assembler(*this); 2341 } 2342 2343 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); } 2344 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); 2349 } 2350 2351 bool Generic_GCC::IsUnwindTablesDefault() const { 2352 return getArch() == llvm::Triple::x86_64; 2353 } 2354 2355 bool Generic_GCC::isPICDefault() const { 2356 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows(); 2357 } 2358 2359 bool Generic_GCC::isPIEDefault() const { return false; } 2360 2361 bool Generic_GCC::isPICDefaultForced() const { 2362 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows(); 2363 } 2364 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: 2381 return true; 2382 default: 2383 return false; 2384 } 2385 } 2386 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)) 2393 return false; 2394 2395 addSystemInclude(DriverArgs, CC1Args, Base + Suffix); 2396 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); 2404 } else { 2405 // Otherwise try to use multiarch naming schemes which have normalized the 2406 // triples and put the triple before the suffix. 2407 // 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); 2414 } 2415 2416 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward"); 2417 return true; 2418 } 2419 2420 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()); 2432 2433 if (DriverArgs.hasFlag(options::OPT_fuse_init_array, 2434 options::OPT_fno_use_init_array, UseInitArrayDefault)) 2435 CC1Args.push_back("-fuse-init-array"); 2436 } 2437 2438 /// Mips Toolchain 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; 2448 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); 2453 2454 // Use LLD by default. 2455 DefaultLinker = "lld"; 2456 } 2457 2458 void MipsLLVMToolChain::AddClangSystemIncludeArgs( 2459 const ArgList &DriverArgs, ArgStringList &CC1Args) const { 2460 if (DriverArgs.hasArg(options::OPT_nostdinc)) 2461 return; 2462 2463 const Driver &D = getDriver(); 2464 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); 2469 } 2470 2471 if (DriverArgs.hasArg(options::OPT_nostdlibinc)) 2472 return; 2473 2474 const auto &Callback = Multilibs.includeDirsCallback(); 2475 if (Callback) { 2476 const auto IncludePaths = 2477 Callback(D.getInstalledDir(), getTripleString(), SelectedMultilib); 2478 for (const auto &Path : IncludePaths) 2479 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path); 2480 } 2481 } 2482 2483 Tool *MipsLLVMToolChain::buildLinker() const { 2484 return new tools::gnutools::Linker(*this); 2485 } 2486 2487 std::string MipsLLVMToolChain::computeSysRoot() const { 2488 if (!getDriver().SysRoot.empty()) 2489 return getDriver().SysRoot + SelectedMultilib.osSuffix(); 2490 2491 const std::string InstalledDir(getDriver().getInstalledDir()); 2492 std::string SysRootPath = 2493 InstalledDir + "/../sysroot" + SelectedMultilib.osSuffix(); 2494 if (llvm::sys::fs::exists(SysRootPath)) 2495 return SysRootPath; 2496 2497 return std::string(); 2498 } 2499 2500 ToolChain::CXXStdlibType 2501 MipsLLVMToolChain::GetCXXStdlibType(const ArgList &Args) const { 2502 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 2503 if (A) { 2504 StringRef Value = A->getValue(); 2505 if (Value != "libc++") 2506 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 2507 << A->getAsString(Args); 2508 } 2509 2510 return ToolChain::CST_Libcxx; 2511 } 2512 2513 void MipsLLVMToolChain::AddClangCXXStdlibIncludeArgs( 2514 const ArgList &DriverArgs, ArgStringList &CC1Args) const { 2515 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2516 DriverArgs.hasArg(options::OPT_nostdincxx)) 2517 return; 2518 2519 assert((GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) && 2520 "Only -lc++ (aka libcxx) is suported in this toolchain."); 2521 2522 const auto &Callback = Multilibs.includeDirsCallback(); 2523 if (Callback) { 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"); 2529 break; 2530 } 2531 } 2532 } 2533 } 2534 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."); 2539 2540 CmdArgs.push_back("-lc++"); 2541 CmdArgs.push_back("-lc++abi"); 2542 CmdArgs.push_back("-lunwind"); 2543 } 2544 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, 2550 getOS()); 2551 llvm::sys::path::append(Path, Twine("libclang_rt." + Component + "-" + 2552 "mips" + (Shared ? ".so" : ".a"))); 2553 return Path.str(); 2554 } 2555 2556 /// Hexagon Toolchain 2557 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(); 2563 2564 // Locate the rest of the toolchain ... 2565 for (auto &I : PrefixDirs) 2566 if (D.getVFS().exists(I)) 2567 return I; 2568 2569 if (getVFS().exists(InstallRelDir = InstalledDir + "/../target")) 2570 return InstallRelDir; 2571 2572 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/target"; 2573 if (getVFS().exists(PrefixRelDir)) 2574 return PrefixRelDir; 2575 2576 return InstallRelDir; 2577 } 2578 2579 2580 Optional<unsigned> HexagonToolChain::getSmallDataThreshold( 2581 const ArgList &Args) { 2582 StringRef Gn = ""; 2583 if (Arg *A = Args.getLastArg(options::OPT_G, options::OPT_G_EQ, 2584 options::OPT_msmall_data_threshold_EQ)) { 2585 Gn = A->getValue(); 2586 } else if (Args.getLastArg(options::OPT_shared, options::OPT_fpic, 2587 options::OPT_fPIC)) { 2588 Gn = "0"; 2589 } 2590 2591 unsigned G; 2592 if (!Gn.getAsInteger(10, G)) 2593 return G; 2594 2595 return None; 2596 } 2597 2598 2599 void HexagonToolChain::getHexagonLibraryPaths(const ArgList &Args, 2600 ToolChain::path_list &LibPaths) const { 2601 const Driver &D = getDriver(); 2602 2603 //---------------------------------------------------------------------------- 2604 // -L Args 2605 //---------------------------------------------------------------------------- 2606 for (Arg *A : Args.filtered(options::OPT_L)) 2607 for (const char *Value : A->getValues()) 2608 LibPaths.push_back(Value); 2609 2610 //---------------------------------------------------------------------------- 2611 // Other standard paths 2612 //---------------------------------------------------------------------------- 2613 std::vector<std::string> RootDirs; 2614 std::copy(D.PrefixDirs.begin(), D.PrefixDirs.end(), RootDirs.begin()); 2615 2616 std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(), 2617 D.PrefixDirs); 2618 if (std::find(RootDirs.begin(), RootDirs.end(), TargetDir) == RootDirs.end()) 2619 RootDirs.push_back(TargetDir); 2620 2621 bool HasPIC = Args.hasArg(options::OPT_fpic, options::OPT_fPIC); 2622 // Assume G0 with -shared. 2623 bool HasG0 = Args.hasArg(options::OPT_shared); 2624 if (auto G = getSmallDataThreshold(Args)) 2625 HasG0 = G.getValue() == 0; 2626 2627 const std::string CpuVer = GetTargetCPUVersion(Args).str(); 2628 for (auto &Dir : RootDirs) { 2629 std::string LibDir = Dir + "/hexagon/lib"; 2630 std::string LibDirCpu = LibDir + '/' + CpuVer; 2631 if (HasG0) { 2632 if (HasPIC) 2633 LibPaths.push_back(LibDirCpu + "/G0/pic"); 2634 LibPaths.push_back(LibDirCpu + "/G0"); 2635 } 2636 LibPaths.push_back(LibDirCpu); 2637 LibPaths.push_back(LibDir); 2638 } 2639 } 2640 2641 HexagonToolChain::HexagonToolChain(const Driver &D, const llvm::Triple &Triple, 2642 const llvm::opt::ArgList &Args) 2643 : Linux(D, Triple, Args) { 2644 const std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(), 2645 D.PrefixDirs); 2646 2647 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to 2648 // program paths 2649 const std::string BinDir(TargetDir + "/bin"); 2650 if (D.getVFS().exists(BinDir)) 2651 getProgramPaths().push_back(BinDir); 2652 2653 ToolChain::path_list &LibPaths = getFilePaths(); 2654 2655 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets 2656 // 'elf' OS type, so the Linux paths are not appropriate. When we actually 2657 // support 'linux' we'll need to fix this up 2658 LibPaths.clear(); 2659 getHexagonLibraryPaths(Args, LibPaths); 2660 } 2661 2662 HexagonToolChain::~HexagonToolChain() {} 2663 2664 Tool *HexagonToolChain::buildAssembler() const { 2665 return new tools::hexagon::Assembler(*this); 2666 } 2667 2668 Tool *HexagonToolChain::buildLinker() const { 2669 return new tools::hexagon::Linker(*this); 2670 } 2671 2672 void HexagonToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 2673 ArgStringList &CC1Args) const { 2674 if (DriverArgs.hasArg(options::OPT_nostdinc) || 2675 DriverArgs.hasArg(options::OPT_nostdlibinc)) 2676 return; 2677 2678 const Driver &D = getDriver(); 2679 std::string TargetDir = getHexagonTargetDir(D.getInstalledDir(), 2680 D.PrefixDirs); 2681 addExternCSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include"); 2682 } 2683 2684 void HexagonToolChain::AddClangCXXStdlibIncludeArgs( 2685 const ArgList &DriverArgs, ArgStringList &CC1Args) const { 2686 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2687 DriverArgs.hasArg(options::OPT_nostdincxx)) 2688 return; 2689 2690 const Driver &D = getDriver(); 2691 std::string TargetDir = getHexagonTargetDir(D.InstalledDir, D.PrefixDirs); 2692 addSystemInclude(DriverArgs, CC1Args, TargetDir + "/hexagon/include/c++"); 2693 } 2694 2695 ToolChain::CXXStdlibType 2696 HexagonToolChain::GetCXXStdlibType(const ArgList &Args) const { 2697 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 2698 if (!A) 2699 return ToolChain::CST_Libstdcxx; 2700 2701 StringRef Value = A->getValue(); 2702 if (Value != "libstdc++") 2703 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 2704 2705 return ToolChain::CST_Libstdcxx; 2706 } 2707 2708 // 2709 // Returns the default CPU for Hexagon. This is the default compilation target 2710 // if no Hexagon processor is selected at the command-line. 2711 // 2712 const StringRef HexagonToolChain::GetDefaultCPU() { 2713 return "hexagonv60"; 2714 } 2715 2716 const StringRef HexagonToolChain::GetTargetCPUVersion(const ArgList &Args) { 2717 Arg *CpuArg = nullptr; 2718 2719 for (auto &A : Args) { 2720 if (A->getOption().matches(options::OPT_mcpu_EQ)) { 2721 CpuArg = A; 2722 A->claim(); 2723 } 2724 } 2725 2726 StringRef CPU = CpuArg ? CpuArg->getValue() : GetDefaultCPU(); 2727 if (CPU.startswith("hexagon")) 2728 return CPU.substr(sizeof("hexagon") - 1); 2729 return CPU; 2730 } 2731 // End Hexagon 2732 2733 /// AMDGPU Toolchain 2734 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple, 2735 const ArgList &Args) 2736 : Generic_ELF(D, Triple, Args) { } 2737 2738 Tool *AMDGPUToolChain::buildLinker() const { 2739 return new tools::amdgpu::Linker(*this); 2740 } 2741 // End AMDGPU 2742 2743 /// NaCl Toolchain 2744 NaClToolChain::NaClToolChain(const Driver &D, const llvm::Triple &Triple, 2745 const ArgList &Args) 2746 : Generic_ELF(D, Triple, Args) { 2747 2748 // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the 2749 // default paths, and must instead only use the paths provided 2750 // with this toolchain based on architecture. 2751 path_list &file_paths = getFilePaths(); 2752 path_list &prog_paths = getProgramPaths(); 2753 2754 file_paths.clear(); 2755 prog_paths.clear(); 2756 2757 // Path for library files (libc.a, ...) 2758 std::string FilePath(getDriver().Dir + "/../"); 2759 2760 // Path for tools (clang, ld, etc..) 2761 std::string ProgPath(getDriver().Dir + "/../"); 2762 2763 // Path for toolchain libraries (libgcc.a, ...) 2764 std::string ToolPath(getDriver().ResourceDir + "/lib/"); 2765 2766 switch (Triple.getArch()) { 2767 case llvm::Triple::x86: 2768 file_paths.push_back(FilePath + "x86_64-nacl/lib32"); 2769 file_paths.push_back(FilePath + "i686-nacl/usr/lib"); 2770 prog_paths.push_back(ProgPath + "x86_64-nacl/bin"); 2771 file_paths.push_back(ToolPath + "i686-nacl"); 2772 break; 2773 case llvm::Triple::x86_64: 2774 file_paths.push_back(FilePath + "x86_64-nacl/lib"); 2775 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib"); 2776 prog_paths.push_back(ProgPath + "x86_64-nacl/bin"); 2777 file_paths.push_back(ToolPath + "x86_64-nacl"); 2778 break; 2779 case llvm::Triple::arm: 2780 file_paths.push_back(FilePath + "arm-nacl/lib"); 2781 file_paths.push_back(FilePath + "arm-nacl/usr/lib"); 2782 prog_paths.push_back(ProgPath + "arm-nacl/bin"); 2783 file_paths.push_back(ToolPath + "arm-nacl"); 2784 break; 2785 case llvm::Triple::mipsel: 2786 file_paths.push_back(FilePath + "mipsel-nacl/lib"); 2787 file_paths.push_back(FilePath + "mipsel-nacl/usr/lib"); 2788 prog_paths.push_back(ProgPath + "bin"); 2789 file_paths.push_back(ToolPath + "mipsel-nacl"); 2790 break; 2791 default: 2792 break; 2793 } 2794 2795 NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s"); 2796 } 2797 2798 void NaClToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 2799 ArgStringList &CC1Args) const { 2800 const Driver &D = getDriver(); 2801 if (DriverArgs.hasArg(options::OPT_nostdinc)) 2802 return; 2803 2804 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { 2805 SmallString<128> P(D.ResourceDir); 2806 llvm::sys::path::append(P, "include"); 2807 addSystemInclude(DriverArgs, CC1Args, P.str()); 2808 } 2809 2810 if (DriverArgs.hasArg(options::OPT_nostdlibinc)) 2811 return; 2812 2813 SmallString<128> P(D.Dir + "/../"); 2814 switch (getTriple().getArch()) { 2815 case llvm::Triple::x86: 2816 // x86 is special because multilib style uses x86_64-nacl/include for libc 2817 // headers but the SDK wants i686-nacl/usr/include. The other architectures 2818 // have the same substring. 2819 llvm::sys::path::append(P, "i686-nacl/usr/include"); 2820 addSystemInclude(DriverArgs, CC1Args, P.str()); 2821 llvm::sys::path::remove_filename(P); 2822 llvm::sys::path::remove_filename(P); 2823 llvm::sys::path::remove_filename(P); 2824 llvm::sys::path::append(P, "x86_64-nacl/include"); 2825 addSystemInclude(DriverArgs, CC1Args, P.str()); 2826 return; 2827 case llvm::Triple::arm: 2828 llvm::sys::path::append(P, "arm-nacl/usr/include"); 2829 break; 2830 case llvm::Triple::x86_64: 2831 llvm::sys::path::append(P, "x86_64-nacl/usr/include"); 2832 break; 2833 case llvm::Triple::mipsel: 2834 llvm::sys::path::append(P, "mipsel-nacl/usr/include"); 2835 break; 2836 default: 2837 return; 2838 } 2839 2840 addSystemInclude(DriverArgs, CC1Args, P.str()); 2841 llvm::sys::path::remove_filename(P); 2842 llvm::sys::path::remove_filename(P); 2843 llvm::sys::path::append(P, "include"); 2844 addSystemInclude(DriverArgs, CC1Args, P.str()); 2845 } 2846 2847 void NaClToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 2848 ArgStringList &CmdArgs) const { 2849 // Check for -stdlib= flags. We only support libc++ but this consumes the arg 2850 // if the value is libc++, and emits an error for other values. 2851 GetCXXStdlibType(Args); 2852 CmdArgs.push_back("-lc++"); 2853 } 2854 2855 void NaClToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2856 ArgStringList &CC1Args) const { 2857 const Driver &D = getDriver(); 2858 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2859 DriverArgs.hasArg(options::OPT_nostdincxx)) 2860 return; 2861 2862 // Check for -stdlib= flags. We only support libc++ but this consumes the arg 2863 // if the value is libc++, and emits an error for other values. 2864 GetCXXStdlibType(DriverArgs); 2865 2866 SmallString<128> P(D.Dir + "/../"); 2867 switch (getTriple().getArch()) { 2868 case llvm::Triple::arm: 2869 llvm::sys::path::append(P, "arm-nacl/include/c++/v1"); 2870 addSystemInclude(DriverArgs, CC1Args, P.str()); 2871 break; 2872 case llvm::Triple::x86: 2873 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1"); 2874 addSystemInclude(DriverArgs, CC1Args, P.str()); 2875 break; 2876 case llvm::Triple::x86_64: 2877 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1"); 2878 addSystemInclude(DriverArgs, CC1Args, P.str()); 2879 break; 2880 case llvm::Triple::mipsel: 2881 llvm::sys::path::append(P, "mipsel-nacl/include/c++/v1"); 2882 addSystemInclude(DriverArgs, CC1Args, P.str()); 2883 break; 2884 default: 2885 break; 2886 } 2887 } 2888 2889 ToolChain::CXXStdlibType 2890 NaClToolChain::GetCXXStdlibType(const ArgList &Args) const { 2891 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 2892 StringRef Value = A->getValue(); 2893 if (Value == "libc++") 2894 return ToolChain::CST_Libcxx; 2895 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 2896 } 2897 2898 return ToolChain::CST_Libcxx; 2899 } 2900 2901 std::string 2902 NaClToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 2903 types::ID InputType) const { 2904 llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType)); 2905 if (TheTriple.getArch() == llvm::Triple::arm && 2906 TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment) 2907 TheTriple.setEnvironment(llvm::Triple::GNUEABIHF); 2908 return TheTriple.getTriple(); 2909 } 2910 2911 Tool *NaClToolChain::buildLinker() const { 2912 return new tools::nacltools::Linker(*this); 2913 } 2914 2915 Tool *NaClToolChain::buildAssembler() const { 2916 if (getTriple().getArch() == llvm::Triple::arm) 2917 return new tools::nacltools::AssemblerARM(*this); 2918 return new tools::gnutools::Assembler(*this); 2919 } 2920 // End NaCl 2921 2922 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform 2923 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target. 2924 /// Currently does not support anything else but compilation. 2925 2926 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple &Triple, 2927 const ArgList &Args) 2928 : ToolChain(D, Triple, Args) { 2929 // Path mangling to find libexec 2930 std::string Path(getDriver().Dir); 2931 2932 Path += "/../libexec"; 2933 getProgramPaths().push_back(Path); 2934 } 2935 2936 TCEToolChain::~TCEToolChain() {} 2937 2938 bool TCEToolChain::IsMathErrnoDefault() const { return true; } 2939 2940 bool TCEToolChain::isPICDefault() const { return false; } 2941 2942 bool TCEToolChain::isPIEDefault() const { return false; } 2943 2944 bool TCEToolChain::isPICDefaultForced() const { return false; } 2945 2946 // CloudABI - CloudABI tool chain which can call ld(1) directly. 2947 2948 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple, 2949 const ArgList &Args) 2950 : Generic_ELF(D, Triple, Args) { 2951 SmallString<128> P(getDriver().Dir); 2952 llvm::sys::path::append(P, "..", getTriple().str(), "lib"); 2953 getFilePaths().push_back(P.str()); 2954 } 2955 2956 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2957 ArgStringList &CC1Args) const { 2958 if (DriverArgs.hasArg(options::OPT_nostdlibinc) && 2959 DriverArgs.hasArg(options::OPT_nostdincxx)) 2960 return; 2961 2962 SmallString<128> P(getDriver().Dir); 2963 llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1"); 2964 addSystemInclude(DriverArgs, CC1Args, P.str()); 2965 } 2966 2967 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args, 2968 ArgStringList &CmdArgs) const { 2969 CmdArgs.push_back("-lc++"); 2970 CmdArgs.push_back("-lc++abi"); 2971 CmdArgs.push_back("-lunwind"); 2972 } 2973 2974 Tool *CloudABI::buildLinker() const { 2975 return new tools::cloudabi::Linker(*this); 2976 } 2977 2978 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly. 2979 2980 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple, 2981 const ArgList &Args) 2982 : Generic_ELF(D, Triple, Args) { 2983 getFilePaths().push_back(getDriver().Dir + "/../lib"); 2984 getFilePaths().push_back("/usr/lib"); 2985 } 2986 2987 Tool *OpenBSD::buildAssembler() const { 2988 return new tools::openbsd::Assembler(*this); 2989 } 2990 2991 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); } 2992 2993 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly. 2994 2995 Bitrig::Bitrig(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) 2996 : Generic_ELF(D, Triple, Args) { 2997 getFilePaths().push_back(getDriver().Dir + "/../lib"); 2998 getFilePaths().push_back("/usr/lib"); 2999 } 3000 3001 Tool *Bitrig::buildAssembler() const { 3002 return new tools::bitrig::Assembler(*this); 3003 } 3004 3005 Tool *Bitrig::buildLinker() const { return new tools::bitrig::Linker(*this); } 3006 3007 ToolChain::CXXStdlibType Bitrig::GetCXXStdlibType(const ArgList &Args) const { 3008 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 3009 StringRef Value = A->getValue(); 3010 if (Value == "libstdc++") 3011 return ToolChain::CST_Libstdcxx; 3012 if (Value == "libc++") 3013 return ToolChain::CST_Libcxx; 3014 3015 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 3016 } 3017 return ToolChain::CST_Libcxx; 3018 } 3019 3020 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3021 ArgStringList &CC1Args) const { 3022 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 3023 DriverArgs.hasArg(options::OPT_nostdincxx)) 3024 return; 3025 3026 switch (GetCXXStdlibType(DriverArgs)) { 3027 case ToolChain::CST_Libcxx: 3028 addSystemInclude(DriverArgs, CC1Args, 3029 getDriver().SysRoot + "/usr/include/c++/v1"); 3030 break; 3031 case ToolChain::CST_Libstdcxx: 3032 addSystemInclude(DriverArgs, CC1Args, 3033 getDriver().SysRoot + "/usr/include/c++/stdc++"); 3034 addSystemInclude(DriverArgs, CC1Args, 3035 getDriver().SysRoot + "/usr/include/c++/stdc++/backward"); 3036 3037 StringRef Triple = getTriple().str(); 3038 if (Triple.startswith("amd64")) 3039 addSystemInclude(DriverArgs, CC1Args, 3040 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" + 3041 Triple.substr(5)); 3042 else 3043 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + 3044 "/usr/include/c++/stdc++/" + 3045 Triple); 3046 break; 3047 } 3048 } 3049 3050 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args, 3051 ArgStringList &CmdArgs) const { 3052 switch (GetCXXStdlibType(Args)) { 3053 case ToolChain::CST_Libcxx: 3054 CmdArgs.push_back("-lc++"); 3055 CmdArgs.push_back("-lc++abi"); 3056 CmdArgs.push_back("-lpthread"); 3057 break; 3058 case ToolChain::CST_Libstdcxx: 3059 CmdArgs.push_back("-lstdc++"); 3060 break; 3061 } 3062 } 3063 3064 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly. 3065 3066 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple, 3067 const ArgList &Args) 3068 : Generic_ELF(D, Triple, Args) { 3069 3070 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall 3071 // back to '/usr/lib' if it doesn't exist. 3072 if ((Triple.getArch() == llvm::Triple::x86 || 3073 Triple.getArch() == llvm::Triple::ppc) && 3074 D.getVFS().exists(getDriver().SysRoot + "/usr/lib32/crt1.o")) 3075 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32"); 3076 else 3077 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib"); 3078 } 3079 3080 ToolChain::CXXStdlibType FreeBSD::GetCXXStdlibType(const ArgList &Args) const { 3081 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 3082 StringRef Value = A->getValue(); 3083 if (Value == "libstdc++") 3084 return ToolChain::CST_Libstdcxx; 3085 if (Value == "libc++") 3086 return ToolChain::CST_Libcxx; 3087 3088 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 3089 } 3090 if (getTriple().getOSMajorVersion() >= 10) 3091 return ToolChain::CST_Libcxx; 3092 return ToolChain::CST_Libstdcxx; 3093 } 3094 3095 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3096 ArgStringList &CC1Args) const { 3097 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 3098 DriverArgs.hasArg(options::OPT_nostdincxx)) 3099 return; 3100 3101 switch (GetCXXStdlibType(DriverArgs)) { 3102 case ToolChain::CST_Libcxx: 3103 addSystemInclude(DriverArgs, CC1Args, 3104 getDriver().SysRoot + "/usr/include/c++/v1"); 3105 break; 3106 case ToolChain::CST_Libstdcxx: 3107 addSystemInclude(DriverArgs, CC1Args, 3108 getDriver().SysRoot + "/usr/include/c++/4.2"); 3109 addSystemInclude(DriverArgs, CC1Args, 3110 getDriver().SysRoot + "/usr/include/c++/4.2/backward"); 3111 break; 3112 } 3113 } 3114 3115 Tool *FreeBSD::buildAssembler() const { 3116 return new tools::freebsd::Assembler(*this); 3117 } 3118 3119 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); } 3120 3121 bool FreeBSD::UseSjLjExceptions(const ArgList &Args) const { 3122 // FreeBSD uses SjLj exceptions on ARM oabi. 3123 switch (getTriple().getEnvironment()) { 3124 case llvm::Triple::GNUEABIHF: 3125 case llvm::Triple::GNUEABI: 3126 case llvm::Triple::EABI: 3127 return false; 3128 3129 default: 3130 return (getTriple().getArch() == llvm::Triple::arm || 3131 getTriple().getArch() == llvm::Triple::thumb); 3132 } 3133 } 3134 3135 bool FreeBSD::HasNativeLLVMSupport() const { return true; } 3136 3137 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); } 3138 3139 SanitizerMask FreeBSD::getSupportedSanitizers() const { 3140 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86; 3141 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; 3142 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 || 3143 getTriple().getArch() == llvm::Triple::mips64el; 3144 SanitizerMask Res = ToolChain::getSupportedSanitizers(); 3145 Res |= SanitizerKind::Address; 3146 Res |= SanitizerKind::Vptr; 3147 if (IsX86_64 || IsMIPS64) { 3148 Res |= SanitizerKind::Leak; 3149 Res |= SanitizerKind::Thread; 3150 } 3151 if (IsX86 || IsX86_64) { 3152 Res |= SanitizerKind::SafeStack; 3153 } 3154 return Res; 3155 } 3156 3157 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly. 3158 3159 NetBSD::NetBSD(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) 3160 : Generic_ELF(D, Triple, Args) { 3161 3162 if (getDriver().UseStdLib) { 3163 // When targeting a 32-bit platform, try the special directory used on 3164 // 64-bit hosts, and only fall back to the main library directory if that 3165 // doesn't work. 3166 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure 3167 // what all logic is needed to emulate the '=' prefix here. 3168 switch (Triple.getArch()) { 3169 case llvm::Triple::x86: 3170 getFilePaths().push_back("=/usr/lib/i386"); 3171 break; 3172 case llvm::Triple::arm: 3173 case llvm::Triple::armeb: 3174 case llvm::Triple::thumb: 3175 case llvm::Triple::thumbeb: 3176 switch (Triple.getEnvironment()) { 3177 case llvm::Triple::EABI: 3178 case llvm::Triple::GNUEABI: 3179 getFilePaths().push_back("=/usr/lib/eabi"); 3180 break; 3181 case llvm::Triple::EABIHF: 3182 case llvm::Triple::GNUEABIHF: 3183 getFilePaths().push_back("=/usr/lib/eabihf"); 3184 break; 3185 default: 3186 getFilePaths().push_back("=/usr/lib/oabi"); 3187 break; 3188 } 3189 break; 3190 case llvm::Triple::mips64: 3191 case llvm::Triple::mips64el: 3192 if (tools::mips::hasMipsAbiArg(Args, "o32")) 3193 getFilePaths().push_back("=/usr/lib/o32"); 3194 else if (tools::mips::hasMipsAbiArg(Args, "64")) 3195 getFilePaths().push_back("=/usr/lib/64"); 3196 break; 3197 case llvm::Triple::ppc: 3198 getFilePaths().push_back("=/usr/lib/powerpc"); 3199 break; 3200 case llvm::Triple::sparc: 3201 getFilePaths().push_back("=/usr/lib/sparc"); 3202 break; 3203 default: 3204 break; 3205 } 3206 3207 getFilePaths().push_back("=/usr/lib"); 3208 } 3209 } 3210 3211 Tool *NetBSD::buildAssembler() const { 3212 return new tools::netbsd::Assembler(*this); 3213 } 3214 3215 Tool *NetBSD::buildLinker() const { return new tools::netbsd::Linker(*this); } 3216 3217 ToolChain::CXXStdlibType NetBSD::GetCXXStdlibType(const ArgList &Args) const { 3218 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 3219 StringRef Value = A->getValue(); 3220 if (Value == "libstdc++") 3221 return ToolChain::CST_Libstdcxx; 3222 if (Value == "libc++") 3223 return ToolChain::CST_Libcxx; 3224 3225 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 3226 } 3227 3228 unsigned Major, Minor, Micro; 3229 getTriple().getOSVersion(Major, Minor, Micro); 3230 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) { 3231 switch (getArch()) { 3232 case llvm::Triple::aarch64: 3233 case llvm::Triple::arm: 3234 case llvm::Triple::armeb: 3235 case llvm::Triple::thumb: 3236 case llvm::Triple::thumbeb: 3237 case llvm::Triple::ppc: 3238 case llvm::Triple::ppc64: 3239 case llvm::Triple::ppc64le: 3240 case llvm::Triple::x86: 3241 case llvm::Triple::x86_64: 3242 return ToolChain::CST_Libcxx; 3243 default: 3244 break; 3245 } 3246 } 3247 return ToolChain::CST_Libstdcxx; 3248 } 3249 3250 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3251 ArgStringList &CC1Args) const { 3252 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 3253 DriverArgs.hasArg(options::OPT_nostdincxx)) 3254 return; 3255 3256 switch (GetCXXStdlibType(DriverArgs)) { 3257 case ToolChain::CST_Libcxx: 3258 addSystemInclude(DriverArgs, CC1Args, 3259 getDriver().SysRoot + "/usr/include/c++/"); 3260 break; 3261 case ToolChain::CST_Libstdcxx: 3262 addSystemInclude(DriverArgs, CC1Args, 3263 getDriver().SysRoot + "/usr/include/g++"); 3264 addSystemInclude(DriverArgs, CC1Args, 3265 getDriver().SysRoot + "/usr/include/g++/backward"); 3266 break; 3267 } 3268 } 3269 3270 /// Minix - Minix tool chain which can call as(1) and ld(1) directly. 3271 3272 Minix::Minix(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) 3273 : Generic_ELF(D, Triple, Args) { 3274 getFilePaths().push_back(getDriver().Dir + "/../lib"); 3275 getFilePaths().push_back("/usr/lib"); 3276 } 3277 3278 Tool *Minix::buildAssembler() const { 3279 return new tools::minix::Assembler(*this); 3280 } 3281 3282 Tool *Minix::buildLinker() const { return new tools::minix::Linker(*this); } 3283 3284 static void addPathIfExists(const Driver &D, const Twine &Path, 3285 ToolChain::path_list &Paths) { 3286 if (D.getVFS().exists(Path)) 3287 Paths.push_back(Path.str()); 3288 } 3289 3290 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly. 3291 3292 Solaris::Solaris(const Driver &D, const llvm::Triple &Triple, 3293 const ArgList &Args) 3294 : Generic_GCC(D, Triple, Args) { 3295 3296 GCCInstallation.init(Triple, Args); 3297 3298 path_list &Paths = getFilePaths(); 3299 if (GCCInstallation.isValid()) 3300 addPathIfExists(D, GCCInstallation.getInstallPath(), Paths); 3301 3302 addPathIfExists(D, getDriver().getInstalledDir(), Paths); 3303 if (getDriver().getInstalledDir() != getDriver().Dir) 3304 addPathIfExists(D, getDriver().Dir, Paths); 3305 3306 addPathIfExists(D, getDriver().SysRoot + getDriver().Dir + "/../lib", Paths); 3307 3308 std::string LibPath = "/usr/lib/"; 3309 switch (Triple.getArch()) { 3310 case llvm::Triple::x86: 3311 case llvm::Triple::sparc: 3312 break; 3313 case llvm::Triple::x86_64: 3314 LibPath += "amd64/"; 3315 break; 3316 case llvm::Triple::sparcv9: 3317 LibPath += "sparcv9/"; 3318 break; 3319 default: 3320 llvm_unreachable("Unsupported architecture"); 3321 } 3322 3323 addPathIfExists(D, getDriver().SysRoot + LibPath, Paths); 3324 } 3325 3326 Tool *Solaris::buildAssembler() const { 3327 return new tools::solaris::Assembler(*this); 3328 } 3329 3330 Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); } 3331 3332 void Solaris::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3333 ArgStringList &CC1Args) const { 3334 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 3335 DriverArgs.hasArg(options::OPT_nostdincxx)) 3336 return; 3337 3338 // Include the support directory for things like xlocale and fudged system 3339 // headers. 3340 addSystemInclude(DriverArgs, CC1Args, "/usr/include/c++/v1/support/solaris"); 3341 3342 if (GCCInstallation.isValid()) { 3343 GCCVersion Version = GCCInstallation.getVersion(); 3344 addSystemInclude(DriverArgs, CC1Args, 3345 getDriver().SysRoot + "/usr/gcc/" + 3346 Version.MajorStr + "." + 3347 Version.MinorStr + 3348 "/include/c++/" + Version.Text); 3349 addSystemInclude(DriverArgs, CC1Args, 3350 getDriver().SysRoot + "/usr/gcc/" + Version.MajorStr + 3351 "." + Version.MinorStr + "/include/c++/" + 3352 Version.Text + "/" + 3353 GCCInstallation.getTriple().str()); 3354 } 3355 } 3356 3357 /// Distribution (very bare-bones at the moment). 3358 3359 enum Distro { 3360 // NB: Releases of a particular Linux distro should be kept together 3361 // in this enum, because some tests are done by integer comparison against 3362 // the first and last known member in the family, e.g. IsRedHat(). 3363 ArchLinux, 3364 DebianLenny, 3365 DebianSqueeze, 3366 DebianWheezy, 3367 DebianJessie, 3368 DebianStretch, 3369 Exherbo, 3370 RHEL4, 3371 RHEL5, 3372 RHEL6, 3373 RHEL7, 3374 Fedora, 3375 OpenSUSE, 3376 UbuntuHardy, 3377 UbuntuIntrepid, 3378 UbuntuJaunty, 3379 UbuntuKarmic, 3380 UbuntuLucid, 3381 UbuntuMaverick, 3382 UbuntuNatty, 3383 UbuntuOneiric, 3384 UbuntuPrecise, 3385 UbuntuQuantal, 3386 UbuntuRaring, 3387 UbuntuSaucy, 3388 UbuntuTrusty, 3389 UbuntuUtopic, 3390 UbuntuVivid, 3391 UbuntuWily, 3392 UbuntuXenial, 3393 UnknownDistro 3394 }; 3395 3396 static bool IsRedhat(enum Distro Distro) { 3397 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7); 3398 } 3399 3400 static bool IsOpenSUSE(enum Distro Distro) { return Distro == OpenSUSE; } 3401 3402 static bool IsDebian(enum Distro Distro) { 3403 return Distro >= DebianLenny && Distro <= DebianStretch; 3404 } 3405 3406 static bool IsUbuntu(enum Distro Distro) { 3407 return Distro >= UbuntuHardy && Distro <= UbuntuXenial; 3408 } 3409 3410 static Distro DetectDistro(const Driver &D, llvm::Triple::ArchType Arch) { 3411 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File = 3412 llvm::MemoryBuffer::getFile("/etc/lsb-release"); 3413 if (File) { 3414 StringRef Data = File.get()->getBuffer(); 3415 SmallVector<StringRef, 16> Lines; 3416 Data.split(Lines, "\n"); 3417 Distro Version = UnknownDistro; 3418 for (StringRef Line : Lines) 3419 if (Version == UnknownDistro && Line.startswith("DISTRIB_CODENAME=")) 3420 Version = llvm::StringSwitch<Distro>(Line.substr(17)) 3421 .Case("hardy", UbuntuHardy) 3422 .Case("intrepid", UbuntuIntrepid) 3423 .Case("jaunty", UbuntuJaunty) 3424 .Case("karmic", UbuntuKarmic) 3425 .Case("lucid", UbuntuLucid) 3426 .Case("maverick", UbuntuMaverick) 3427 .Case("natty", UbuntuNatty) 3428 .Case("oneiric", UbuntuOneiric) 3429 .Case("precise", UbuntuPrecise) 3430 .Case("quantal", UbuntuQuantal) 3431 .Case("raring", UbuntuRaring) 3432 .Case("saucy", UbuntuSaucy) 3433 .Case("trusty", UbuntuTrusty) 3434 .Case("utopic", UbuntuUtopic) 3435 .Case("vivid", UbuntuVivid) 3436 .Case("wily", UbuntuWily) 3437 .Case("xenial", UbuntuXenial) 3438 .Default(UnknownDistro); 3439 return Version; 3440 } 3441 3442 File = llvm::MemoryBuffer::getFile("/etc/redhat-release"); 3443 if (File) { 3444 StringRef Data = File.get()->getBuffer(); 3445 if (Data.startswith("Fedora release")) 3446 return Fedora; 3447 if (Data.startswith("Red Hat Enterprise Linux") || 3448 Data.startswith("CentOS")) { 3449 if (Data.find("release 7") != StringRef::npos) 3450 return RHEL7; 3451 else if (Data.find("release 6") != StringRef::npos) 3452 return RHEL6; 3453 else if (Data.find("release 5") != StringRef::npos) 3454 return RHEL5; 3455 else if (Data.find("release 4") != StringRef::npos) 3456 return RHEL4; 3457 } 3458 return UnknownDistro; 3459 } 3460 3461 File = llvm::MemoryBuffer::getFile("/etc/debian_version"); 3462 if (File) { 3463 StringRef Data = File.get()->getBuffer(); 3464 if (Data[0] == '5') 3465 return DebianLenny; 3466 else if (Data.startswith("squeeze/sid") || Data[0] == '6') 3467 return DebianSqueeze; 3468 else if (Data.startswith("wheezy/sid") || Data[0] == '7') 3469 return DebianWheezy; 3470 else if (Data.startswith("jessie/sid") || Data[0] == '8') 3471 return DebianJessie; 3472 else if (Data.startswith("stretch/sid") || Data[0] == '9') 3473 return DebianStretch; 3474 return UnknownDistro; 3475 } 3476 3477 if (D.getVFS().exists("/etc/SuSE-release")) 3478 return OpenSUSE; 3479 3480 if (D.getVFS().exists("/etc/exherbo-release")) 3481 return Exherbo; 3482 3483 if (D.getVFS().exists("/etc/arch-release")) 3484 return ArchLinux; 3485 3486 return UnknownDistro; 3487 } 3488 3489 /// \brief Get our best guess at the multiarch triple for a target. 3490 /// 3491 /// Debian-based systems are starting to use a multiarch setup where they use 3492 /// a target-triple directory in the library and header search paths. 3493 /// Unfortunately, this triple does not align with the vanilla target triple, 3494 /// so we provide a rough mapping here. 3495 static std::string getMultiarchTriple(const Driver &D, 3496 const llvm::Triple &TargetTriple, 3497 StringRef SysRoot) { 3498 llvm::Triple::EnvironmentType TargetEnvironment = 3499 TargetTriple.getEnvironment(); 3500 3501 // For most architectures, just use whatever we have rather than trying to be 3502 // clever. 3503 switch (TargetTriple.getArch()) { 3504 default: 3505 break; 3506 3507 // We use the existence of '/lib/<triple>' as a directory to detect some 3508 // common linux triples that don't quite match the Clang triple for both 3509 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these 3510 // regardless of what the actual target triple is. 3511 case llvm::Triple::arm: 3512 case llvm::Triple::thumb: 3513 if (TargetEnvironment == llvm::Triple::GNUEABIHF) { 3514 if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf")) 3515 return "arm-linux-gnueabihf"; 3516 } else { 3517 if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi")) 3518 return "arm-linux-gnueabi"; 3519 } 3520 break; 3521 case llvm::Triple::armeb: 3522 case llvm::Triple::thumbeb: 3523 if (TargetEnvironment == llvm::Triple::GNUEABIHF) { 3524 if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf")) 3525 return "armeb-linux-gnueabihf"; 3526 } else { 3527 if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi")) 3528 return "armeb-linux-gnueabi"; 3529 } 3530 break; 3531 case llvm::Triple::x86: 3532 if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu")) 3533 return "i386-linux-gnu"; 3534 break; 3535 case llvm::Triple::x86_64: 3536 // We don't want this for x32, otherwise it will match x86_64 libs 3537 if (TargetEnvironment != llvm::Triple::GNUX32 && 3538 D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu")) 3539 return "x86_64-linux-gnu"; 3540 break; 3541 case llvm::Triple::aarch64: 3542 if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu")) 3543 return "aarch64-linux-gnu"; 3544 break; 3545 case llvm::Triple::aarch64_be: 3546 if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu")) 3547 return "aarch64_be-linux-gnu"; 3548 break; 3549 case llvm::Triple::mips: 3550 if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu")) 3551 return "mips-linux-gnu"; 3552 break; 3553 case llvm::Triple::mipsel: 3554 if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu")) 3555 return "mipsel-linux-gnu"; 3556 break; 3557 case llvm::Triple::mips64: 3558 if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu")) 3559 return "mips64-linux-gnu"; 3560 if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64")) 3561 return "mips64-linux-gnuabi64"; 3562 break; 3563 case llvm::Triple::mips64el: 3564 if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu")) 3565 return "mips64el-linux-gnu"; 3566 if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64")) 3567 return "mips64el-linux-gnuabi64"; 3568 break; 3569 case llvm::Triple::ppc: 3570 if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe")) 3571 return "powerpc-linux-gnuspe"; 3572 if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu")) 3573 return "powerpc-linux-gnu"; 3574 break; 3575 case llvm::Triple::ppc64: 3576 if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu")) 3577 return "powerpc64-linux-gnu"; 3578 break; 3579 case llvm::Triple::ppc64le: 3580 if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu")) 3581 return "powerpc64le-linux-gnu"; 3582 break; 3583 case llvm::Triple::sparc: 3584 if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu")) 3585 return "sparc-linux-gnu"; 3586 break; 3587 case llvm::Triple::sparcv9: 3588 if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu")) 3589 return "sparc64-linux-gnu"; 3590 break; 3591 case llvm::Triple::systemz: 3592 if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu")) 3593 return "s390x-linux-gnu"; 3594 break; 3595 } 3596 return TargetTriple.str(); 3597 } 3598 3599 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) { 3600 if (isMipsArch(Triple.getArch())) { 3601 // lib32 directory has a special meaning on MIPS targets. 3602 // It contains N32 ABI binaries. Use this folder if produce 3603 // code for N32 ABI only. 3604 if (tools::mips::hasMipsAbiArg(Args, "n32")) 3605 return "lib32"; 3606 return Triple.isArch32Bit() ? "lib" : "lib64"; 3607 } 3608 3609 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and 3610 // using that variant while targeting other architectures causes problems 3611 // because the libraries are laid out in shared system roots that can't cope 3612 // with a 'lib32' library search path being considered. So we only enable 3613 // them when we know we may need it. 3614 // 3615 // FIXME: This is a bit of a hack. We should really unify this code for 3616 // reasoning about oslibdir spellings with the lib dir spellings in the 3617 // GCCInstallationDetector, but that is a more significant refactoring. 3618 if (Triple.getArch() == llvm::Triple::x86 || 3619 Triple.getArch() == llvm::Triple::ppc) 3620 return "lib32"; 3621 3622 if (Triple.getArch() == llvm::Triple::x86_64 && 3623 Triple.getEnvironment() == llvm::Triple::GNUX32) 3624 return "libx32"; 3625 3626 return Triple.isArch32Bit() ? "lib" : "lib64"; 3627 } 3628 3629 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) 3630 : Generic_ELF(D, Triple, Args) { 3631 GCCInstallation.init(Triple, Args); 3632 CudaInstallation.init(Triple, Args); 3633 Multilibs = GCCInstallation.getMultilibs(); 3634 llvm::Triple::ArchType Arch = Triple.getArch(); 3635 std::string SysRoot = computeSysRoot(); 3636 3637 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at 3638 // least) put various tools in a triple-prefixed directory off of the parent 3639 // of the GCC installation. We use the GCC triple here to ensure that we end 3640 // up with tools that support the same amount of cross compiling as the 3641 // detected GCC installation. For example, if we find a GCC installation 3642 // targeting x86_64, but it is a bi-arch GCC installation, it can also be 3643 // used to target i386. 3644 // FIXME: This seems unlikely to be Linux-specific. 3645 ToolChain::path_list &PPaths = getProgramPaths(); 3646 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" + 3647 GCCInstallation.getTriple().str() + "/bin") 3648 .str()); 3649 3650 Distro Distro = DetectDistro(D, Arch); 3651 3652 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) { 3653 ExtraOpts.push_back("-z"); 3654 ExtraOpts.push_back("relro"); 3655 } 3656 3657 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) 3658 ExtraOpts.push_back("-X"); 3659 3660 const bool IsAndroid = Triple.isAndroid(); 3661 const bool IsMips = isMipsArch(Arch); 3662 3663 if (IsMips && !SysRoot.empty()) 3664 ExtraOpts.push_back("--sysroot=" + SysRoot); 3665 3666 // Do not use 'gnu' hash style for Mips targets because .gnu.hash 3667 // and the MIPS ABI require .dynsym to be sorted in different ways. 3668 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS 3669 // ABI requires a mapping between the GOT and the symbol table. 3670 // Android loader does not support .gnu.hash. 3671 if (!IsMips && !IsAndroid) { 3672 if (IsRedhat(Distro) || IsOpenSUSE(Distro) || 3673 (IsUbuntu(Distro) && Distro >= UbuntuMaverick)) 3674 ExtraOpts.push_back("--hash-style=gnu"); 3675 3676 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid || 3677 Distro == UbuntuJaunty || Distro == UbuntuKarmic) 3678 ExtraOpts.push_back("--hash-style=both"); 3679 } 3680 3681 if (IsRedhat(Distro)) 3682 ExtraOpts.push_back("--no-add-needed"); 3683 3684 if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) || 3685 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) || 3686 (IsUbuntu(Distro) && Distro >= UbuntuKarmic)) 3687 ExtraOpts.push_back("--build-id"); 3688 3689 if (IsOpenSUSE(Distro)) 3690 ExtraOpts.push_back("--enable-new-dtags"); 3691 3692 // The selection of paths to try here is designed to match the patterns which 3693 // the GCC driver itself uses, as this is part of the GCC-compatible driver. 3694 // This was determined by running GCC in a fake filesystem, creating all 3695 // possible permutations of these directories, and seeing which ones it added 3696 // to the link paths. 3697 path_list &Paths = getFilePaths(); 3698 3699 const std::string OSLibDir = getOSLibDir(Triple, Args); 3700 const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot); 3701 3702 // Add the multilib suffixed paths where they are available. 3703 if (GCCInstallation.isValid()) { 3704 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3705 const std::string &LibPath = GCCInstallation.getParentLibPath(); 3706 const Multilib &Multilib = GCCInstallation.getMultilib(); 3707 3708 // Sourcery CodeBench MIPS toolchain holds some libraries under 3709 // a biarch-like suffix of the GCC installation. 3710 addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(), 3711 Paths); 3712 3713 // GCC cross compiling toolchains will install target libraries which ship 3714 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as 3715 // any part of the GCC installation in 3716 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat 3717 // debatable, but is the reality today. We need to search this tree even 3718 // when we have a sysroot somewhere else. It is the responsibility of 3719 // whomever is doing the cross build targeting a sysroot using a GCC 3720 // installation that is *not* within the system root to ensure two things: 3721 // 3722 // 1) Any DSOs that are linked in from this tree or from the install path 3723 // above must be present on the system root and found via an 3724 // appropriate rpath. 3725 // 2) There must not be libraries installed into 3726 // <prefix>/<triple>/<libdir> unless they should be preferred over 3727 // those within the system root. 3728 // 3729 // Note that this matches the GCC behavior. See the below comment for where 3730 // Clang diverges from GCC's behavior. 3731 addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" + 3732 OSLibDir + Multilib.osSuffix(), 3733 Paths); 3734 3735 // If the GCC installation we found is inside of the sysroot, we want to 3736 // prefer libraries installed in the parent prefix of the GCC installation. 3737 // It is important to *not* use these paths when the GCC installation is 3738 // outside of the system root as that can pick up unintended libraries. 3739 // This usually happens when there is an external cross compiler on the 3740 // host system, and a more minimal sysroot available that is the target of 3741 // the cross. Note that GCC does include some of these directories in some 3742 // configurations but this seems somewhere between questionable and simply 3743 // a bug. 3744 if (StringRef(LibPath).startswith(SysRoot)) { 3745 addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths); 3746 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths); 3747 } 3748 } 3749 3750 // Similar to the logic for GCC above, if we currently running Clang inside 3751 // of the requested system root, add its parent library paths to 3752 // those searched. 3753 // FIXME: It's not clear whether we should use the driver's installed 3754 // directory ('Dir' below) or the ResourceDir. 3755 if (StringRef(D.Dir).startswith(SysRoot)) { 3756 addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths); 3757 addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths); 3758 } 3759 3760 addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths); 3761 addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths); 3762 addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths); 3763 addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths); 3764 3765 // Try walking via the GCC triple path in case of biarch or multiarch GCC 3766 // installations with strange symlinks. 3767 if (GCCInstallation.isValid()) { 3768 addPathIfExists(D, 3769 SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() + 3770 "/../../" + OSLibDir, 3771 Paths); 3772 3773 // Add the 'other' biarch variant path 3774 Multilib BiarchSibling; 3775 if (GCCInstallation.getBiarchSibling(BiarchSibling)) { 3776 addPathIfExists(D, GCCInstallation.getInstallPath() + 3777 BiarchSibling.gccSuffix(), 3778 Paths); 3779 } 3780 3781 // See comments above on the multilib variant for details of why this is 3782 // included even from outside the sysroot. 3783 const std::string &LibPath = GCCInstallation.getParentLibPath(); 3784 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3785 const Multilib &Multilib = GCCInstallation.getMultilib(); 3786 addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" + 3787 Multilib.osSuffix(), 3788 Paths); 3789 3790 // See comments above on the multilib variant for details of why this is 3791 // only included from within the sysroot. 3792 if (StringRef(LibPath).startswith(SysRoot)) 3793 addPathIfExists(D, LibPath, Paths); 3794 } 3795 3796 // Similar to the logic for GCC above, if we are currently running Clang 3797 // inside of the requested system root, add its parent library path to those 3798 // searched. 3799 // FIXME: It's not clear whether we should use the driver's installed 3800 // directory ('Dir' below) or the ResourceDir. 3801 if (StringRef(D.Dir).startswith(SysRoot)) 3802 addPathIfExists(D, D.Dir + "/../lib", Paths); 3803 3804 addPathIfExists(D, SysRoot + "/lib", Paths); 3805 addPathIfExists(D, SysRoot + "/usr/lib", Paths); 3806 } 3807 3808 bool Linux::HasNativeLLVMSupport() const { return true; } 3809 3810 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); } 3811 3812 Tool *Linux::buildAssembler() const { 3813 return new tools::gnutools::Assembler(*this); 3814 } 3815 3816 std::string Linux::computeSysRoot() const { 3817 if (!getDriver().SysRoot.empty()) 3818 return getDriver().SysRoot; 3819 3820 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch())) 3821 return std::string(); 3822 3823 // Standalone MIPS toolchains use different names for sysroot folder 3824 // and put it into different places. Here we try to check some known 3825 // variants. 3826 3827 const StringRef InstallDir = GCCInstallation.getInstallPath(); 3828 const StringRef TripleStr = GCCInstallation.getTriple().str(); 3829 const Multilib &Multilib = GCCInstallation.getMultilib(); 3830 3831 std::string Path = 3832 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix()) 3833 .str(); 3834 3835 if (getVFS().exists(Path)) 3836 return Path; 3837 3838 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str(); 3839 3840 if (getVFS().exists(Path)) 3841 return Path; 3842 3843 return std::string(); 3844 } 3845 3846 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 3847 ArgStringList &CC1Args) const { 3848 const Driver &D = getDriver(); 3849 std::string SysRoot = computeSysRoot(); 3850 3851 if (DriverArgs.hasArg(options::OPT_nostdinc)) 3852 return; 3853 3854 if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) 3855 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include"); 3856 3857 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { 3858 SmallString<128> P(D.ResourceDir); 3859 llvm::sys::path::append(P, "include"); 3860 addSystemInclude(DriverArgs, CC1Args, P); 3861 } 3862 3863 if (DriverArgs.hasArg(options::OPT_nostdlibinc)) 3864 return; 3865 3866 // Check for configure-time C include directories. 3867 StringRef CIncludeDirs(C_INCLUDE_DIRS); 3868 if (CIncludeDirs != "") { 3869 SmallVector<StringRef, 5> dirs; 3870 CIncludeDirs.split(dirs, ":"); 3871 for (StringRef dir : dirs) { 3872 StringRef Prefix = 3873 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : ""; 3874 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir); 3875 } 3876 return; 3877 } 3878 3879 // Lacking those, try to detect the correct set of system includes for the 3880 // target triple. 3881 3882 // Add include directories specific to the selected multilib set and multilib. 3883 if (GCCInstallation.isValid()) { 3884 const auto &Callback = Multilibs.includeDirsCallback(); 3885 if (Callback) { 3886 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(), 3887 GCCInstallation.getTriple().str(), 3888 GCCInstallation.getMultilib()); 3889 for (const auto &Path : IncludePaths) 3890 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path); 3891 } 3892 } 3893 3894 // Implement generic Debian multiarch support. 3895 const StringRef X86_64MultiarchIncludeDirs[] = { 3896 "/usr/include/x86_64-linux-gnu", 3897 3898 // FIXME: These are older forms of multiarch. It's not clear that they're 3899 // in use in any released version of Debian, so we should consider 3900 // removing them. 3901 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"}; 3902 const StringRef X86MultiarchIncludeDirs[] = { 3903 "/usr/include/i386-linux-gnu", 3904 3905 // FIXME: These are older forms of multiarch. It's not clear that they're 3906 // in use in any released version of Debian, so we should consider 3907 // removing them. 3908 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu", 3909 "/usr/include/i486-linux-gnu"}; 3910 const StringRef AArch64MultiarchIncludeDirs[] = { 3911 "/usr/include/aarch64-linux-gnu"}; 3912 const StringRef ARMMultiarchIncludeDirs[] = { 3913 "/usr/include/arm-linux-gnueabi"}; 3914 const StringRef ARMHFMultiarchIncludeDirs[] = { 3915 "/usr/include/arm-linux-gnueabihf"}; 3916 const StringRef ARMEBMultiarchIncludeDirs[] = { 3917 "/usr/include/armeb-linux-gnueabi"}; 3918 const StringRef ARMEBHFMultiarchIncludeDirs[] = { 3919 "/usr/include/armeb-linux-gnueabihf"}; 3920 const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"}; 3921 const StringRef MIPSELMultiarchIncludeDirs[] = { 3922 "/usr/include/mipsel-linux-gnu"}; 3923 const StringRef MIPS64MultiarchIncludeDirs[] = { 3924 "/usr/include/mips64-linux-gnu", "/usr/include/mips64-linux-gnuabi64"}; 3925 const StringRef MIPS64ELMultiarchIncludeDirs[] = { 3926 "/usr/include/mips64el-linux-gnu", 3927 "/usr/include/mips64el-linux-gnuabi64"}; 3928 const StringRef PPCMultiarchIncludeDirs[] = { 3929 "/usr/include/powerpc-linux-gnu"}; 3930 const StringRef PPC64MultiarchIncludeDirs[] = { 3931 "/usr/include/powerpc64-linux-gnu"}; 3932 const StringRef PPC64LEMultiarchIncludeDirs[] = { 3933 "/usr/include/powerpc64le-linux-gnu"}; 3934 const StringRef SparcMultiarchIncludeDirs[] = { 3935 "/usr/include/sparc-linux-gnu"}; 3936 const StringRef Sparc64MultiarchIncludeDirs[] = { 3937 "/usr/include/sparc64-linux-gnu"}; 3938 const StringRef SYSTEMZMultiarchIncludeDirs[] = { 3939 "/usr/include/s390x-linux-gnu"}; 3940 ArrayRef<StringRef> MultiarchIncludeDirs; 3941 switch (getTriple().getArch()) { 3942 case llvm::Triple::x86_64: 3943 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs; 3944 break; 3945 case llvm::Triple::x86: 3946 MultiarchIncludeDirs = X86MultiarchIncludeDirs; 3947 break; 3948 case llvm::Triple::aarch64: 3949 case llvm::Triple::aarch64_be: 3950 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs; 3951 break; 3952 case llvm::Triple::arm: 3953 case llvm::Triple::thumb: 3954 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF) 3955 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs; 3956 else 3957 MultiarchIncludeDirs = ARMMultiarchIncludeDirs; 3958 break; 3959 case llvm::Triple::armeb: 3960 case llvm::Triple::thumbeb: 3961 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF) 3962 MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs; 3963 else 3964 MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs; 3965 break; 3966 case llvm::Triple::mips: 3967 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs; 3968 break; 3969 case llvm::Triple::mipsel: 3970 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs; 3971 break; 3972 case llvm::Triple::mips64: 3973 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs; 3974 break; 3975 case llvm::Triple::mips64el: 3976 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs; 3977 break; 3978 case llvm::Triple::ppc: 3979 MultiarchIncludeDirs = PPCMultiarchIncludeDirs; 3980 break; 3981 case llvm::Triple::ppc64: 3982 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs; 3983 break; 3984 case llvm::Triple::ppc64le: 3985 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs; 3986 break; 3987 case llvm::Triple::sparc: 3988 MultiarchIncludeDirs = SparcMultiarchIncludeDirs; 3989 break; 3990 case llvm::Triple::sparcv9: 3991 MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs; 3992 break; 3993 case llvm::Triple::systemz: 3994 MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs; 3995 break; 3996 default: 3997 break; 3998 } 3999 for (StringRef Dir : MultiarchIncludeDirs) { 4000 if (D.getVFS().exists(SysRoot + Dir)) { 4001 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir); 4002 break; 4003 } 4004 } 4005 4006 if (getTriple().getOS() == llvm::Triple::RTEMS) 4007 return; 4008 4009 // Add an include of '/include' directly. This isn't provided by default by 4010 // system GCCs, but is often used with cross-compiling GCCs, and harmless to 4011 // add even when Clang is acting as-if it were a system compiler. 4012 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include"); 4013 4014 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include"); 4015 } 4016 4017 4018 static std::string DetectLibcxxIncludePath(StringRef base) { 4019 std::error_code EC; 4020 int MaxVersion = 0; 4021 std::string MaxVersionString = ""; 4022 for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE; 4023 LI = LI.increment(EC)) { 4024 StringRef VersionText = llvm::sys::path::filename(LI->path()); 4025 int Version; 4026 if (VersionText[0] == 'v' && 4027 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) { 4028 if (Version > MaxVersion) { 4029 MaxVersion = Version; 4030 MaxVersionString = VersionText; 4031 } 4032 } 4033 } 4034 return MaxVersion ? (base + "/" + MaxVersionString).str() : ""; 4035 } 4036 4037 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 4038 ArgStringList &CC1Args) const { 4039 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 4040 DriverArgs.hasArg(options::OPT_nostdincxx)) 4041 return; 4042 4043 // Check if libc++ has been enabled and provide its include paths if so. 4044 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) { 4045 const std::string LibCXXIncludePathCandidates[] = { 4046 DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"), 4047 4048 // We also check the system as for a long time this is the only place 4049 // Clang looked. 4050 // FIXME: We should really remove this. It doesn't make any sense. 4051 DetectLibcxxIncludePath(getDriver().SysRoot + "/usr/include/c++")}; 4052 for (const auto &IncludePath : LibCXXIncludePathCandidates) { 4053 if (IncludePath.empty() || !getVFS().exists(IncludePath)) 4054 continue; 4055 // Add the first candidate that exists. 4056 addSystemInclude(DriverArgs, CC1Args, IncludePath); 4057 break; 4058 } 4059 return; 4060 } 4061 4062 // We need a detected GCC installation on Linux to provide libstdc++'s 4063 // headers. We handled the libc++ case above. 4064 if (!GCCInstallation.isValid()) 4065 return; 4066 4067 // By default, look for the C++ headers in an include directory adjacent to 4068 // the lib directory of the GCC installation. Note that this is expect to be 4069 // equivalent to '/usr/include/c++/X.Y' in almost all cases. 4070 StringRef LibDir = GCCInstallation.getParentLibPath(); 4071 StringRef InstallDir = GCCInstallation.getInstallPath(); 4072 StringRef TripleStr = GCCInstallation.getTriple().str(); 4073 const Multilib &Multilib = GCCInstallation.getMultilib(); 4074 const std::string GCCMultiarchTriple = getMultiarchTriple( 4075 getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot); 4076 const std::string TargetMultiarchTriple = 4077 getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot); 4078 const GCCVersion &Version = GCCInstallation.getVersion(); 4079 4080 // The primary search for libstdc++ supports multiarch variants. 4081 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include", 4082 "/c++/" + Version.Text, TripleStr, 4083 GCCMultiarchTriple, TargetMultiarchTriple, 4084 Multilib.includeSuffix(), DriverArgs, CC1Args)) 4085 return; 4086 4087 // Otherwise, fall back on a bunch of options which don't use multiarch 4088 // layouts for simplicity. 4089 const std::string LibStdCXXIncludePathCandidates[] = { 4090 // Gentoo is weird and places its headers inside the GCC install, 4091 // so if the first attempt to find the headers fails, try these patterns. 4092 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." + 4093 Version.MinorStr, 4094 InstallDir.str() + "/include/g++-v" + Version.MajorStr, 4095 // Android standalone toolchain has C++ headers in yet another place. 4096 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text, 4097 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++, 4098 // without a subdirectory corresponding to the gcc version. 4099 LibDir.str() + "/../include/c++", 4100 }; 4101 4102 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) { 4103 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr, 4104 /*GCCMultiarchTriple*/ "", 4105 /*TargetMultiarchTriple*/ "", 4106 Multilib.includeSuffix(), DriverArgs, CC1Args)) 4107 break; 4108 } 4109 } 4110 4111 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs, 4112 ArgStringList &CC1Args) const { 4113 if (DriverArgs.hasArg(options::OPT_nocudainc)) 4114 return; 4115 4116 if (CudaInstallation.isValid()) { 4117 addSystemInclude(DriverArgs, CC1Args, CudaInstallation.getIncludePath()); 4118 CC1Args.push_back("-include"); 4119 CC1Args.push_back("__clang_cuda_runtime_wrapper.h"); 4120 } 4121 } 4122 4123 bool Linux::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); } 4124 4125 SanitizerMask Linux::getSupportedSanitizers() const { 4126 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86; 4127 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; 4128 const bool IsMIPS64 = getTriple().getArch() == llvm::Triple::mips64 || 4129 getTriple().getArch() == llvm::Triple::mips64el; 4130 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 || 4131 getTriple().getArch() == llvm::Triple::ppc64le; 4132 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 || 4133 getTriple().getArch() == llvm::Triple::aarch64_be; 4134 SanitizerMask Res = ToolChain::getSupportedSanitizers(); 4135 Res |= SanitizerKind::Address; 4136 Res |= SanitizerKind::KernelAddress; 4137 Res |= SanitizerKind::Vptr; 4138 Res |= SanitizerKind::SafeStack; 4139 if (IsX86_64 || IsMIPS64 || IsAArch64) 4140 Res |= SanitizerKind::DataFlow; 4141 if (IsX86_64 || IsMIPS64 || IsAArch64) 4142 Res |= SanitizerKind::Leak; 4143 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64) 4144 Res |= SanitizerKind::Thread; 4145 if (IsX86_64 || IsMIPS64 || IsPowerPC64 || IsAArch64) 4146 Res |= SanitizerKind::Memory; 4147 if (IsX86 || IsX86_64) { 4148 Res |= SanitizerKind::Function; 4149 } 4150 return Res; 4151 } 4152 4153 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args, 4154 llvm::opt::ArgStringList &CmdArgs) const { 4155 if (!needsProfileRT(Args)) return; 4156 4157 // Add linker option -u__llvm_runtime_variable to cause runtime 4158 // initialization module to be linked in. 4159 if (!Args.hasArg(options::OPT_coverage)) 4160 CmdArgs.push_back(Args.MakeArgString( 4161 Twine("-u", llvm::getInstrProfRuntimeHookVarName()))); 4162 ToolChain::addProfileRTLibs(Args, CmdArgs); 4163 } 4164 4165 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly. 4166 4167 DragonFly::DragonFly(const Driver &D, const llvm::Triple &Triple, 4168 const ArgList &Args) 4169 : Generic_ELF(D, Triple, Args) { 4170 4171 // Path mangling to find libexec 4172 getProgramPaths().push_back(getDriver().getInstalledDir()); 4173 if (getDriver().getInstalledDir() != getDriver().Dir) 4174 getProgramPaths().push_back(getDriver().Dir); 4175 4176 getFilePaths().push_back(getDriver().Dir + "/../lib"); 4177 getFilePaths().push_back("/usr/lib"); 4178 if (D.getVFS().exists("/usr/lib/gcc47")) 4179 getFilePaths().push_back("/usr/lib/gcc47"); 4180 else 4181 getFilePaths().push_back("/usr/lib/gcc44"); 4182 } 4183 4184 Tool *DragonFly::buildAssembler() const { 4185 return new tools::dragonfly::Assembler(*this); 4186 } 4187 4188 Tool *DragonFly::buildLinker() const { 4189 return new tools::dragonfly::Linker(*this); 4190 } 4191 4192 /// Stub for CUDA toolchain. At the moment we don't have assembler or 4193 /// linker and need toolchain mainly to propagate device-side options 4194 /// to CC1. 4195 4196 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple, 4197 const ArgList &Args) 4198 : Linux(D, Triple, Args) {} 4199 4200 void 4201 CudaToolChain::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, 4202 llvm::opt::ArgStringList &CC1Args) const { 4203 Linux::addClangTargetOptions(DriverArgs, CC1Args); 4204 CC1Args.push_back("-fcuda-is-device"); 4205 4206 if (DriverArgs.hasArg(options::OPT_nocudalib)) 4207 return; 4208 4209 std::string LibDeviceFile = CudaInstallation.getLibDeviceFile( 4210 DriverArgs.getLastArgValue(options::OPT_march_EQ)); 4211 if (!LibDeviceFile.empty()) { 4212 CC1Args.push_back("-mlink-cuda-bitcode"); 4213 CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile)); 4214 4215 // Libdevice in CUDA-7.0 requires PTX version that's more recent 4216 // than LLVM defaults to. Use PTX4.2 which is the PTX version that 4217 // came with CUDA-7.0. 4218 CC1Args.push_back("-target-feature"); 4219 CC1Args.push_back("+ptx42"); 4220 } 4221 } 4222 4223 llvm::opt::DerivedArgList * 4224 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args, 4225 const char *BoundArch) const { 4226 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 4227 const OptTable &Opts = getDriver().getOpts(); 4228 4229 for (Arg *A : Args) { 4230 if (A->getOption().matches(options::OPT_Xarch__)) { 4231 // Skip this argument unless the architecture matches BoundArch 4232 if (A->getValue(0) != StringRef(BoundArch)) 4233 continue; 4234 4235 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 4236 unsigned Prev = Index; 4237 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index)); 4238 4239 // If the argument parsing failed or more than one argument was 4240 // consumed, the -Xarch_ argument's parameter tried to consume 4241 // extra arguments. Emit an error and ignore. 4242 // 4243 // We also want to disallow any options which would alter the 4244 // driver behavior; that isn't going to work in our model. We 4245 // use isDriverOption() as an approximation, although things 4246 // like -O4 are going to slip through. 4247 if (!XarchArg || Index > Prev + 1) { 4248 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) 4249 << A->getAsString(Args); 4250 continue; 4251 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) { 4252 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver) 4253 << A->getAsString(Args); 4254 continue; 4255 } 4256 XarchArg->setBaseArg(A); 4257 A = XarchArg.release(); 4258 DAL->AddSynthesizedArg(A); 4259 } 4260 DAL->append(A); 4261 } 4262 4263 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch); 4264 return DAL; 4265 } 4266 4267 /// XCore tool chain 4268 XCoreToolChain::XCoreToolChain(const Driver &D, const llvm::Triple &Triple, 4269 const ArgList &Args) 4270 : ToolChain(D, Triple, Args) { 4271 // ProgramPaths are found via 'PATH' environment variable. 4272 } 4273 4274 Tool *XCoreToolChain::buildAssembler() const { 4275 return new tools::XCore::Assembler(*this); 4276 } 4277 4278 Tool *XCoreToolChain::buildLinker() const { 4279 return new tools::XCore::Linker(*this); 4280 } 4281 4282 bool XCoreToolChain::isPICDefault() const { return false; } 4283 4284 bool XCoreToolChain::isPIEDefault() const { return false; } 4285 4286 bool XCoreToolChain::isPICDefaultForced() const { return false; } 4287 4288 bool XCoreToolChain::SupportsProfiling() const { return false; } 4289 4290 bool XCoreToolChain::hasBlocksRuntime() const { return false; } 4291 4292 void XCoreToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 4293 ArgStringList &CC1Args) const { 4294 if (DriverArgs.hasArg(options::OPT_nostdinc) || 4295 DriverArgs.hasArg(options::OPT_nostdlibinc)) 4296 return; 4297 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) { 4298 SmallVector<StringRef, 4> Dirs; 4299 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 4300 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr)); 4301 ArrayRef<StringRef> DirVec(Dirs); 4302 addSystemIncludes(DriverArgs, CC1Args, DirVec); 4303 } 4304 } 4305 4306 void XCoreToolChain::addClangTargetOptions(const ArgList &DriverArgs, 4307 ArgStringList &CC1Args) const { 4308 CC1Args.push_back("-nostdsysteminc"); 4309 } 4310 4311 void XCoreToolChain::AddClangCXXStdlibIncludeArgs( 4312 const ArgList &DriverArgs, ArgStringList &CC1Args) const { 4313 if (DriverArgs.hasArg(options::OPT_nostdinc) || 4314 DriverArgs.hasArg(options::OPT_nostdlibinc) || 4315 DriverArgs.hasArg(options::OPT_nostdincxx)) 4316 return; 4317 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) { 4318 SmallVector<StringRef, 4> Dirs; 4319 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; 4320 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr)); 4321 ArrayRef<StringRef> DirVec(Dirs); 4322 addSystemIncludes(DriverArgs, CC1Args, DirVec); 4323 } 4324 } 4325 4326 void XCoreToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 4327 ArgStringList &CmdArgs) const { 4328 // We don't output any lib args. This is handled by xcc. 4329 } 4330 4331 MyriadToolChain::MyriadToolChain(const Driver &D, const llvm::Triple &Triple, 4332 const ArgList &Args) 4333 : Generic_GCC(D, Triple, Args) { 4334 // If a target of 'sparc-myriad-elf' is specified to clang, it wants to use 4335 // 'sparc-myriad--elf' (note the unknown OS) as the canonical triple. 4336 // This won't work to find gcc. Instead we give the installation detector an 4337 // extra triple, which is preferable to further hacks of the logic that at 4338 // present is based solely on getArch(). In particular, it would be wrong to 4339 // choose the myriad installation when targeting a non-myriad sparc install. 4340 switch (Triple.getArch()) { 4341 default: 4342 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName() 4343 << "myriad"; 4344 case llvm::Triple::sparc: 4345 case llvm::Triple::sparcel: 4346 case llvm::Triple::shave: 4347 GCCInstallation.init(Triple, Args, {"sparc-myriad-elf"}); 4348 } 4349 4350 if (GCCInstallation.isValid()) { 4351 // The contents of LibDir are independent of the version of gcc. 4352 // This contains libc, libg (a superset of libc), libm, libstdc++, libssp. 4353 SmallString<128> LibDir(GCCInstallation.getParentLibPath()); 4354 if (Triple.getArch() == llvm::Triple::sparcel) 4355 llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib/le"); 4356 else 4357 llvm::sys::path::append(LibDir, "../sparc-myriad-elf/lib"); 4358 addPathIfExists(D, LibDir, getFilePaths()); 4359 4360 // This directory contains crt{i,n,begin,end}.o as well as libgcc. 4361 // These files are tied to a particular version of gcc. 4362 SmallString<128> CompilerSupportDir(GCCInstallation.getInstallPath()); 4363 // There are actually 4 choices: {le,be} x {fpu,nofpu} 4364 // but as this toolchain is for LEON sparc, it can assume FPU. 4365 if (Triple.getArch() == llvm::Triple::sparcel) 4366 llvm::sys::path::append(CompilerSupportDir, "le"); 4367 addPathIfExists(D, CompilerSupportDir, getFilePaths()); 4368 } 4369 } 4370 4371 MyriadToolChain::~MyriadToolChain() {} 4372 4373 void MyriadToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 4374 ArgStringList &CC1Args) const { 4375 if (!DriverArgs.hasArg(options::OPT_nostdinc)) 4376 addSystemInclude(DriverArgs, CC1Args, getDriver().SysRoot + "/include"); 4377 } 4378 4379 void MyriadToolChain::AddClangCXXStdlibIncludeArgs( 4380 const ArgList &DriverArgs, ArgStringList &CC1Args) const { 4381 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 4382 DriverArgs.hasArg(options::OPT_nostdincxx)) 4383 return; 4384 4385 // Only libstdc++, for now. 4386 StringRef LibDir = GCCInstallation.getParentLibPath(); 4387 const GCCVersion &Version = GCCInstallation.getVersion(); 4388 StringRef TripleStr = GCCInstallation.getTriple().str(); 4389 const Multilib &Multilib = GCCInstallation.getMultilib(); 4390 4391 addLibStdCXXIncludePaths( 4392 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text, 4393 "", TripleStr, "", "", Multilib.includeSuffix(), DriverArgs, CC1Args); 4394 } 4395 4396 // MyriadToolChain handles several triples: 4397 // {shave,sparc{,el}}-myriad-{rtems,unknown}-elf 4398 Tool *MyriadToolChain::SelectTool(const JobAction &JA) const { 4399 // The inherited method works fine if not targeting the SHAVE. 4400 if (!isShaveCompilation(getTriple())) 4401 return ToolChain::SelectTool(JA); 4402 switch (JA.getKind()) { 4403 case Action::PreprocessJobClass: 4404 case Action::CompileJobClass: 4405 if (!Compiler) 4406 Compiler.reset(new tools::SHAVE::Compiler(*this)); 4407 return Compiler.get(); 4408 case Action::AssembleJobClass: 4409 if (!Assembler) 4410 Assembler.reset(new tools::SHAVE::Assembler(*this)); 4411 return Assembler.get(); 4412 default: 4413 return ToolChain::getTool(JA.getKind()); 4414 } 4415 } 4416 4417 Tool *MyriadToolChain::buildLinker() const { 4418 return new tools::Myriad::Linker(*this); 4419 } 4420 4421 WebAssembly::WebAssembly(const Driver &D, const llvm::Triple &Triple, 4422 const llvm::opt::ArgList &Args) 4423 : ToolChain(D, Triple, Args) { 4424 // Use LLD by default. 4425 DefaultLinker = "lld"; 4426 } 4427 4428 bool WebAssembly::IsMathErrnoDefault() const { return false; } 4429 4430 bool WebAssembly::IsObjCNonFragileABIDefault() const { return true; } 4431 4432 bool WebAssembly::UseObjCMixedDispatch() const { return true; } 4433 4434 bool WebAssembly::isPICDefault() const { return false; } 4435 4436 bool WebAssembly::isPIEDefault() const { return false; } 4437 4438 bool WebAssembly::isPICDefaultForced() const { return false; } 4439 4440 bool WebAssembly::IsIntegratedAssemblerDefault() const { return true; } 4441 4442 // TODO: Support Objective C stuff. 4443 bool WebAssembly::SupportsObjCGC() const { return false; } 4444 4445 bool WebAssembly::hasBlocksRuntime() const { return false; } 4446 4447 // TODO: Support profiling. 4448 bool WebAssembly::SupportsProfiling() const { return false; } 4449 4450 bool WebAssembly::HasNativeLLVMSupport() const { return true; } 4451 4452 void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs, 4453 ArgStringList &CC1Args) const { 4454 if (DriverArgs.hasFlag(options::OPT_fuse_init_array, 4455 options::OPT_fno_use_init_array, true)) 4456 CC1Args.push_back("-fuse-init-array"); 4457 } 4458 4459 Tool *WebAssembly::buildLinker() const { 4460 return new tools::wasm::Linker(*this); 4461 } 4462 4463 PS4CPU::PS4CPU(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) 4464 : Generic_ELF(D, Triple, Args) { 4465 if (Args.hasArg(options::OPT_static)) 4466 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-static" << "PS4"; 4467 4468 // Determine where to find the PS4 libraries. We use SCE_PS4_SDK_DIR 4469 // if it exists; otherwise use the driver's installation path, which 4470 // should be <SDK_DIR>/host_tools/bin. 4471 4472 SmallString<512> PS4SDKDir; 4473 if (const char *EnvValue = getenv("SCE_PS4_SDK_DIR")) { 4474 if (!llvm::sys::fs::exists(EnvValue)) 4475 getDriver().Diag(clang::diag::warn_drv_ps4_sdk_dir) << EnvValue; 4476 PS4SDKDir = EnvValue; 4477 } else { 4478 PS4SDKDir = getDriver().Dir; 4479 llvm::sys::path::append(PS4SDKDir, "/../../"); 4480 } 4481 4482 // By default, the driver won't report a warning if it can't find 4483 // PS4's include or lib directories. This behavior could be changed if 4484 // -Weverything or -Winvalid-or-nonexistent-directory options are passed. 4485 // If -isysroot was passed, use that as the SDK base path. 4486 std::string PrefixDir; 4487 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { 4488 PrefixDir = A->getValue(); 4489 if (!llvm::sys::fs::exists(PrefixDir)) 4490 getDriver().Diag(clang::diag::warn_missing_sysroot) << PrefixDir; 4491 } else 4492 PrefixDir = PS4SDKDir.str(); 4493 4494 SmallString<512> PS4SDKIncludeDir(PrefixDir); 4495 llvm::sys::path::append(PS4SDKIncludeDir, "target/include"); 4496 if (!Args.hasArg(options::OPT_nostdinc) && 4497 !Args.hasArg(options::OPT_nostdlibinc) && 4498 !Args.hasArg(options::OPT_isysroot) && 4499 !Args.hasArg(options::OPT__sysroot_EQ) && 4500 !llvm::sys::fs::exists(PS4SDKIncludeDir)) { 4501 getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected) 4502 << "PS4 system headers" << PS4SDKIncludeDir; 4503 } 4504 4505 SmallString<512> PS4SDKLibDir(PS4SDKDir); 4506 llvm::sys::path::append(PS4SDKLibDir, "target/lib"); 4507 if (!Args.hasArg(options::OPT_nostdlib) && 4508 !Args.hasArg(options::OPT_nodefaultlibs) && 4509 !Args.hasArg(options::OPT__sysroot_EQ) && !Args.hasArg(options::OPT_E) && 4510 !Args.hasArg(options::OPT_c) && !Args.hasArg(options::OPT_S) && 4511 !Args.hasArg(options::OPT_emit_ast) && 4512 !llvm::sys::fs::exists(PS4SDKLibDir)) { 4513 getDriver().Diag(clang::diag::warn_drv_unable_to_find_directory_expected) 4514 << "PS4 system libraries" << PS4SDKLibDir; 4515 return; 4516 } 4517 getFilePaths().push_back(PS4SDKLibDir.str()); 4518 } 4519 4520 Tool *PS4CPU::buildAssembler() const { 4521 return new tools::PS4cpu::Assemble(*this); 4522 } 4523 4524 Tool *PS4CPU::buildLinker() const { return new tools::PS4cpu::Link(*this); } 4525 4526 bool PS4CPU::isPICDefault() const { return true; } 4527 4528 bool PS4CPU::HasNativeLLVMSupport() const { return true; } 4529 4530 SanitizerMask PS4CPU::getSupportedSanitizers() const { 4531 SanitizerMask Res = ToolChain::getSupportedSanitizers(); 4532 Res |= SanitizerKind::Address; 4533 Res |= SanitizerKind::Vptr; 4534 return Res; 4535 } 4536