1 //===--- ToolChains.cpp - ToolChain Implementations -----------------------===// 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/Config/config.h" // for GCC_INSTALL_PREFIX 14 #include "clang/Driver/Compilation.h" 15 #include "clang/Driver/Driver.h" 16 #include "clang/Driver/DriverDiagnostic.h" 17 #include "clang/Driver/Options.h" 18 #include "clang/Driver/SanitizerArgs.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/Option/Arg.h" 24 #include "llvm/Option/ArgList.h" 25 #include "llvm/Option/OptTable.h" 26 #include "llvm/Option/Option.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/MemoryBuffer.h" 30 #include "llvm/Support/Path.h" 31 #include "llvm/Support/Program.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <cstdlib> // ::getenv 34 #include <system_error> 35 36 using namespace clang::driver; 37 using namespace clang::driver::toolchains; 38 using namespace clang; 39 using namespace llvm::opt; 40 41 MachO::MachO(const Driver &D, const llvm::Triple &Triple, 42 const ArgList &Args) 43 : ToolChain(D, Triple, Args) { 44 getProgramPaths().push_back(getDriver().getInstalledDir()); 45 if (getDriver().getInstalledDir() != getDriver().Dir) 46 getProgramPaths().push_back(getDriver().Dir); 47 48 // We expect 'as', 'ld', etc. to be adjacent to our install dir. 49 getProgramPaths().push_back(getDriver().getInstalledDir()); 50 if (getDriver().getInstalledDir() != getDriver().Dir) 51 getProgramPaths().push_back(getDriver().Dir); 52 } 53 54 /// Darwin - Darwin tool chain for i386 and x86_64. 55 Darwin::Darwin(const Driver & D, const llvm::Triple & Triple, 56 const ArgList & Args) 57 : MachO(D, Triple, Args), TargetInitialized(false) { 58 // Compute the initial Darwin version from the triple 59 unsigned Major, Minor, Micro; 60 if (!Triple.getMacOSXVersion(Major, Minor, Micro)) 61 getDriver().Diag(diag::err_drv_invalid_darwin_version) << 62 Triple.getOSName(); 63 llvm::raw_string_ostream(MacosxVersionMin) 64 << Major << '.' << Minor << '.' << Micro; 65 66 // FIXME: DarwinVersion is only used to find GCC's libexec directory. 67 // It should be removed when we stop supporting that. 68 DarwinVersion[0] = Minor + 4; 69 DarwinVersion[1] = Micro; 70 DarwinVersion[2] = 0; 71 72 // Compute the initial iOS version from the triple 73 Triple.getiOSVersion(Major, Minor, Micro); 74 llvm::raw_string_ostream(iOSVersionMin) 75 << Major << '.' << Minor << '.' << Micro; 76 } 77 78 types::ID MachO::LookupTypeForExtension(const char *Ext) const { 79 types::ID Ty = types::lookupTypeForExtension(Ext); 80 81 // Darwin always preprocesses assembly files (unless -x is used explicitly). 82 if (Ty == types::TY_PP_Asm) 83 return types::TY_Asm; 84 85 return Ty; 86 } 87 88 bool MachO::HasNativeLLVMSupport() const { 89 return true; 90 } 91 92 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0. 93 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const { 94 if (isTargetIOSBased()) 95 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion); 96 if (isNonFragile) 97 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion); 98 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion); 99 } 100 101 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2. 102 bool Darwin::hasBlocksRuntime() const { 103 if (isTargetIOSBased()) 104 return !isIPhoneOSVersionLT(3, 2); 105 else { 106 assert(isTargetMacOS() && "unexpected darwin target"); 107 return !isMacosxVersionLT(10, 6); 108 } 109 } 110 111 static const char *GetArmArchForMArch(StringRef Value) { 112 return llvm::StringSwitch<const char*>(Value) 113 .Case("armv6k", "armv6") 114 .Case("armv6m", "armv6m") 115 .Case("armv5tej", "armv5") 116 .Case("xscale", "xscale") 117 .Case("armv4t", "armv4t") 118 .Case("armv7", "armv7") 119 .Cases("armv7a", "armv7-a", "armv7") 120 .Cases("armv7r", "armv7-r", "armv7") 121 .Cases("armv7em", "armv7e-m", "armv7em") 122 .Cases("armv7k", "armv7-k", "armv7k") 123 .Cases("armv7m", "armv7-m", "armv7m") 124 .Cases("armv7s", "armv7-s", "armv7s") 125 .Default(nullptr); 126 } 127 128 static const char *GetArmArchForMCpu(StringRef Value) { 129 return llvm::StringSwitch<const char *>(Value) 130 .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5") 131 .Cases("arm10e", "arm10tdmi", "armv5") 132 .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5") 133 .Case("xscale", "xscale") 134 .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "arm1176jzf-s", "armv6") 135 .Cases("sc000", "cortex-m0", "cortex-m0plus", "cortex-m1", "armv6m") 136 .Cases("cortex-a5", "cortex-a7", "cortex-a8", "armv7") 137 .Cases("cortex-a9", "cortex-a12", "cortex-a15", "cortex-a17", "krait", "armv7") 138 .Cases("cortex-r4", "cortex-r4f", "cortex-r5", "cortex-r7", "armv7r") 139 .Cases("sc300", "cortex-m3", "armv7m") 140 .Cases("cortex-m4", "cortex-m7", "armv7em") 141 .Case("swift", "armv7s") 142 .Default(nullptr); 143 } 144 145 static bool isSoftFloatABI(const ArgList &Args) { 146 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float, 147 options::OPT_mfloat_abi_EQ); 148 if (!A) 149 return false; 150 151 return A->getOption().matches(options::OPT_msoft_float) || 152 (A->getOption().matches(options::OPT_mfloat_abi_EQ) && 153 A->getValue() == StringRef("soft")); 154 } 155 156 StringRef MachO::getMachOArchName(const ArgList &Args) const { 157 switch (getTriple().getArch()) { 158 default: 159 return getDefaultUniversalArchName(); 160 161 case llvm::Triple::aarch64: 162 return "arm64"; 163 164 case llvm::Triple::thumb: 165 case llvm::Triple::arm: { 166 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 167 if (const char *Arch = GetArmArchForMArch(A->getValue())) 168 return Arch; 169 170 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 171 if (const char *Arch = GetArmArchForMCpu(A->getValue())) 172 return Arch; 173 174 return "arm"; 175 } 176 } 177 } 178 179 Darwin::~Darwin() { 180 } 181 182 MachO::~MachO() { 183 } 184 185 186 std::string MachO::ComputeEffectiveClangTriple(const ArgList &Args, 187 types::ID InputType) const { 188 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); 189 190 return Triple.getTriple(); 191 } 192 193 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args, 194 types::ID InputType) const { 195 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); 196 197 // If the target isn't initialized (e.g., an unknown Darwin platform, return 198 // the default triple). 199 if (!isTargetInitialized()) 200 return Triple.getTriple(); 201 202 SmallString<16> Str; 203 Str += isTargetIOSBased() ? "ios" : "macosx"; 204 Str += getTargetVersion().getAsString(); 205 Triple.setOSName(Str); 206 207 return Triple.getTriple(); 208 } 209 210 void Generic_ELF::anchor() {} 211 212 Tool *MachO::getTool(Action::ActionClass AC) const { 213 switch (AC) { 214 case Action::LipoJobClass: 215 if (!Lipo) 216 Lipo.reset(new tools::darwin::Lipo(*this)); 217 return Lipo.get(); 218 case Action::DsymutilJobClass: 219 if (!Dsymutil) 220 Dsymutil.reset(new tools::darwin::Dsymutil(*this)); 221 return Dsymutil.get(); 222 case Action::VerifyDebugInfoJobClass: 223 if (!VerifyDebug) 224 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this)); 225 return VerifyDebug.get(); 226 default: 227 return ToolChain::getTool(AC); 228 } 229 } 230 231 Tool *MachO::buildLinker() const { 232 return new tools::darwin::Link(*this); 233 } 234 235 Tool *MachO::buildAssembler() const { 236 return new tools::darwin::Assemble(*this); 237 } 238 239 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple, 240 const ArgList &Args) 241 : Darwin(D, Triple, Args) { 242 } 243 244 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const { 245 // For iOS, 64-bit, promote certain warnings to errors. 246 if (!isTargetMacOS() && getTriple().isArch64Bit()) { 247 // Always enable -Wdeprecated-objc-isa-usage and promote it 248 // to an error. 249 CC1Args.push_back("-Wdeprecated-objc-isa-usage"); 250 CC1Args.push_back("-Werror=deprecated-objc-isa-usage"); 251 252 // Also error about implicit function declarations, as that 253 // can impact calling conventions. 254 CC1Args.push_back("-Werror=implicit-function-declaration"); 255 } 256 } 257 258 /// \brief Determine whether Objective-C automated reference counting is 259 /// enabled. 260 static bool isObjCAutoRefCount(const ArgList &Args) { 261 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); 262 } 263 264 void DarwinClang::AddLinkARCArgs(const ArgList &Args, 265 ArgStringList &CmdArgs) const { 266 // Avoid linking compatibility stubs on i386 mac. 267 if (isTargetMacOS() && getArch() == llvm::Triple::x86) 268 return; 269 270 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true); 271 272 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) && 273 runtime.hasSubscripting()) 274 return; 275 276 CmdArgs.push_back("-force_load"); 277 SmallString<128> P(getDriver().ClangExecutable); 278 llvm::sys::path::remove_filename(P); // 'clang' 279 llvm::sys::path::remove_filename(P); // 'bin' 280 llvm::sys::path::append(P, "lib", "arc", "libarclite_"); 281 // Mash in the platform. 282 if (isTargetIOSSimulator()) 283 P += "iphonesimulator"; 284 else if (isTargetIPhoneOS()) 285 P += "iphoneos"; 286 else 287 P += "macosx"; 288 P += ".a"; 289 290 CmdArgs.push_back(Args.MakeArgString(P)); 291 } 292 293 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs, 294 StringRef DarwinLibName, bool AlwaysLink, 295 bool IsEmbedded, bool AddRPath) const { 296 SmallString<128> Dir(getDriver().ResourceDir); 297 llvm::sys::path::append(Dir, "lib", IsEmbedded ? "macho_embedded" : "darwin"); 298 299 SmallString<128> P(Dir); 300 llvm::sys::path::append(P, DarwinLibName); 301 302 // For now, allow missing resource libraries to support developers who may 303 // not have compiler-rt checked out or integrated into their build (unless 304 // we explicitly force linking with this library). 305 if (AlwaysLink || llvm::sys::fs::exists(P)) 306 CmdArgs.push_back(Args.MakeArgString(P)); 307 308 // Adding the rpaths might negatively interact when other rpaths are involved, 309 // so we should make sure we add the rpaths last, after all user-specified 310 // rpaths. This is currently true from this place, but we need to be 311 // careful if this function is ever called before user's rpaths are emitted. 312 if (AddRPath) { 313 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library"); 314 315 // Add @executable_path to rpath to support having the dylib copied with 316 // the executable. 317 CmdArgs.push_back("-rpath"); 318 CmdArgs.push_back("@executable_path"); 319 320 // Add the path to the resource dir to rpath to support using the dylib 321 // from the default location without copying. 322 CmdArgs.push_back("-rpath"); 323 CmdArgs.push_back(Args.MakeArgString(Dir)); 324 } 325 } 326 327 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args, 328 ArgStringList &CmdArgs, 329 StringRef Sanitizer) const { 330 if (!Args.hasArg(options::OPT_dynamiclib) && 331 !Args.hasArg(options::OPT_bundle)) { 332 // Sanitizer runtime libraries requires C++. 333 AddCXXStdlibLibArgs(Args, CmdArgs); 334 } 335 assert(isTargetMacOS() || isTargetIOSSimulator()); 336 StringRef OS = isTargetMacOS() ? "osx" : "iossim"; 337 AddLinkRuntimeLib(Args, CmdArgs, (Twine("libclang_rt.") + Sanitizer + "_" + 338 OS + "_dynamic.dylib").str(), 339 /*AlwaysLink*/ true, /*IsEmbedded*/ false, 340 /*AddRPath*/ true); 341 342 if (GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) { 343 // Add explicit dependcy on -lc++abi, as -lc++ doesn't re-export 344 // all RTTI-related symbols that UBSan uses. 345 CmdArgs.push_back("-lc++abi"); 346 } 347 } 348 349 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args, 350 ArgStringList &CmdArgs) const { 351 // Darwin only supports the compiler-rt based runtime libraries. 352 switch (GetRuntimeLibType(Args)) { 353 case ToolChain::RLT_CompilerRT: 354 break; 355 default: 356 getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) 357 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "darwin"; 358 return; 359 } 360 361 // Darwin doesn't support real static executables, don't link any runtime 362 // libraries with -static. 363 if (Args.hasArg(options::OPT_static) || 364 Args.hasArg(options::OPT_fapple_kext) || 365 Args.hasArg(options::OPT_mkernel)) 366 return; 367 368 // Reject -static-libgcc for now, we can deal with this when and if someone 369 // cares. This is useful in situations where someone wants to statically link 370 // something like libstdc++, and needs its runtime support routines. 371 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) { 372 getDriver().Diag(diag::err_drv_unsupported_opt) 373 << A->getAsString(Args); 374 return; 375 } 376 377 // If we are building profile support, link that library in. 378 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 379 false) || 380 Args.hasArg(options::OPT_fprofile_generate) || 381 Args.hasArg(options::OPT_fprofile_instr_generate) || 382 Args.hasArg(options::OPT_fcreate_profile) || 383 Args.hasArg(options::OPT_coverage)) { 384 // Select the appropriate runtime library for the target. 385 if (isTargetIOSBased()) 386 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a"); 387 else 388 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a"); 389 } 390 391 const SanitizerArgs &Sanitize = getSanitizerArgs(); 392 393 if (Sanitize.needsAsanRt()) { 394 if (!isTargetMacOS() && !isTargetIOSSimulator()) { 395 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds. 396 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform) 397 << "-fsanitize=address"; 398 } else { 399 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan"); 400 } 401 } 402 403 if (Sanitize.needsUbsanRt()) { 404 if (!isTargetMacOS() && !isTargetIOSSimulator()) { 405 // FIXME: Move this check to SanitizerArgs::filterUnsupportedKinds. 406 getDriver().Diag(diag::err_drv_clang_unsupported_per_platform) 407 << "-fsanitize=undefined"; 408 } else { 409 AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan"); 410 } 411 } 412 413 // Otherwise link libSystem, then the dynamic runtime library, and finally any 414 // target specific static runtime library. 415 CmdArgs.push_back("-lSystem"); 416 417 // Select the dynamic runtime library and the target specific static library. 418 if (isTargetIOSBased()) { 419 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1, 420 // it never went into the SDK. 421 // Linking against libgcc_s.1 isn't needed for iOS 5.0+ 422 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() && 423 getTriple().getArch() != llvm::Triple::aarch64) 424 CmdArgs.push_back("-lgcc_s.1"); 425 426 // We currently always need a static runtime library for iOS. 427 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a"); 428 } else { 429 assert(isTargetMacOS() && "unexpected non MacOS platform"); 430 // The dynamic runtime library was merged with libSystem for 10.6 and 431 // beyond; only 10.4 and 10.5 need an additional runtime library. 432 if (isMacosxVersionLT(10, 5)) 433 CmdArgs.push_back("-lgcc_s.10.4"); 434 else if (isMacosxVersionLT(10, 6)) 435 CmdArgs.push_back("-lgcc_s.10.5"); 436 437 // For OS X, we thought we would only need a static runtime library when 438 // targeting 10.4, to provide versions of the static functions which were 439 // omitted from 10.4.dylib. 440 // 441 // Unfortunately, that turned out to not be true, because Darwin system 442 // headers can still use eprintf on i386, and it is not exported from 443 // libSystem. Therefore, we still must provide a runtime library just for 444 // the tiny tiny handful of projects that *might* use that symbol. 445 if (isMacosxVersionLT(10, 5)) { 446 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a"); 447 } else { 448 if (getTriple().getArch() == llvm::Triple::x86) 449 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a"); 450 AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a"); 451 } 452 } 453 } 454 455 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { 456 const OptTable &Opts = getDriver().getOpts(); 457 458 // Support allowing the SDKROOT environment variable used by xcrun and other 459 // Xcode tools to define the default sysroot, by making it the default for 460 // isysroot. 461 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { 462 // Warn if the path does not exist. 463 if (!llvm::sys::fs::exists(A->getValue())) 464 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue(); 465 } else { 466 if (char *env = ::getenv("SDKROOT")) { 467 // We only use this value as the default if it is an absolute path, 468 // exists, and it is not the root path. 469 if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) && 470 StringRef(env) != "/") { 471 Args.append(Args.MakeSeparateArg( 472 nullptr, Opts.getOption(options::OPT_isysroot), env)); 473 } 474 } 475 } 476 477 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ); 478 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ); 479 480 if (OSXVersion && iOSVersion) { 481 getDriver().Diag(diag::err_drv_argument_not_allowed_with) 482 << OSXVersion->getAsString(Args) 483 << iOSVersion->getAsString(Args); 484 iOSVersion = nullptr; 485 } else if (!OSXVersion && !iOSVersion) { 486 // If no deployment target was specified on the command line, check for 487 // environment defines. 488 StringRef OSXTarget; 489 StringRef iOSTarget; 490 if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET")) 491 OSXTarget = env; 492 if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET")) 493 iOSTarget = env; 494 495 // If no '-miphoneos-version-min' specified on the command line and 496 // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default 497 // based on -isysroot. 498 if (iOSTarget.empty()) { 499 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { 500 StringRef first, second; 501 StringRef isysroot = A->getValue(); 502 std::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS")); 503 if (second != "") 504 iOSTarget = second.substr(0,3); 505 } 506 } 507 508 // If no OSX or iOS target has been specified and we're compiling for armv7, 509 // go ahead as assume we're targeting iOS. 510 StringRef MachOArchName = getMachOArchName(Args); 511 if (OSXTarget.empty() && iOSTarget.empty() && 512 (MachOArchName == "armv7" || MachOArchName == "armv7s" || 513 MachOArchName == "arm64")) 514 iOSTarget = iOSVersionMin; 515 516 // Allow conflicts among OSX and iOS for historical reasons, but choose the 517 // default platform. 518 if (!OSXTarget.empty() && !iOSTarget.empty()) { 519 if (getTriple().getArch() == llvm::Triple::arm || 520 getTriple().getArch() == llvm::Triple::aarch64 || 521 getTriple().getArch() == llvm::Triple::thumb) 522 OSXTarget = ""; 523 else 524 iOSTarget = ""; 525 } 526 527 if (!OSXTarget.empty()) { 528 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); 529 OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget); 530 Args.append(OSXVersion); 531 } else if (!iOSTarget.empty()) { 532 const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ); 533 iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget); 534 Args.append(iOSVersion); 535 } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" && 536 MachOArchName != "armv7em") { 537 // Otherwise, assume we are targeting OS X. 538 const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); 539 OSXVersion = Args.MakeJoinedArg(nullptr, O, MacosxVersionMin); 540 Args.append(OSXVersion); 541 } 542 } 543 544 DarwinPlatformKind Platform; 545 if (OSXVersion) 546 Platform = MacOS; 547 else if (iOSVersion) 548 Platform = IPhoneOS; 549 else 550 llvm_unreachable("Unable to infer Darwin variant"); 551 552 // Set the tool chain target information. 553 unsigned Major, Minor, Micro; 554 bool HadExtra; 555 if (Platform == MacOS) { 556 assert(!iOSVersion && "Unknown target platform!"); 557 if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, 558 Micro, HadExtra) || HadExtra || 559 Major != 10 || Minor >= 100 || Micro >= 100) 560 getDriver().Diag(diag::err_drv_invalid_version_number) 561 << OSXVersion->getAsString(Args); 562 } else if (Platform == IPhoneOS) { 563 assert(iOSVersion && "Unknown target platform!"); 564 if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, 565 Micro, HadExtra) || HadExtra || 566 Major >= 10 || Minor >= 100 || Micro >= 100) 567 getDriver().Diag(diag::err_drv_invalid_version_number) 568 << iOSVersion->getAsString(Args); 569 } else 570 llvm_unreachable("unknown kind of Darwin platform"); 571 572 // Recognize iOS targets with an x86 architecture as the iOS simulator. 573 if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 || 574 getTriple().getArch() == llvm::Triple::x86_64)) 575 Platform = IPhoneOSSimulator; 576 577 setTarget(Platform, Major, Minor, Micro); 578 } 579 580 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args, 581 ArgStringList &CmdArgs) const { 582 CXXStdlibType Type = GetCXXStdlibType(Args); 583 584 switch (Type) { 585 case ToolChain::CST_Libcxx: 586 CmdArgs.push_back("-lc++"); 587 break; 588 589 case ToolChain::CST_Libstdcxx: { 590 // Unfortunately, -lstdc++ doesn't always exist in the standard search path; 591 // it was previously found in the gcc lib dir. However, for all the Darwin 592 // platforms we care about it was -lstdc++.6, so we search for that 593 // explicitly if we can't see an obvious -lstdc++ candidate. 594 595 // Check in the sysroot first. 596 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { 597 SmallString<128> P(A->getValue()); 598 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib"); 599 600 if (!llvm::sys::fs::exists(P)) { 601 llvm::sys::path::remove_filename(P); 602 llvm::sys::path::append(P, "libstdc++.6.dylib"); 603 if (llvm::sys::fs::exists(P)) { 604 CmdArgs.push_back(Args.MakeArgString(P)); 605 return; 606 } 607 } 608 } 609 610 // Otherwise, look in the root. 611 // FIXME: This should be removed someday when we don't have to care about 612 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist. 613 if (!llvm::sys::fs::exists("/usr/lib/libstdc++.dylib") && 614 llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib")) { 615 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib"); 616 return; 617 } 618 619 // Otherwise, let the linker search. 620 CmdArgs.push_back("-lstdc++"); 621 break; 622 } 623 } 624 } 625 626 void DarwinClang::AddCCKextLibArgs(const ArgList &Args, 627 ArgStringList &CmdArgs) const { 628 629 // For Darwin platforms, use the compiler-rt-based support library 630 // instead of the gcc-provided one (which is also incidentally 631 // only present in the gcc lib dir, which makes it hard to find). 632 633 SmallString<128> P(getDriver().ResourceDir); 634 llvm::sys::path::append(P, "lib", "darwin"); 635 636 // Use the newer cc_kext for iOS ARM after 6.0. 637 if (!isTargetIPhoneOS() || isTargetIOSSimulator() || 638 getTriple().getArch() == llvm::Triple::aarch64 || 639 !isIPhoneOSVersionLT(6, 0)) { 640 llvm::sys::path::append(P, "libclang_rt.cc_kext.a"); 641 } else { 642 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios5.a"); 643 } 644 645 // For now, allow missing resource libraries to support developers who may 646 // not have compiler-rt checked out or integrated into their build. 647 if (llvm::sys::fs::exists(P)) 648 CmdArgs.push_back(Args.MakeArgString(P)); 649 } 650 651 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args, 652 const char *BoundArch) const { 653 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 654 const OptTable &Opts = getDriver().getOpts(); 655 656 // FIXME: We really want to get out of the tool chain level argument 657 // translation business, as it makes the driver functionality much 658 // more opaque. For now, we follow gcc closely solely for the 659 // purpose of easily achieving feature parity & testability. Once we 660 // have something that works, we should reevaluate each translation 661 // and try to push it down into tool specific logic. 662 663 for (Arg *A : Args) { 664 if (A->getOption().matches(options::OPT_Xarch__)) { 665 // Skip this argument unless the architecture matches either the toolchain 666 // triple arch, or the arch being bound. 667 llvm::Triple::ArchType XarchArch = 668 tools::darwin::getArchTypeForMachOArchName(A->getValue(0)); 669 if (!(XarchArch == getArch() || 670 (BoundArch && XarchArch == 671 tools::darwin::getArchTypeForMachOArchName(BoundArch)))) 672 continue; 673 674 Arg *OriginalArg = A; 675 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 676 unsigned Prev = Index; 677 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index)); 678 679 // If the argument parsing failed or more than one argument was 680 // consumed, the -Xarch_ argument's parameter tried to consume 681 // extra arguments. Emit an error and ignore. 682 // 683 // We also want to disallow any options which would alter the 684 // driver behavior; that isn't going to work in our model. We 685 // use isDriverOption() as an approximation, although things 686 // like -O4 are going to slip through. 687 if (!XarchArg || Index > Prev + 1) { 688 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) 689 << A->getAsString(Args); 690 continue; 691 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) { 692 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver) 693 << A->getAsString(Args); 694 continue; 695 } 696 697 XarchArg->setBaseArg(A); 698 699 A = XarchArg.release(); 700 DAL->AddSynthesizedArg(A); 701 702 // Linker input arguments require custom handling. The problem is that we 703 // have already constructed the phase actions, so we can not treat them as 704 // "input arguments". 705 if (A->getOption().hasFlag(options::LinkerInput)) { 706 // Convert the argument into individual Zlinker_input_args. 707 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) { 708 DAL->AddSeparateArg(OriginalArg, 709 Opts.getOption(options::OPT_Zlinker_input), 710 A->getValue(i)); 711 712 } 713 continue; 714 } 715 } 716 717 // Sob. These is strictly gcc compatible for the time being. Apple 718 // gcc translates options twice, which means that self-expanding 719 // options add duplicates. 720 switch ((options::ID) A->getOption().getID()) { 721 default: 722 DAL->append(A); 723 break; 724 725 case options::OPT_mkernel: 726 case options::OPT_fapple_kext: 727 DAL->append(A); 728 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static)); 729 break; 730 731 case options::OPT_dependency_file: 732 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), 733 A->getValue()); 734 break; 735 736 case options::OPT_gfull: 737 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); 738 DAL->AddFlagArg(A, 739 Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols)); 740 break; 741 742 case options::OPT_gused: 743 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); 744 DAL->AddFlagArg(A, 745 Opts.getOption(options::OPT_feliminate_unused_debug_symbols)); 746 break; 747 748 case options::OPT_shared: 749 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib)); 750 break; 751 752 case options::OPT_fconstant_cfstrings: 753 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings)); 754 break; 755 756 case options::OPT_fno_constant_cfstrings: 757 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings)); 758 break; 759 760 case options::OPT_Wnonportable_cfstrings: 761 DAL->AddFlagArg(A, 762 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings)); 763 break; 764 765 case options::OPT_Wno_nonportable_cfstrings: 766 DAL->AddFlagArg(A, 767 Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings)); 768 break; 769 770 case options::OPT_fpascal_strings: 771 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings)); 772 break; 773 774 case options::OPT_fno_pascal_strings: 775 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings)); 776 break; 777 } 778 } 779 780 if (getTriple().getArch() == llvm::Triple::x86 || 781 getTriple().getArch() == llvm::Triple::x86_64) 782 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ)) 783 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ), 784 "core2"); 785 786 // Add the arch options based on the particular spelling of -arch, to match 787 // how the driver driver works. 788 if (BoundArch) { 789 StringRef Name = BoundArch; 790 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ); 791 const Option MArch = Opts.getOption(options::OPT_march_EQ); 792 793 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch, 794 // which defines the list of which architectures we accept. 795 if (Name == "ppc") 796 ; 797 else if (Name == "ppc601") 798 DAL->AddJoinedArg(nullptr, MCpu, "601"); 799 else if (Name == "ppc603") 800 DAL->AddJoinedArg(nullptr, MCpu, "603"); 801 else if (Name == "ppc604") 802 DAL->AddJoinedArg(nullptr, MCpu, "604"); 803 else if (Name == "ppc604e") 804 DAL->AddJoinedArg(nullptr, MCpu, "604e"); 805 else if (Name == "ppc750") 806 DAL->AddJoinedArg(nullptr, MCpu, "750"); 807 else if (Name == "ppc7400") 808 DAL->AddJoinedArg(nullptr, MCpu, "7400"); 809 else if (Name == "ppc7450") 810 DAL->AddJoinedArg(nullptr, MCpu, "7450"); 811 else if (Name == "ppc970") 812 DAL->AddJoinedArg(nullptr, MCpu, "970"); 813 814 else if (Name == "ppc64" || Name == "ppc64le") 815 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64)); 816 817 else if (Name == "i386") 818 ; 819 else if (Name == "i486") 820 DAL->AddJoinedArg(nullptr, MArch, "i486"); 821 else if (Name == "i586") 822 DAL->AddJoinedArg(nullptr, MArch, "i586"); 823 else if (Name == "i686") 824 DAL->AddJoinedArg(nullptr, MArch, "i686"); 825 else if (Name == "pentium") 826 DAL->AddJoinedArg(nullptr, MArch, "pentium"); 827 else if (Name == "pentium2") 828 DAL->AddJoinedArg(nullptr, MArch, "pentium2"); 829 else if (Name == "pentpro") 830 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro"); 831 else if (Name == "pentIIm3") 832 DAL->AddJoinedArg(nullptr, MArch, "pentium2"); 833 834 else if (Name == "x86_64") 835 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64)); 836 else if (Name == "x86_64h") { 837 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64)); 838 DAL->AddJoinedArg(nullptr, MArch, "x86_64h"); 839 } 840 841 else if (Name == "arm") 842 DAL->AddJoinedArg(nullptr, MArch, "armv4t"); 843 else if (Name == "armv4t") 844 DAL->AddJoinedArg(nullptr, MArch, "armv4t"); 845 else if (Name == "armv5") 846 DAL->AddJoinedArg(nullptr, MArch, "armv5tej"); 847 else if (Name == "xscale") 848 DAL->AddJoinedArg(nullptr, MArch, "xscale"); 849 else if (Name == "armv6") 850 DAL->AddJoinedArg(nullptr, MArch, "armv6k"); 851 else if (Name == "armv6m") 852 DAL->AddJoinedArg(nullptr, MArch, "armv6m"); 853 else if (Name == "armv7") 854 DAL->AddJoinedArg(nullptr, MArch, "armv7a"); 855 else if (Name == "armv7em") 856 DAL->AddJoinedArg(nullptr, MArch, "armv7em"); 857 else if (Name == "armv7k") 858 DAL->AddJoinedArg(nullptr, MArch, "armv7k"); 859 else if (Name == "armv7m") 860 DAL->AddJoinedArg(nullptr, MArch, "armv7m"); 861 else if (Name == "armv7s") 862 DAL->AddJoinedArg(nullptr, MArch, "armv7s"); 863 } 864 865 return DAL; 866 } 867 868 void MachO::AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, 869 llvm::opt::ArgStringList &CmdArgs) const { 870 // Embedded targets are simple at the moment, not supporting sanitizers and 871 // with different libraries for each member of the product { static, PIC } x 872 // { hard-float, soft-float } 873 llvm::SmallString<32> CompilerRT = StringRef("libclang_rt."); 874 CompilerRT += 875 tools::arm::getARMFloatABI(getDriver(), Args, getTriple()) == "hard" 876 ? "hard" 877 : "soft"; 878 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a"; 879 880 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true); 881 } 882 883 884 DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args, 885 const char *BoundArch) const { 886 // First get the generic Apple args, before moving onto Darwin-specific ones. 887 DerivedArgList *DAL = MachO::TranslateArgs(Args, BoundArch); 888 const OptTable &Opts = getDriver().getOpts(); 889 890 // If no architecture is bound, none of the translations here are relevant. 891 if (!BoundArch) 892 return DAL; 893 894 // Add an explicit version min argument for the deployment target. We do this 895 // after argument translation because -Xarch_ arguments may add a version min 896 // argument. 897 AddDeploymentTarget(*DAL); 898 899 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext. 900 // FIXME: It would be far better to avoid inserting those -static arguments, 901 // but we can't check the deployment target in the translation code until 902 // it is set here. 903 if (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0)) { 904 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) { 905 Arg *A = *it; 906 ++it; 907 if (A->getOption().getID() != options::OPT_mkernel && 908 A->getOption().getID() != options::OPT_fapple_kext) 909 continue; 910 assert(it != ie && "unexpected argument translation"); 911 A = *it; 912 assert(A->getOption().getID() == options::OPT_static && 913 "missing expected -static argument"); 914 it = DAL->getArgs().erase(it); 915 } 916 } 917 918 // Default to use libc++ on OS X 10.9+ and iOS 7+. 919 if (((isTargetMacOS() && !isMacosxVersionLT(10, 9)) || 920 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0))) && 921 !Args.getLastArg(options::OPT_stdlib_EQ)) 922 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ), 923 "libc++"); 924 925 // Validate the C++ standard library choice. 926 CXXStdlibType Type = GetCXXStdlibType(*DAL); 927 if (Type == ToolChain::CST_Libcxx) { 928 // Check whether the target provides libc++. 929 StringRef where; 930 931 // Complain about targeting iOS < 5.0 in any way. 932 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0)) 933 where = "iOS 5.0"; 934 935 if (where != StringRef()) { 936 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) 937 << where; 938 } 939 } 940 941 return DAL; 942 } 943 944 bool MachO::IsUnwindTablesDefault() const { 945 return getArch() == llvm::Triple::x86_64; 946 } 947 948 bool MachO::UseDwarfDebugFlags() const { 949 if (const char *S = ::getenv("RC_DEBUG_OPTIONS")) 950 return S[0] != '\0'; 951 return false; 952 } 953 954 bool Darwin::UseSjLjExceptions() const { 955 // Darwin uses SjLj exceptions on ARM. 956 return (getTriple().getArch() == llvm::Triple::arm || 957 getTriple().getArch() == llvm::Triple::thumb); 958 } 959 960 bool MachO::isPICDefault() const { 961 return true; 962 } 963 964 bool MachO::isPIEDefault() const { 965 return false; 966 } 967 968 bool MachO::isPICDefaultForced() const { 969 return (getArch() == llvm::Triple::x86_64 || 970 getArch() == llvm::Triple::aarch64); 971 } 972 973 bool MachO::SupportsProfiling() const { 974 // Profiling instrumentation is only supported on x86. 975 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64; 976 } 977 978 void Darwin::addMinVersionArgs(const llvm::opt::ArgList &Args, 979 llvm::opt::ArgStringList &CmdArgs) const { 980 VersionTuple TargetVersion = getTargetVersion(); 981 982 if (isTargetIOSSimulator()) 983 CmdArgs.push_back("-ios_simulator_version_min"); 984 else if (isTargetIOSBased()) 985 CmdArgs.push_back("-iphoneos_version_min"); 986 else { 987 assert(isTargetMacOS() && "unexpected target"); 988 CmdArgs.push_back("-macosx_version_min"); 989 } 990 991 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString())); 992 } 993 994 void Darwin::addStartObjectFileArgs(const llvm::opt::ArgList &Args, 995 llvm::opt::ArgStringList &CmdArgs) const { 996 // Derived from startfile spec. 997 if (Args.hasArg(options::OPT_dynamiclib)) { 998 // Derived from darwin_dylib1 spec. 999 if (isTargetIOSSimulator()) { 1000 ; // iOS simulator does not need dylib1.o. 1001 } else if (isTargetIPhoneOS()) { 1002 if (isIPhoneOSVersionLT(3, 1)) 1003 CmdArgs.push_back("-ldylib1.o"); 1004 } else { 1005 if (isMacosxVersionLT(10, 5)) 1006 CmdArgs.push_back("-ldylib1.o"); 1007 else if (isMacosxVersionLT(10, 6)) 1008 CmdArgs.push_back("-ldylib1.10.5.o"); 1009 } 1010 } else { 1011 if (Args.hasArg(options::OPT_bundle)) { 1012 if (!Args.hasArg(options::OPT_static)) { 1013 // Derived from darwin_bundle1 spec. 1014 if (isTargetIOSSimulator()) { 1015 ; // iOS simulator does not need bundle1.o. 1016 } else if (isTargetIPhoneOS()) { 1017 if (isIPhoneOSVersionLT(3, 1)) 1018 CmdArgs.push_back("-lbundle1.o"); 1019 } else { 1020 if (isMacosxVersionLT(10, 6)) 1021 CmdArgs.push_back("-lbundle1.o"); 1022 } 1023 } 1024 } else { 1025 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) { 1026 if (Args.hasArg(options::OPT_static) || 1027 Args.hasArg(options::OPT_object) || 1028 Args.hasArg(options::OPT_preload)) { 1029 CmdArgs.push_back("-lgcrt0.o"); 1030 } else { 1031 CmdArgs.push_back("-lgcrt1.o"); 1032 1033 // darwin_crt2 spec is empty. 1034 } 1035 // By default on OS X 10.8 and later, we don't link with a crt1.o 1036 // file and the linker knows to use _main as the entry point. But, 1037 // when compiling with -pg, we need to link with the gcrt1.o file, 1038 // so pass the -no_new_main option to tell the linker to use the 1039 // "start" symbol as the entry point. 1040 if (isTargetMacOS() && !isMacosxVersionLT(10, 8)) 1041 CmdArgs.push_back("-no_new_main"); 1042 } else { 1043 if (Args.hasArg(options::OPT_static) || 1044 Args.hasArg(options::OPT_object) || 1045 Args.hasArg(options::OPT_preload)) { 1046 CmdArgs.push_back("-lcrt0.o"); 1047 } else { 1048 // Derived from darwin_crt1 spec. 1049 if (isTargetIOSSimulator()) { 1050 ; // iOS simulator does not need crt1.o. 1051 } else if (isTargetIPhoneOS()) { 1052 if (getArch() == llvm::Triple::aarch64) 1053 ; // iOS does not need any crt1 files for arm64 1054 else if (isIPhoneOSVersionLT(3, 1)) 1055 CmdArgs.push_back("-lcrt1.o"); 1056 else if (isIPhoneOSVersionLT(6, 0)) 1057 CmdArgs.push_back("-lcrt1.3.1.o"); 1058 } else { 1059 if (isMacosxVersionLT(10, 5)) 1060 CmdArgs.push_back("-lcrt1.o"); 1061 else if (isMacosxVersionLT(10, 6)) 1062 CmdArgs.push_back("-lcrt1.10.5.o"); 1063 else if (isMacosxVersionLT(10, 8)) 1064 CmdArgs.push_back("-lcrt1.10.6.o"); 1065 1066 // darwin_crt2 spec is empty. 1067 } 1068 } 1069 } 1070 } 1071 } 1072 1073 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) && 1074 isMacosxVersionLT(10, 5)) { 1075 const char *Str = Args.MakeArgString(GetFilePath("crt3.o")); 1076 CmdArgs.push_back(Str); 1077 } 1078 } 1079 1080 bool Darwin::SupportsObjCGC() const { 1081 return isTargetMacOS(); 1082 } 1083 1084 void Darwin::CheckObjCARC() const { 1085 if (isTargetIOSBased()|| (isTargetMacOS() && !isMacosxVersionLT(10, 6))) 1086 return; 1087 getDriver().Diag(diag::err_arc_unsupported_on_toolchain); 1088 } 1089 1090 /// Generic_GCC - A tool chain using the 'gcc' command to perform 1091 /// all subcommands; this relies on gcc translating the majority of 1092 /// command line options. 1093 1094 /// \brief Parse a GCCVersion object out of a string of text. 1095 /// 1096 /// This is the primary means of forming GCCVersion objects. 1097 /*static*/ 1098 Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) { 1099 const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "", "", "" }; 1100 std::pair<StringRef, StringRef> First = VersionText.split('.'); 1101 std::pair<StringRef, StringRef> Second = First.second.split('.'); 1102 1103 GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "", "", "" }; 1104 if (First.first.getAsInteger(10, GoodVersion.Major) || 1105 GoodVersion.Major < 0) 1106 return BadVersion; 1107 GoodVersion.MajorStr = First.first.str(); 1108 if (Second.first.getAsInteger(10, GoodVersion.Minor) || 1109 GoodVersion.Minor < 0) 1110 return BadVersion; 1111 GoodVersion.MinorStr = Second.first.str(); 1112 1113 // First look for a number prefix and parse that if present. Otherwise just 1114 // stash the entire patch string in the suffix, and leave the number 1115 // unspecified. This covers versions strings such as: 1116 // 4.4 1117 // 4.4.0 1118 // 4.4.x 1119 // 4.4.2-rc4 1120 // 4.4.x-patched 1121 // And retains any patch number it finds. 1122 StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str(); 1123 if (!PatchText.empty()) { 1124 if (size_t EndNumber = PatchText.find_first_not_of("0123456789")) { 1125 // Try to parse the number and any suffix. 1126 if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) || 1127 GoodVersion.Patch < 0) 1128 return BadVersion; 1129 GoodVersion.PatchSuffix = PatchText.substr(EndNumber); 1130 } 1131 } 1132 1133 return GoodVersion; 1134 } 1135 1136 /// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering. 1137 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor, 1138 int RHSPatch, 1139 StringRef RHSPatchSuffix) const { 1140 if (Major != RHSMajor) 1141 return Major < RHSMajor; 1142 if (Minor != RHSMinor) 1143 return Minor < RHSMinor; 1144 if (Patch != RHSPatch) { 1145 // Note that versions without a specified patch sort higher than those with 1146 // a patch. 1147 if (RHSPatch == -1) 1148 return true; 1149 if (Patch == -1) 1150 return false; 1151 1152 // Otherwise just sort on the patch itself. 1153 return Patch < RHSPatch; 1154 } 1155 if (PatchSuffix != RHSPatchSuffix) { 1156 // Sort empty suffixes higher. 1157 if (RHSPatchSuffix.empty()) 1158 return true; 1159 if (PatchSuffix.empty()) 1160 return false; 1161 1162 // Provide a lexicographic sort to make this a total ordering. 1163 return PatchSuffix < RHSPatchSuffix; 1164 } 1165 1166 // The versions are equal. 1167 return false; 1168 } 1169 1170 static llvm::StringRef getGCCToolchainDir(const ArgList &Args) { 1171 const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain); 1172 if (A) 1173 return A->getValue(); 1174 return GCC_INSTALL_PREFIX; 1175 } 1176 1177 /// \brief Initialize a GCCInstallationDetector from the driver. 1178 /// 1179 /// This performs all of the autodetection and sets up the various paths. 1180 /// Once constructed, a GCCInstallationDetector is essentially immutable. 1181 /// 1182 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and 1183 /// should instead pull the target out of the driver. This is currently 1184 /// necessary because the driver doesn't store the final version of the target 1185 /// triple. 1186 void 1187 Generic_GCC::GCCInstallationDetector::init( 1188 const Driver &D, const llvm::Triple &TargetTriple, const ArgList &Args) { 1189 llvm::Triple BiarchVariantTriple = 1190 TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant() 1191 : TargetTriple.get32BitArchVariant(); 1192 // The library directories which may contain GCC installations. 1193 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs; 1194 // The compatible GCC triples for this particular architecture. 1195 SmallVector<StringRef, 16> CandidateTripleAliases; 1196 SmallVector<StringRef, 16> CandidateBiarchTripleAliases; 1197 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs, 1198 CandidateTripleAliases, CandidateBiarchLibDirs, 1199 CandidateBiarchTripleAliases); 1200 1201 // Compute the set of prefixes for our search. 1202 SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(), 1203 D.PrefixDirs.end()); 1204 1205 StringRef GCCToolchainDir = getGCCToolchainDir(Args); 1206 if (GCCToolchainDir != "") { 1207 if (GCCToolchainDir.back() == '/') 1208 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the / 1209 1210 Prefixes.push_back(GCCToolchainDir); 1211 } else { 1212 // If we have a SysRoot, try that first. 1213 if (!D.SysRoot.empty()) { 1214 Prefixes.push_back(D.SysRoot); 1215 Prefixes.push_back(D.SysRoot + "/usr"); 1216 } 1217 1218 // Then look for gcc installed alongside clang. 1219 Prefixes.push_back(D.InstalledDir + "/.."); 1220 1221 // And finally in /usr. 1222 if (D.SysRoot.empty()) 1223 Prefixes.push_back("/usr"); 1224 } 1225 1226 // Loop over the various components which exist and select the best GCC 1227 // installation available. GCC installs are ranked by version number. 1228 Version = GCCVersion::Parse("0.0.0"); 1229 for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) { 1230 if (!llvm::sys::fs::exists(Prefixes[i])) 1231 continue; 1232 for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) { 1233 const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str(); 1234 if (!llvm::sys::fs::exists(LibDir)) 1235 continue; 1236 for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k) 1237 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, 1238 CandidateTripleAliases[k]); 1239 } 1240 for (unsigned j = 0, je = CandidateBiarchLibDirs.size(); j < je; ++j) { 1241 const std::string LibDir = Prefixes[i] + CandidateBiarchLibDirs[j].str(); 1242 if (!llvm::sys::fs::exists(LibDir)) 1243 continue; 1244 for (unsigned k = 0, ke = CandidateBiarchTripleAliases.size(); k < ke; 1245 ++k) 1246 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, 1247 CandidateBiarchTripleAliases[k], 1248 /*NeedsBiarchSuffix=*/ true); 1249 } 1250 } 1251 } 1252 1253 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const { 1254 for (const auto &InstallPath : CandidateGCCInstallPaths) 1255 OS << "Found candidate GCC installation: " << InstallPath << "\n"; 1256 1257 if (!GCCInstallPath.empty()) 1258 OS << "Selected GCC installation: " << GCCInstallPath << "\n"; 1259 1260 for (const auto &Multilib : Multilibs) 1261 OS << "Candidate multilib: " << Multilib << "\n"; 1262 1263 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault()) 1264 OS << "Selected multilib: " << SelectedMultilib << "\n"; 1265 } 1266 1267 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const { 1268 if (BiarchSibling.hasValue()) { 1269 M = BiarchSibling.getValue(); 1270 return true; 1271 } 1272 return false; 1273 } 1274 1275 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples( 1276 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple, 1277 SmallVectorImpl<StringRef> &LibDirs, 1278 SmallVectorImpl<StringRef> &TripleAliases, 1279 SmallVectorImpl<StringRef> &BiarchLibDirs, 1280 SmallVectorImpl<StringRef> &BiarchTripleAliases) { 1281 // Declare a bunch of static data sets that we'll select between below. These 1282 // are specifically designed to always refer to string literals to avoid any 1283 // lifetime or initialization issues. 1284 static const char *const AArch64LibDirs[] = { "/lib64", "/lib" }; 1285 static const char *const AArch64Triples[] = { "aarch64-none-linux-gnu", 1286 "aarch64-linux-gnu", 1287 "aarch64-linux-android", 1288 "aarch64-redhat-linux" }; 1289 static const char *const AArch64beLibDirs[] = { "/lib" }; 1290 static const char *const AArch64beTriples[] = { "aarch64_be-none-linux-gnu", 1291 "aarch64_be-linux-gnu" }; 1292 1293 static const char *const ARMLibDirs[] = { "/lib" }; 1294 static const char *const ARMTriples[] = { "arm-linux-gnueabi", 1295 "arm-linux-androideabi" }; 1296 static const char *const ARMHFTriples[] = { "arm-linux-gnueabihf", 1297 "armv7hl-redhat-linux-gnueabi" }; 1298 static const char *const ARMebLibDirs[] = { "/lib" }; 1299 static const char *const ARMebTriples[] = { "armeb-linux-gnueabi", 1300 "armeb-linux-androideabi" }; 1301 static const char *const ARMebHFTriples[] = { "armeb-linux-gnueabihf", 1302 "armebv7hl-redhat-linux-gnueabi" }; 1303 1304 static const char *const X86_64LibDirs[] = { "/lib64", "/lib" }; 1305 static const char *const X86_64Triples[] = { 1306 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu", 1307 "x86_64-redhat-linux6E", "x86_64-redhat-linux", "x86_64-suse-linux", 1308 "x86_64-manbo-linux-gnu", "x86_64-linux-gnu", "x86_64-slackware-linux", 1309 "x86_64-linux-android", "x86_64-unknown-linux" 1310 }; 1311 static const char *const X32LibDirs[] = { "/libx32" }; 1312 static const char *const X86LibDirs[] = { "/lib32", "/lib" }; 1313 static const char *const X86Triples[] = { 1314 "i686-linux-gnu", "i686-pc-linux-gnu", "i486-linux-gnu", "i386-linux-gnu", 1315 "i386-redhat-linux6E", "i686-redhat-linux", "i586-redhat-linux", 1316 "i386-redhat-linux", "i586-suse-linux", "i486-slackware-linux", 1317 "i686-montavista-linux", "i686-linux-android", "i586-linux-gnu" 1318 }; 1319 1320 static const char *const MIPSLibDirs[] = { "/lib" }; 1321 static const char *const MIPSTriples[] = { "mips-linux-gnu", 1322 "mips-mti-linux-gnu", 1323 "mips-img-linux-gnu" }; 1324 static const char *const MIPSELLibDirs[] = { "/lib" }; 1325 static const char *const MIPSELTriples[] = { "mipsel-linux-gnu", 1326 "mipsel-linux-android", 1327 "mips-img-linux-gnu" }; 1328 1329 static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" }; 1330 static const char *const MIPS64Triples[] = { "mips64-linux-gnu", 1331 "mips-mti-linux-gnu", 1332 "mips-img-linux-gnu", 1333 "mips64-linux-gnuabi64" }; 1334 static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" }; 1335 static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu", 1336 "mips-mti-linux-gnu", 1337 "mips-img-linux-gnu", 1338 "mips64el-linux-android", 1339 "mips64el-linux-gnuabi64" }; 1340 1341 static const char *const PPCLibDirs[] = { "/lib32", "/lib" }; 1342 static const char *const PPCTriples[] = { 1343 "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe", 1344 "powerpc-suse-linux", "powerpc-montavista-linuxspe" 1345 }; 1346 static const char *const PPC64LibDirs[] = { "/lib64", "/lib" }; 1347 static const char *const PPC64Triples[] = { "powerpc64-linux-gnu", 1348 "powerpc64-unknown-linux-gnu", 1349 "powerpc64-suse-linux", 1350 "ppc64-redhat-linux" }; 1351 static const char *const PPC64LELibDirs[] = { "/lib64", "/lib" }; 1352 static const char *const PPC64LETriples[] = { "powerpc64le-linux-gnu", 1353 "powerpc64le-unknown-linux-gnu", 1354 "powerpc64le-suse-linux", 1355 "ppc64le-redhat-linux" }; 1356 1357 static const char *const SPARCv8LibDirs[] = { "/lib32", "/lib" }; 1358 static const char *const SPARCv8Triples[] = { "sparc-linux-gnu", 1359 "sparcv8-linux-gnu" }; 1360 static const char *const SPARCv9LibDirs[] = { "/lib64", "/lib" }; 1361 static const char *const SPARCv9Triples[] = { "sparc64-linux-gnu", 1362 "sparcv9-linux-gnu" }; 1363 1364 static const char *const SystemZLibDirs[] = { "/lib64", "/lib" }; 1365 static const char *const SystemZTriples[] = { 1366 "s390x-linux-gnu", "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", 1367 "s390x-suse-linux", "s390x-redhat-linux" 1368 }; 1369 1370 using std::begin; 1371 using std::end; 1372 1373 switch (TargetTriple.getArch()) { 1374 case llvm::Triple::aarch64: 1375 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs)); 1376 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples)); 1377 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs)); 1378 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples)); 1379 break; 1380 case llvm::Triple::aarch64_be: 1381 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs)); 1382 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples)); 1383 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs)); 1384 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples)); 1385 break; 1386 case llvm::Triple::arm: 1387 case llvm::Triple::thumb: 1388 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs)); 1389 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) { 1390 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples)); 1391 } else { 1392 TripleAliases.append(begin(ARMTriples), end(ARMTriples)); 1393 } 1394 break; 1395 case llvm::Triple::armeb: 1396 case llvm::Triple::thumbeb: 1397 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs)); 1398 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) { 1399 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples)); 1400 } else { 1401 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples)); 1402 } 1403 break; 1404 case llvm::Triple::x86_64: 1405 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 1406 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples)); 1407 // x32 is always available when x86_64 is available, so adding it as 1408 // secondary arch with x86_64 triples 1409 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) { 1410 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs)); 1411 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples)); 1412 } else { 1413 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 1414 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples)); 1415 } 1416 break; 1417 case llvm::Triple::x86: 1418 LibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 1419 TripleAliases.append(begin(X86Triples), end(X86Triples)); 1420 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 1421 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples)); 1422 break; 1423 case llvm::Triple::mips: 1424 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs)); 1425 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 1426 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs)); 1427 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples)); 1428 break; 1429 case llvm::Triple::mipsel: 1430 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs)); 1431 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples)); 1432 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 1433 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs)); 1434 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples)); 1435 break; 1436 case llvm::Triple::mips64: 1437 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs)); 1438 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples)); 1439 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs)); 1440 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 1441 break; 1442 case llvm::Triple::mips64el: 1443 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs)); 1444 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples)); 1445 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs)); 1446 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples)); 1447 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 1448 break; 1449 case llvm::Triple::ppc: 1450 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs)); 1451 TripleAliases.append(begin(PPCTriples), end(PPCTriples)); 1452 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs)); 1453 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples)); 1454 break; 1455 case llvm::Triple::ppc64: 1456 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs)); 1457 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples)); 1458 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs)); 1459 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples)); 1460 break; 1461 case llvm::Triple::ppc64le: 1462 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs)); 1463 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples)); 1464 break; 1465 case llvm::Triple::sparc: 1466 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs)); 1467 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples)); 1468 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs)); 1469 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples)); 1470 break; 1471 case llvm::Triple::sparcv9: 1472 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs)); 1473 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples)); 1474 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs)); 1475 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples)); 1476 break; 1477 case llvm::Triple::systemz: 1478 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs)); 1479 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples)); 1480 break; 1481 1482 default: 1483 // By default, just rely on the standard lib directories and the original 1484 // triple. 1485 break; 1486 } 1487 1488 // Always append the drivers target triple to the end, in case it doesn't 1489 // match any of our aliases. 1490 TripleAliases.push_back(TargetTriple.str()); 1491 1492 // Also include the multiarch variant if it's different. 1493 if (TargetTriple.str() != BiarchTriple.str()) 1494 BiarchTripleAliases.push_back(BiarchTriple.str()); 1495 } 1496 1497 namespace { 1498 // Filter to remove Multilibs that don't exist as a suffix to Path 1499 class FilterNonExistent { 1500 StringRef Base; 1501 1502 public: 1503 FilterNonExistent(StringRef Base) : Base(Base) {} 1504 bool operator()(const Multilib &M) { 1505 return !llvm::sys::fs::exists(Base + M.gccSuffix() + "/crtbegin.o"); 1506 } 1507 }; 1508 } // end anonymous namespace 1509 1510 static void addMultilibFlag(bool Enabled, const char *const Flag, 1511 std::vector<std::string> &Flags) { 1512 if (Enabled) 1513 Flags.push_back(std::string("+") + Flag); 1514 else 1515 Flags.push_back(std::string("-") + Flag); 1516 } 1517 1518 static bool isMipsArch(llvm::Triple::ArchType Arch) { 1519 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel || 1520 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el; 1521 } 1522 1523 static bool isMips32(llvm::Triple::ArchType Arch) { 1524 return Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel; 1525 } 1526 1527 static bool isMips64(llvm::Triple::ArchType Arch) { 1528 return Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el; 1529 } 1530 1531 static bool isMipsEL(llvm::Triple::ArchType Arch) { 1532 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el; 1533 } 1534 1535 static bool isMips16(const ArgList &Args) { 1536 Arg *A = Args.getLastArg(options::OPT_mips16, 1537 options::OPT_mno_mips16); 1538 return A && A->getOption().matches(options::OPT_mips16); 1539 } 1540 1541 static bool isMicroMips(const ArgList &Args) { 1542 Arg *A = Args.getLastArg(options::OPT_mmicromips, 1543 options::OPT_mno_micromips); 1544 return A && A->getOption().matches(options::OPT_mmicromips); 1545 } 1546 1547 struct DetectedMultilibs { 1548 /// The set of multilibs that the detected installation supports. 1549 MultilibSet Multilibs; 1550 1551 /// The primary multilib appropriate for the given flags. 1552 Multilib SelectedMultilib; 1553 1554 /// On Biarch systems, this corresponds to the default multilib when 1555 /// targeting the non-default multilib. Otherwise, it is empty. 1556 llvm::Optional<Multilib> BiarchSibling; 1557 }; 1558 1559 static Multilib makeMultilib(StringRef commonSuffix) { 1560 return Multilib(commonSuffix, commonSuffix, commonSuffix); 1561 } 1562 1563 static bool findMIPSMultilibs(const llvm::Triple &TargetTriple, StringRef Path, 1564 const llvm::opt::ArgList &Args, 1565 DetectedMultilibs &Result) { 1566 // Some MIPS toolchains put libraries and object files compiled 1567 // using different options in to the sub-directoris which names 1568 // reflects the flags used for compilation. For example sysroot 1569 // directory might looks like the following examples: 1570 // 1571 // /usr 1572 // /lib <= crt*.o files compiled with '-mips32' 1573 // /mips16 1574 // /usr 1575 // /lib <= crt*.o files compiled with '-mips16' 1576 // /el 1577 // /usr 1578 // /lib <= crt*.o files compiled with '-mips16 -EL' 1579 // 1580 // or 1581 // 1582 // /usr 1583 // /lib <= crt*.o files compiled with '-mips32r2' 1584 // /mips16 1585 // /usr 1586 // /lib <= crt*.o files compiled with '-mips32r2 -mips16' 1587 // /mips32 1588 // /usr 1589 // /lib <= crt*.o files compiled with '-mips32' 1590 1591 FilterNonExistent NonExistent(Path); 1592 1593 // Check for FSF toolchain multilibs 1594 MultilibSet FSFMipsMultilibs; 1595 { 1596 auto MArchMips32 = makeMultilib("/mips32") 1597 .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32"); 1598 1599 auto MArchMicroMips = makeMultilib("/micromips") 1600 .flag("+m32").flag("-m64").flag("+mmicromips"); 1601 1602 auto MArchMips64r2 = makeMultilib("/mips64r2") 1603 .flag("-m32").flag("+m64").flag("+march=mips64r2"); 1604 1605 auto MArchMips64 = makeMultilib("/mips64") 1606 .flag("-m32").flag("+m64").flag("-march=mips64r2"); 1607 1608 auto MArchDefault = makeMultilib("") 1609 .flag("+m32").flag("-m64").flag("-mmicromips").flag("+march=mips32r2"); 1610 1611 auto Mips16 = makeMultilib("/mips16") 1612 .flag("+mips16"); 1613 1614 auto UCLibc = makeMultilib("/uclibc") 1615 .flag("+muclibc"); 1616 1617 auto MAbi64 = makeMultilib("/64") 1618 .flag("+mabi=n64").flag("-mabi=n32").flag("-m32"); 1619 1620 auto BigEndian = makeMultilib("") 1621 .flag("+EB").flag("-EL"); 1622 1623 auto LittleEndian = makeMultilib("/el") 1624 .flag("+EL").flag("-EB"); 1625 1626 auto SoftFloat = makeMultilib("/sof") 1627 .flag("+msoft-float"); 1628 1629 auto Nan2008 = makeMultilib("/nan2008") 1630 .flag("+mnan=2008"); 1631 1632 FSFMipsMultilibs = MultilibSet() 1633 .Either(MArchMips32, MArchMicroMips, 1634 MArchMips64r2, MArchMips64, MArchDefault) 1635 .Maybe(UCLibc) 1636 .Maybe(Mips16) 1637 .FilterOut("/mips64/mips16") 1638 .FilterOut("/mips64r2/mips16") 1639 .FilterOut("/micromips/mips16") 1640 .Maybe(MAbi64) 1641 .FilterOut("/micromips/64") 1642 .FilterOut("/mips32/64") 1643 .FilterOut("^/64") 1644 .FilterOut("/mips16/64") 1645 .Either(BigEndian, LittleEndian) 1646 .Maybe(SoftFloat) 1647 .Maybe(Nan2008) 1648 .FilterOut(".*sof/nan2008") 1649 .FilterOut(NonExistent) 1650 .setIncludeDirsCallback([]( 1651 StringRef InstallDir, StringRef TripleStr, const Multilib &M) { 1652 std::vector<std::string> Dirs; 1653 Dirs.push_back((InstallDir + "/include").str()); 1654 std::string SysRootInc = InstallDir.str() + "/../../../../sysroot"; 1655 if (StringRef(M.includeSuffix()).startswith("/uclibc")) 1656 Dirs.push_back(SysRootInc + "/uclibc/usr/include"); 1657 else 1658 Dirs.push_back(SysRootInc + "/usr/include"); 1659 return Dirs; 1660 }); 1661 } 1662 1663 // Check for Code Sourcery toolchain multilibs 1664 MultilibSet CSMipsMultilibs; 1665 { 1666 auto MArchMips16 = makeMultilib("/mips16") 1667 .flag("+m32").flag("+mips16"); 1668 1669 auto MArchMicroMips = makeMultilib("/micromips") 1670 .flag("+m32").flag("+mmicromips"); 1671 1672 auto MArchDefault = makeMultilib("") 1673 .flag("-mips16").flag("-mmicromips"); 1674 1675 auto UCLibc = makeMultilib("/uclibc") 1676 .flag("+muclibc"); 1677 1678 auto SoftFloat = makeMultilib("/soft-float") 1679 .flag("+msoft-float"); 1680 1681 auto Nan2008 = makeMultilib("/nan2008") 1682 .flag("+mnan=2008"); 1683 1684 auto DefaultFloat = makeMultilib("") 1685 .flag("-msoft-float").flag("-mnan=2008"); 1686 1687 auto BigEndian = makeMultilib("") 1688 .flag("+EB").flag("-EL"); 1689 1690 auto LittleEndian = makeMultilib("/el") 1691 .flag("+EL").flag("-EB"); 1692 1693 // Note that this one's osSuffix is "" 1694 auto MAbi64 = makeMultilib("") 1695 .gccSuffix("/64") 1696 .includeSuffix("/64") 1697 .flag("+mabi=n64").flag("-mabi=n32").flag("-m32"); 1698 1699 CSMipsMultilibs = MultilibSet() 1700 .Either(MArchMips16, MArchMicroMips, MArchDefault) 1701 .Maybe(UCLibc) 1702 .Either(SoftFloat, Nan2008, DefaultFloat) 1703 .FilterOut("/micromips/nan2008") 1704 .FilterOut("/mips16/nan2008") 1705 .Either(BigEndian, LittleEndian) 1706 .Maybe(MAbi64) 1707 .FilterOut("/mips16.*/64") 1708 .FilterOut("/micromips.*/64") 1709 .FilterOut(NonExistent) 1710 .setIncludeDirsCallback([]( 1711 StringRef InstallDir, StringRef TripleStr, const Multilib &M) { 1712 std::vector<std::string> Dirs; 1713 Dirs.push_back((InstallDir + "/include").str()); 1714 std::string SysRootInc = 1715 InstallDir.str() + "/../../../../" + TripleStr.str(); 1716 if (StringRef(M.includeSuffix()).startswith("/uclibc")) 1717 Dirs.push_back(SysRootInc + "/libc/uclibc/usr/include"); 1718 else 1719 Dirs.push_back(SysRootInc + "/libc/usr/include"); 1720 return Dirs; 1721 }); 1722 } 1723 1724 MultilibSet AndroidMipsMultilibs = MultilibSet() 1725 .Maybe(Multilib("/mips-r2").flag("+march=mips32r2")) 1726 .Maybe(Multilib("/mips-r6").flag("+march=mips32r6")) 1727 .FilterOut(NonExistent); 1728 1729 MultilibSet DebianMipsMultilibs; 1730 { 1731 Multilib MAbiN32 = Multilib() 1732 .gccSuffix("/n32") 1733 .includeSuffix("/n32") 1734 .flag("+mabi=n32"); 1735 1736 Multilib M64 = Multilib() 1737 .gccSuffix("/64") 1738 .includeSuffix("/64") 1739 .flag("+m64").flag("-m32").flag("-mabi=n32"); 1740 1741 Multilib M32 = Multilib() 1742 .flag("-m64").flag("+m32").flag("-mabi=n32"); 1743 1744 DebianMipsMultilibs = MultilibSet() 1745 .Either(M32, M64, MAbiN32) 1746 .FilterOut(NonExistent); 1747 } 1748 1749 MultilibSet ImgMultilibs; 1750 { 1751 auto Mips64r6 = makeMultilib("/mips64r6") 1752 .flag("+m64").flag("-m32"); 1753 1754 auto LittleEndian = makeMultilib("/el") 1755 .flag("+EL").flag("-EB"); 1756 1757 auto MAbi64 = makeMultilib("/64") 1758 .flag("+mabi=n64").flag("-mabi=n32").flag("-m32"); 1759 1760 ImgMultilibs = MultilibSet() 1761 .Maybe(Mips64r6) 1762 .Maybe(MAbi64) 1763 .Maybe(LittleEndian) 1764 .FilterOut(NonExistent) 1765 .setIncludeDirsCallback([]( 1766 StringRef InstallDir, StringRef TripleStr, const Multilib &M) { 1767 std::vector<std::string> Dirs; 1768 Dirs.push_back((InstallDir + "/include").str()); 1769 Dirs.push_back((InstallDir + "/../../../../sysroot/usr/include").str()); 1770 return Dirs; 1771 }); 1772 } 1773 1774 StringRef CPUName; 1775 StringRef ABIName; 1776 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName); 1777 1778 llvm::Triple::ArchType TargetArch = TargetTriple.getArch(); 1779 1780 Multilib::flags_list Flags; 1781 addMultilibFlag(isMips32(TargetArch), "m32", Flags); 1782 addMultilibFlag(isMips64(TargetArch), "m64", Flags); 1783 addMultilibFlag(isMips16(Args), "mips16", Flags); 1784 addMultilibFlag(CPUName == "mips32", "march=mips32", Flags); 1785 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" || 1786 CPUName == "mips32r5", 1787 "march=mips32r2", Flags); 1788 addMultilibFlag(CPUName == "mips32r6", "march=mips32r6", Flags); 1789 addMultilibFlag(CPUName == "mips64", "march=mips64", Flags); 1790 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" || 1791 CPUName == "mips64r5" || CPUName == "octeon", 1792 "march=mips64r2", Flags); 1793 addMultilibFlag(isMicroMips(Args), "mmicromips", Flags); 1794 addMultilibFlag(tools::mips::isUCLibc(Args), "muclibc", Flags); 1795 addMultilibFlag(tools::mips::isNaN2008(Args, TargetTriple), "mnan=2008", 1796 Flags); 1797 addMultilibFlag(ABIName == "n32", "mabi=n32", Flags); 1798 addMultilibFlag(ABIName == "n64", "mabi=n64", Flags); 1799 addMultilibFlag(isSoftFloatABI(Args), "msoft-float", Flags); 1800 addMultilibFlag(!isSoftFloatABI(Args), "mhard-float", Flags); 1801 addMultilibFlag(isMipsEL(TargetArch), "EL", Flags); 1802 addMultilibFlag(!isMipsEL(TargetArch), "EB", Flags); 1803 1804 if (TargetTriple.getEnvironment() == llvm::Triple::Android) { 1805 // Select Android toolchain. It's the only choice in that case. 1806 if (AndroidMipsMultilibs.select(Flags, Result.SelectedMultilib)) { 1807 Result.Multilibs = AndroidMipsMultilibs; 1808 return true; 1809 } 1810 return false; 1811 } 1812 1813 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies && 1814 TargetTriple.getOS() == llvm::Triple::Linux && 1815 TargetTriple.getEnvironment() == llvm::Triple::GNU) { 1816 // Select mips-img-linux-gnu toolchain. 1817 if (ImgMultilibs.select(Flags, Result.SelectedMultilib)) { 1818 Result.Multilibs = ImgMultilibs; 1819 return true; 1820 } 1821 return false; 1822 } 1823 1824 // Sort candidates. Toolchain that best meets the directories goes first. 1825 // Then select the first toolchains matches command line flags. 1826 MultilibSet *candidates[] = { &DebianMipsMultilibs, &FSFMipsMultilibs, 1827 &CSMipsMultilibs }; 1828 std::sort( 1829 std::begin(candidates), std::end(candidates), 1830 [](MultilibSet *a, MultilibSet *b) { return a->size() > b->size(); }); 1831 for (const auto &candidate : candidates) { 1832 if (candidate->select(Flags, Result.SelectedMultilib)) { 1833 if (candidate == &DebianMipsMultilibs) 1834 Result.BiarchSibling = Multilib(); 1835 Result.Multilibs = *candidate; 1836 return true; 1837 } 1838 } 1839 1840 { 1841 // Fallback to the regular toolchain-tree structure. 1842 Multilib Default; 1843 Result.Multilibs.push_back(Default); 1844 Result.Multilibs.FilterOut(NonExistent); 1845 1846 if (Result.Multilibs.select(Flags, Result.SelectedMultilib)) { 1847 Result.BiarchSibling = Multilib(); 1848 return true; 1849 } 1850 } 1851 1852 return false; 1853 } 1854 1855 static bool findBiarchMultilibs(const llvm::Triple &TargetTriple, 1856 StringRef Path, const ArgList &Args, 1857 bool NeedsBiarchSuffix, 1858 DetectedMultilibs &Result) { 1859 1860 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs 1861 // in what would normally be GCCInstallPath and put the 64-bit 1862 // libs in a subdirectory named 64. The simple logic we follow is that 1863 // *if* there is a subdirectory of the right name with crtbegin.o in it, 1864 // we use that. If not, and if not a biarch triple alias, we look for 1865 // crtbegin.o without the subdirectory. 1866 1867 Multilib Default; 1868 Multilib Alt64 = Multilib() 1869 .gccSuffix("/64") 1870 .includeSuffix("/64") 1871 .flag("-m32").flag("+m64").flag("-mx32"); 1872 Multilib Alt32 = Multilib() 1873 .gccSuffix("/32") 1874 .includeSuffix("/32") 1875 .flag("+m32").flag("-m64").flag("-mx32"); 1876 Multilib Altx32 = Multilib() 1877 .gccSuffix("/x32") 1878 .includeSuffix("/x32") 1879 .flag("-m32").flag("-m64").flag("+mx32"); 1880 1881 FilterNonExistent NonExistent(Path); 1882 1883 // Determine default multilib from: 32, 64, x32 1884 // Also handle cases such as 64 on 32, 32 on 64, etc. 1885 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN; 1886 const bool IsX32 = TargetTriple.getEnvironment() == llvm::Triple::GNUX32; 1887 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32)) 1888 Want = WANT64; 1889 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32)) 1890 Want = WANT64; 1891 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64)) 1892 Want = WANT32; 1893 else { 1894 if (TargetTriple.isArch32Bit()) 1895 Want = NeedsBiarchSuffix ? WANT64 : WANT32; 1896 else if (IsX32) 1897 Want = NeedsBiarchSuffix ? WANT64 : WANTX32; 1898 else 1899 Want = NeedsBiarchSuffix ? WANT32 : WANT64; 1900 } 1901 1902 if (Want == WANT32) 1903 Default.flag("+m32").flag("-m64").flag("-mx32"); 1904 else if (Want == WANT64) 1905 Default.flag("-m32").flag("+m64").flag("-mx32"); 1906 else if (Want == WANTX32) 1907 Default.flag("-m32").flag("-m64").flag("+mx32"); 1908 else 1909 return false; 1910 1911 Result.Multilibs.push_back(Default); 1912 Result.Multilibs.push_back(Alt64); 1913 Result.Multilibs.push_back(Alt32); 1914 Result.Multilibs.push_back(Altx32); 1915 1916 Result.Multilibs.FilterOut(NonExistent); 1917 1918 Multilib::flags_list Flags; 1919 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "m64", Flags); 1920 addMultilibFlag(TargetTriple.isArch32Bit(), "m32", Flags); 1921 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "mx32", Flags); 1922 1923 if (!Result.Multilibs.select(Flags, Result.SelectedMultilib)) 1924 return false; 1925 1926 if (Result.SelectedMultilib == Alt64 || 1927 Result.SelectedMultilib == Alt32 || 1928 Result.SelectedMultilib == Altx32) 1929 Result.BiarchSibling = Default; 1930 1931 return true; 1932 } 1933 1934 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple( 1935 const llvm::Triple &TargetTriple, const ArgList &Args, 1936 const std::string &LibDir, StringRef CandidateTriple, 1937 bool NeedsBiarchSuffix) { 1938 llvm::Triple::ArchType TargetArch = TargetTriple.getArch(); 1939 // There are various different suffixes involving the triple we 1940 // check for. We also record what is necessary to walk from each back 1941 // up to the lib directory. 1942 const std::string LibSuffixes[] = { 1943 "/gcc/" + CandidateTriple.str(), 1944 // Debian puts cross-compilers in gcc-cross 1945 "/gcc-cross/" + CandidateTriple.str(), 1946 "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), 1947 1948 // The Freescale PPC SDK has the gcc libraries in 1949 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. 1950 "/" + CandidateTriple.str(), 1951 1952 // Ubuntu has a strange mis-matched pair of triples that this happens to 1953 // match. 1954 // FIXME: It may be worthwhile to generalize this and look for a second 1955 // triple. 1956 "/i386-linux-gnu/gcc/" + CandidateTriple.str() 1957 }; 1958 const std::string InstallSuffixes[] = { 1959 "/../../..", // gcc/ 1960 "/../../..", // gcc-cross/ 1961 "/../../../..", // <triple>/gcc/ 1962 "/../..", // <triple>/ 1963 "/../../../.." // i386-linux-gnu/gcc/<triple>/ 1964 }; 1965 // Only look at the final, weird Ubuntu suffix for i386-linux-gnu. 1966 const unsigned NumLibSuffixes = 1967 (llvm::array_lengthof(LibSuffixes) - (TargetArch != llvm::Triple::x86)); 1968 for (unsigned i = 0; i < NumLibSuffixes; ++i) { 1969 StringRef LibSuffix = LibSuffixes[i]; 1970 std::error_code EC; 1971 for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE; 1972 !EC && LI != LE; LI = LI.increment(EC)) { 1973 StringRef VersionText = llvm::sys::path::filename(LI->path()); 1974 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText); 1975 if (CandidateVersion.Major != -1) // Filter obviously bad entries. 1976 if (!CandidateGCCInstallPaths.insert(LI->path()).second) 1977 continue; // Saw this path before; no need to look at it again. 1978 if (CandidateVersion.isOlderThan(4, 1, 1)) 1979 continue; 1980 if (CandidateVersion <= Version) 1981 continue; 1982 1983 DetectedMultilibs Detected; 1984 1985 // Debian mips multilibs behave more like the rest of the biarch ones, 1986 // so handle them there 1987 if (isMipsArch(TargetArch)) { 1988 if (!findMIPSMultilibs(TargetTriple, LI->path(), Args, Detected)) 1989 continue; 1990 } else if (!findBiarchMultilibs(TargetTriple, LI->path(), Args, 1991 NeedsBiarchSuffix, Detected)) { 1992 continue; 1993 } 1994 1995 Multilibs = Detected.Multilibs; 1996 SelectedMultilib = Detected.SelectedMultilib; 1997 BiarchSibling = Detected.BiarchSibling; 1998 Version = CandidateVersion; 1999 GCCTriple.setTriple(CandidateTriple); 2000 // FIXME: We hack together the directory name here instead of 2001 // using LI to ensure stable path separators across Windows and 2002 // Linux. 2003 GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str(); 2004 GCCParentLibPath = GCCInstallPath + InstallSuffixes[i]; 2005 IsValid = true; 2006 } 2007 } 2008 } 2009 2010 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple, 2011 const ArgList &Args) 2012 : ToolChain(D, Triple, Args), GCCInstallation() { 2013 getProgramPaths().push_back(getDriver().getInstalledDir()); 2014 if (getDriver().getInstalledDir() != getDriver().Dir) 2015 getProgramPaths().push_back(getDriver().Dir); 2016 } 2017 2018 Generic_GCC::~Generic_GCC() { 2019 } 2020 2021 Tool *Generic_GCC::getTool(Action::ActionClass AC) const { 2022 switch (AC) { 2023 case Action::PreprocessJobClass: 2024 if (!Preprocess) 2025 Preprocess.reset(new tools::gcc::Preprocess(*this)); 2026 return Preprocess.get(); 2027 case Action::CompileJobClass: 2028 if (!Compile) 2029 Compile.reset(new tools::gcc::Compile(*this)); 2030 return Compile.get(); 2031 default: 2032 return ToolChain::getTool(AC); 2033 } 2034 } 2035 2036 Tool *Generic_GCC::buildAssembler() const { 2037 return new tools::gnutools::Assemble(*this); 2038 } 2039 2040 Tool *Generic_GCC::buildLinker() const { 2041 return new tools::gcc::Link(*this); 2042 } 2043 2044 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const { 2045 // Print the information about how we detected the GCC installation. 2046 GCCInstallation.print(OS); 2047 } 2048 2049 bool Generic_GCC::IsUnwindTablesDefault() const { 2050 return getArch() == llvm::Triple::x86_64; 2051 } 2052 2053 bool Generic_GCC::isPICDefault() const { 2054 return false; 2055 } 2056 2057 bool Generic_GCC::isPIEDefault() const { 2058 return false; 2059 } 2060 2061 bool Generic_GCC::isPICDefaultForced() const { 2062 return false; 2063 } 2064 2065 bool Generic_GCC::IsIntegratedAssemblerDefault() const { 2066 return getTriple().getArch() == llvm::Triple::x86 || 2067 getTriple().getArch() == llvm::Triple::x86_64 || 2068 getTriple().getArch() == llvm::Triple::aarch64 || 2069 getTriple().getArch() == llvm::Triple::aarch64_be || 2070 getTriple().getArch() == llvm::Triple::arm || 2071 getTriple().getArch() == llvm::Triple::armeb || 2072 getTriple().getArch() == llvm::Triple::thumb || 2073 getTriple().getArch() == llvm::Triple::thumbeb || 2074 getTriple().getArch() == llvm::Triple::ppc || 2075 getTriple().getArch() == llvm::Triple::ppc64 || 2076 getTriple().getArch() == llvm::Triple::ppc64le || 2077 getTriple().getArch() == llvm::Triple::sparc || 2078 getTriple().getArch() == llvm::Triple::sparcv9 || 2079 getTriple().getArch() == llvm::Triple::systemz; 2080 } 2081 2082 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs, 2083 ArgStringList &CC1Args) const { 2084 const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion(); 2085 bool UseInitArrayDefault = 2086 getTriple().getArch() == llvm::Triple::aarch64 || 2087 getTriple().getArch() == llvm::Triple::aarch64_be || 2088 (getTriple().getOS() == llvm::Triple::Linux && 2089 (!V.isOlderThan(4, 7, 0) || 2090 getTriple().getEnvironment() == llvm::Triple::Android)) || 2091 getTriple().getOS() == llvm::Triple::NaCl; 2092 2093 if (DriverArgs.hasFlag(options::OPT_fuse_init_array, 2094 options::OPT_fno_use_init_array, 2095 UseInitArrayDefault)) 2096 CC1Args.push_back("-fuse-init-array"); 2097 } 2098 2099 /// Hexagon Toolchain 2100 2101 std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir, 2102 const ArgList &Args) { 2103 2104 // Locate the rest of the toolchain ... 2105 std::string GccToolchain = getGCCToolchainDir(Args); 2106 2107 if (!GccToolchain.empty()) 2108 return GccToolchain; 2109 2110 std::string InstallRelDir = InstalledDir + "/../../gnu"; 2111 if (llvm::sys::fs::exists(InstallRelDir)) 2112 return InstallRelDir; 2113 2114 std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu"; 2115 if (llvm::sys::fs::exists(PrefixRelDir)) 2116 return PrefixRelDir; 2117 2118 return InstallRelDir; 2119 } 2120 2121 static void GetHexagonLibraryPaths( 2122 const ArgList &Args, 2123 const std::string &Ver, 2124 const std::string &MarchString, 2125 const std::string &InstalledDir, 2126 ToolChain::path_list *LibPaths) 2127 { 2128 bool buildingLib = Args.hasArg(options::OPT_shared); 2129 2130 //---------------------------------------------------------------------------- 2131 // -L Args 2132 //---------------------------------------------------------------------------- 2133 for (arg_iterator 2134 it = Args.filtered_begin(options::OPT_L), 2135 ie = Args.filtered_end(); 2136 it != ie; 2137 ++it) { 2138 for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i) 2139 LibPaths->push_back((*it)->getValue(i)); 2140 } 2141 2142 //---------------------------------------------------------------------------- 2143 // Other standard paths 2144 //---------------------------------------------------------------------------- 2145 const std::string MarchSuffix = "/" + MarchString; 2146 const std::string G0Suffix = "/G0"; 2147 const std::string MarchG0Suffix = MarchSuffix + G0Suffix; 2148 const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir, Args) + "/"; 2149 2150 // lib/gcc/hexagon/... 2151 std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/"; 2152 if (buildingLib) { 2153 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix); 2154 LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix); 2155 } 2156 LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix); 2157 LibPaths->push_back(LibGCCHexagonDir + Ver); 2158 2159 // lib/gcc/... 2160 LibPaths->push_back(RootDir + "lib/gcc"); 2161 2162 // hexagon/lib/... 2163 std::string HexagonLibDir = RootDir + "hexagon/lib"; 2164 if (buildingLib) { 2165 LibPaths->push_back(HexagonLibDir + MarchG0Suffix); 2166 LibPaths->push_back(HexagonLibDir + G0Suffix); 2167 } 2168 LibPaths->push_back(HexagonLibDir + MarchSuffix); 2169 LibPaths->push_back(HexagonLibDir); 2170 } 2171 2172 Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple, 2173 const ArgList &Args) 2174 : Linux(D, Triple, Args) { 2175 const std::string InstalledDir(getDriver().getInstalledDir()); 2176 const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir, Args); 2177 2178 // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to 2179 // program paths 2180 const std::string BinDir(GnuDir + "/bin"); 2181 if (llvm::sys::fs::exists(BinDir)) 2182 getProgramPaths().push_back(BinDir); 2183 2184 // Determine version of GCC libraries and headers to use. 2185 const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon"); 2186 std::error_code ec; 2187 GCCVersion MaxVersion= GCCVersion::Parse("0.0.0"); 2188 for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de; 2189 !ec && di != de; di = di.increment(ec)) { 2190 GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path())); 2191 if (MaxVersion < cv) 2192 MaxVersion = cv; 2193 } 2194 GCCLibAndIncVersion = MaxVersion; 2195 2196 ToolChain::path_list *LibPaths= &getFilePaths(); 2197 2198 // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets 2199 // 'elf' OS type, so the Linux paths are not appropriate. When we actually 2200 // support 'linux' we'll need to fix this up 2201 LibPaths->clear(); 2202 2203 GetHexagonLibraryPaths( 2204 Args, 2205 GetGCCLibAndIncVersion(), 2206 GetTargetCPU(Args), 2207 InstalledDir, 2208 LibPaths); 2209 } 2210 2211 Hexagon_TC::~Hexagon_TC() { 2212 } 2213 2214 Tool *Hexagon_TC::buildAssembler() const { 2215 return new tools::hexagon::Assemble(*this); 2216 } 2217 2218 Tool *Hexagon_TC::buildLinker() const { 2219 return new tools::hexagon::Link(*this); 2220 } 2221 2222 void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 2223 ArgStringList &CC1Args) const { 2224 const Driver &D = getDriver(); 2225 2226 if (DriverArgs.hasArg(options::OPT_nostdinc) || 2227 DriverArgs.hasArg(options::OPT_nostdlibinc)) 2228 return; 2229 2230 std::string Ver(GetGCCLibAndIncVersion()); 2231 std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs); 2232 std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver); 2233 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include"); 2234 addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed"); 2235 addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include"); 2236 } 2237 2238 void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2239 ArgStringList &CC1Args) const { 2240 2241 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2242 DriverArgs.hasArg(options::OPT_nostdincxx)) 2243 return; 2244 2245 const Driver &D = getDriver(); 2246 std::string Ver(GetGCCLibAndIncVersion()); 2247 SmallString<128> IncludeDir( 2248 Hexagon_TC::GetGnuDir(D.InstalledDir, DriverArgs)); 2249 2250 llvm::sys::path::append(IncludeDir, "hexagon/include/c++/"); 2251 llvm::sys::path::append(IncludeDir, Ver); 2252 addSystemInclude(DriverArgs, CC1Args, IncludeDir); 2253 } 2254 2255 ToolChain::CXXStdlibType 2256 Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const { 2257 Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 2258 if (!A) 2259 return ToolChain::CST_Libstdcxx; 2260 2261 StringRef Value = A->getValue(); 2262 if (Value != "libstdc++") { 2263 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 2264 << A->getAsString(Args); 2265 } 2266 2267 return ToolChain::CST_Libstdcxx; 2268 } 2269 2270 static int getHexagonVersion(const ArgList &Args) { 2271 Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ); 2272 // Select the default CPU (v4) if none was given. 2273 if (!A) 2274 return 4; 2275 2276 // FIXME: produce errors if we cannot parse the version. 2277 StringRef WhichHexagon = A->getValue(); 2278 if (WhichHexagon.startswith("hexagonv")) { 2279 int Val; 2280 if (!WhichHexagon.substr(sizeof("hexagonv") - 1).getAsInteger(10, Val)) 2281 return Val; 2282 } 2283 if (WhichHexagon.startswith("v")) { 2284 int Val; 2285 if (!WhichHexagon.substr(1).getAsInteger(10, Val)) 2286 return Val; 2287 } 2288 2289 // FIXME: should probably be an error. 2290 return 4; 2291 } 2292 2293 StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args) 2294 { 2295 int V = getHexagonVersion(Args); 2296 // FIXME: We don't support versions < 4. We should error on them. 2297 switch (V) { 2298 default: 2299 llvm_unreachable("Unexpected version"); 2300 case 5: 2301 return "v5"; 2302 case 4: 2303 return "v4"; 2304 case 3: 2305 return "v3"; 2306 case 2: 2307 return "v2"; 2308 case 1: 2309 return "v1"; 2310 } 2311 } 2312 // End Hexagon 2313 2314 /// NaCl Toolchain 2315 NaCl_TC::NaCl_TC(const Driver &D, const llvm::Triple &Triple, 2316 const ArgList &Args) 2317 : Generic_ELF(D, Triple, Args) { 2318 2319 // Remove paths added by Generic_GCC. NaCl Toolchain cannot use the 2320 // default paths, and must instead only use the paths provided 2321 // with this toolchain based on architecture. 2322 path_list& file_paths = getFilePaths(); 2323 path_list& prog_paths = getProgramPaths(); 2324 2325 file_paths.clear(); 2326 prog_paths.clear(); 2327 2328 // Path for library files (libc.a, ...) 2329 std::string FilePath(getDriver().Dir + "/../"); 2330 2331 // Path for tools (clang, ld, etc..) 2332 std::string ProgPath(getDriver().Dir + "/../"); 2333 2334 // Path for toolchain libraries (libgcc.a, ...) 2335 std::string ToolPath(getDriver().ResourceDir + "/lib/"); 2336 2337 switch(Triple.getArch()) { 2338 case llvm::Triple::x86: { 2339 file_paths.push_back(FilePath + "x86_64-nacl/lib32"); 2340 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib32"); 2341 prog_paths.push_back(ProgPath + "x86_64-nacl/bin"); 2342 file_paths.push_back(ToolPath + "i686-nacl"); 2343 break; 2344 } 2345 case llvm::Triple::x86_64: { 2346 file_paths.push_back(FilePath + "x86_64-nacl/lib"); 2347 file_paths.push_back(FilePath + "x86_64-nacl/usr/lib"); 2348 prog_paths.push_back(ProgPath + "x86_64-nacl/bin"); 2349 file_paths.push_back(ToolPath + "x86_64-nacl"); 2350 break; 2351 } 2352 case llvm::Triple::arm: { 2353 file_paths.push_back(FilePath + "arm-nacl/lib"); 2354 file_paths.push_back(FilePath + "arm-nacl/usr/lib"); 2355 prog_paths.push_back(ProgPath + "arm-nacl/bin"); 2356 file_paths.push_back(ToolPath + "arm-nacl"); 2357 break; 2358 } 2359 default: 2360 break; 2361 } 2362 2363 // Use provided linker, not system linker 2364 Linker = GetProgramPath("ld"); 2365 NaClArmMacrosPath = GetFilePath("nacl-arm-macros.s"); 2366 } 2367 2368 void NaCl_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 2369 ArgStringList &CC1Args) const { 2370 const Driver &D = getDriver(); 2371 if (DriverArgs.hasArg(options::OPT_nostdinc)) 2372 return; 2373 2374 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { 2375 SmallString<128> P(D.ResourceDir); 2376 llvm::sys::path::append(P, "include"); 2377 addSystemInclude(DriverArgs, CC1Args, P.str()); 2378 } 2379 2380 if (DriverArgs.hasArg(options::OPT_nostdlibinc)) 2381 return; 2382 2383 SmallString<128> P(D.Dir + "/../"); 2384 if (getTriple().getArch() == llvm::Triple::arm) { 2385 llvm::sys::path::append(P, "arm-nacl/usr/include"); 2386 } else if (getTriple().getArch() == llvm::Triple::x86) { 2387 llvm::sys::path::append(P, "x86_64-nacl/usr/include"); 2388 } else if (getTriple().getArch() == llvm::Triple::x86_64) { 2389 llvm::sys::path::append(P, "x86_64-nacl/usr/include"); 2390 } else { 2391 return; 2392 } 2393 2394 addSystemInclude(DriverArgs, CC1Args, P.str()); 2395 llvm::sys::path::remove_filename(P); 2396 llvm::sys::path::remove_filename(P); 2397 llvm::sys::path::append(P, "include"); 2398 addSystemInclude(DriverArgs, CC1Args, P.str()); 2399 } 2400 2401 void NaCl_TC::AddCXXStdlibLibArgs(const ArgList &Args, 2402 ArgStringList &CmdArgs) const { 2403 // Check for -stdlib= flags. We only support libc++ but this consumes the arg 2404 // if the value is libc++, and emits an error for other values. 2405 GetCXXStdlibType(Args); 2406 CmdArgs.push_back("-lc++"); 2407 } 2408 2409 void NaCl_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2410 ArgStringList &CC1Args) const { 2411 const Driver &D = getDriver(); 2412 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2413 DriverArgs.hasArg(options::OPT_nostdincxx)) 2414 return; 2415 2416 // Check for -stdlib= flags. We only support libc++ but this consumes the arg 2417 // if the value is libc++, and emits an error for other values. 2418 GetCXXStdlibType(DriverArgs); 2419 2420 if (getTriple().getArch() == llvm::Triple::arm) { 2421 SmallString<128> P(D.Dir + "/../"); 2422 llvm::sys::path::append(P, "arm-nacl/include/c++/v1"); 2423 addSystemInclude(DriverArgs, CC1Args, P.str()); 2424 } else if (getTriple().getArch() == llvm::Triple::x86) { 2425 SmallString<128> P(D.Dir + "/../"); 2426 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1"); 2427 addSystemInclude(DriverArgs, CC1Args, P.str()); 2428 } else if (getTriple().getArch() == llvm::Triple::x86_64) { 2429 SmallString<128> P(D.Dir + "/../"); 2430 llvm::sys::path::append(P, "x86_64-nacl/include/c++/v1"); 2431 addSystemInclude(DriverArgs, CC1Args, P.str()); 2432 } 2433 } 2434 2435 ToolChain::CXXStdlibType NaCl_TC::GetCXXStdlibType(const ArgList &Args) const { 2436 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 2437 StringRef Value = A->getValue(); 2438 if (Value == "libc++") 2439 return ToolChain::CST_Libcxx; 2440 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 2441 << A->getAsString(Args); 2442 } 2443 2444 return ToolChain::CST_Libcxx; 2445 } 2446 2447 std::string NaCl_TC::ComputeEffectiveClangTriple( 2448 const ArgList &Args, types::ID InputType) const { 2449 llvm::Triple TheTriple(ComputeLLVMTriple(Args, InputType)); 2450 if (TheTriple.getArch() == llvm::Triple::arm && 2451 TheTriple.getEnvironment() == llvm::Triple::UnknownEnvironment) 2452 TheTriple.setEnvironment(llvm::Triple::GNUEABIHF); 2453 return TheTriple.getTriple(); 2454 } 2455 2456 Tool *NaCl_TC::buildLinker() const { 2457 return new tools::nacltools::Link(*this); 2458 } 2459 2460 Tool *NaCl_TC::buildAssembler() const { 2461 if (getTriple().getArch() == llvm::Triple::arm) 2462 return new tools::nacltools::AssembleARM(*this); 2463 return new tools::gnutools::Assemble(*this); 2464 } 2465 // End NaCl 2466 2467 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform 2468 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target. 2469 /// Currently does not support anything else but compilation. 2470 2471 TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple, 2472 const ArgList &Args) 2473 : ToolChain(D, Triple, Args) { 2474 // Path mangling to find libexec 2475 std::string Path(getDriver().Dir); 2476 2477 Path += "/../libexec"; 2478 getProgramPaths().push_back(Path); 2479 } 2480 2481 TCEToolChain::~TCEToolChain() { 2482 } 2483 2484 bool TCEToolChain::IsMathErrnoDefault() const { 2485 return true; 2486 } 2487 2488 bool TCEToolChain::isPICDefault() const { 2489 return false; 2490 } 2491 2492 bool TCEToolChain::isPIEDefault() const { 2493 return false; 2494 } 2495 2496 bool TCEToolChain::isPICDefaultForced() const { 2497 return false; 2498 } 2499 2500 // CloudABI - CloudABI tool chain which can call ld(1) directly. 2501 2502 CloudABI::CloudABI(const Driver &D, const llvm::Triple &Triple, 2503 const ArgList &Args) 2504 : Generic_ELF(D, Triple, Args) { 2505 SmallString<128> P(getDriver().Dir); 2506 llvm::sys::path::append(P, "..", getTriple().str(), "lib"); 2507 getFilePaths().push_back(P.str()); 2508 } 2509 2510 void CloudABI::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2511 ArgStringList &CC1Args) const { 2512 if (DriverArgs.hasArg(options::OPT_nostdlibinc) && 2513 DriverArgs.hasArg(options::OPT_nostdincxx)) 2514 return; 2515 2516 SmallString<128> P(getDriver().Dir); 2517 llvm::sys::path::append(P, "..", getTriple().str(), "include/c++/v1"); 2518 addSystemInclude(DriverArgs, CC1Args, P.str()); 2519 } 2520 2521 void CloudABI::AddCXXStdlibLibArgs(const ArgList &Args, 2522 ArgStringList &CmdArgs) const { 2523 CmdArgs.push_back("-lc++"); 2524 CmdArgs.push_back("-lc++abi"); 2525 CmdArgs.push_back("-lunwind"); 2526 } 2527 2528 Tool *CloudABI::buildLinker() const { return new tools::cloudabi::Link(*this); } 2529 2530 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly. 2531 2532 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) 2533 : Generic_ELF(D, Triple, Args) { 2534 getFilePaths().push_back(getDriver().Dir + "/../lib"); 2535 getFilePaths().push_back("/usr/lib"); 2536 } 2537 2538 Tool *OpenBSD::buildAssembler() const { 2539 return new tools::openbsd::Assemble(*this); 2540 } 2541 2542 Tool *OpenBSD::buildLinker() const { 2543 return new tools::openbsd::Link(*this); 2544 } 2545 2546 /// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly. 2547 2548 Bitrig::Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) 2549 : Generic_ELF(D, Triple, Args) { 2550 getFilePaths().push_back(getDriver().Dir + "/../lib"); 2551 getFilePaths().push_back("/usr/lib"); 2552 } 2553 2554 Tool *Bitrig::buildAssembler() const { 2555 return new tools::bitrig::Assemble(*this); 2556 } 2557 2558 Tool *Bitrig::buildLinker() const { 2559 return new tools::bitrig::Link(*this); 2560 } 2561 2562 ToolChain::CXXStdlibType 2563 Bitrig::GetCXXStdlibType(const ArgList &Args) const { 2564 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 2565 StringRef Value = A->getValue(); 2566 if (Value == "libstdc++") 2567 return ToolChain::CST_Libstdcxx; 2568 if (Value == "libc++") 2569 return ToolChain::CST_Libcxx; 2570 2571 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 2572 << A->getAsString(Args); 2573 } 2574 return ToolChain::CST_Libcxx; 2575 } 2576 2577 void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2578 ArgStringList &CC1Args) const { 2579 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2580 DriverArgs.hasArg(options::OPT_nostdincxx)) 2581 return; 2582 2583 switch (GetCXXStdlibType(DriverArgs)) { 2584 case ToolChain::CST_Libcxx: 2585 addSystemInclude(DriverArgs, CC1Args, 2586 getDriver().SysRoot + "/usr/include/c++/v1"); 2587 break; 2588 case ToolChain::CST_Libstdcxx: 2589 addSystemInclude(DriverArgs, CC1Args, 2590 getDriver().SysRoot + "/usr/include/c++/stdc++"); 2591 addSystemInclude(DriverArgs, CC1Args, 2592 getDriver().SysRoot + "/usr/include/c++/stdc++/backward"); 2593 2594 StringRef Triple = getTriple().str(); 2595 if (Triple.startswith("amd64")) 2596 addSystemInclude(DriverArgs, CC1Args, 2597 getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" + 2598 Triple.substr(5)); 2599 else 2600 addSystemInclude(DriverArgs, CC1Args, 2601 getDriver().SysRoot + "/usr/include/c++/stdc++/" + 2602 Triple); 2603 break; 2604 } 2605 } 2606 2607 void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args, 2608 ArgStringList &CmdArgs) const { 2609 switch (GetCXXStdlibType(Args)) { 2610 case ToolChain::CST_Libcxx: 2611 CmdArgs.push_back("-lc++"); 2612 CmdArgs.push_back("-lc++abi"); 2613 CmdArgs.push_back("-lpthread"); 2614 break; 2615 case ToolChain::CST_Libstdcxx: 2616 CmdArgs.push_back("-lstdc++"); 2617 break; 2618 } 2619 } 2620 2621 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly. 2622 2623 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) 2624 : Generic_ELF(D, Triple, Args) { 2625 2626 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall 2627 // back to '/usr/lib' if it doesn't exist. 2628 if ((Triple.getArch() == llvm::Triple::x86 || 2629 Triple.getArch() == llvm::Triple::ppc) && 2630 llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o")) 2631 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32"); 2632 else 2633 getFilePaths().push_back(getDriver().SysRoot + "/usr/lib"); 2634 } 2635 2636 ToolChain::CXXStdlibType 2637 FreeBSD::GetCXXStdlibType(const ArgList &Args) const { 2638 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 2639 StringRef Value = A->getValue(); 2640 if (Value == "libstdc++") 2641 return ToolChain::CST_Libstdcxx; 2642 if (Value == "libc++") 2643 return ToolChain::CST_Libcxx; 2644 2645 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 2646 << A->getAsString(Args); 2647 } 2648 if (getTriple().getOSMajorVersion() >= 10) 2649 return ToolChain::CST_Libcxx; 2650 return ToolChain::CST_Libstdcxx; 2651 } 2652 2653 void FreeBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2654 ArgStringList &CC1Args) const { 2655 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2656 DriverArgs.hasArg(options::OPT_nostdincxx)) 2657 return; 2658 2659 switch (GetCXXStdlibType(DriverArgs)) { 2660 case ToolChain::CST_Libcxx: 2661 addSystemInclude(DriverArgs, CC1Args, 2662 getDriver().SysRoot + "/usr/include/c++/v1"); 2663 break; 2664 case ToolChain::CST_Libstdcxx: 2665 addSystemInclude(DriverArgs, CC1Args, 2666 getDriver().SysRoot + "/usr/include/c++/4.2"); 2667 addSystemInclude(DriverArgs, CC1Args, 2668 getDriver().SysRoot + "/usr/include/c++/4.2/backward"); 2669 break; 2670 } 2671 } 2672 2673 Tool *FreeBSD::buildAssembler() const { 2674 return new tools::freebsd::Assemble(*this); 2675 } 2676 2677 Tool *FreeBSD::buildLinker() const { 2678 return new tools::freebsd::Link(*this); 2679 } 2680 2681 bool FreeBSD::UseSjLjExceptions() const { 2682 // FreeBSD uses SjLj exceptions on ARM oabi. 2683 switch (getTriple().getEnvironment()) { 2684 case llvm::Triple::GNUEABIHF: 2685 case llvm::Triple::GNUEABI: 2686 case llvm::Triple::EABI: 2687 return false; 2688 2689 default: 2690 return (getTriple().getArch() == llvm::Triple::arm || 2691 getTriple().getArch() == llvm::Triple::thumb); 2692 } 2693 } 2694 2695 bool FreeBSD::HasNativeLLVMSupport() const { 2696 return true; 2697 } 2698 2699 bool FreeBSD::isPIEDefault() const { 2700 return getSanitizerArgs().requiresPIE(); 2701 } 2702 2703 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly. 2704 2705 NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) 2706 : Generic_ELF(D, Triple, Args) { 2707 2708 if (getDriver().UseStdLib) { 2709 // When targeting a 32-bit platform, try the special directory used on 2710 // 64-bit hosts, and only fall back to the main library directory if that 2711 // doesn't work. 2712 // FIXME: It'd be nicer to test if this directory exists, but I'm not sure 2713 // what all logic is needed to emulate the '=' prefix here. 2714 switch (Triple.getArch()) { 2715 case llvm::Triple::x86: 2716 getFilePaths().push_back("=/usr/lib/i386"); 2717 break; 2718 case llvm::Triple::arm: 2719 case llvm::Triple::armeb: 2720 case llvm::Triple::thumb: 2721 case llvm::Triple::thumbeb: 2722 switch (Triple.getEnvironment()) { 2723 case llvm::Triple::EABI: 2724 case llvm::Triple::GNUEABI: 2725 getFilePaths().push_back("=/usr/lib/eabi"); 2726 break; 2727 case llvm::Triple::EABIHF: 2728 case llvm::Triple::GNUEABIHF: 2729 getFilePaths().push_back("=/usr/lib/eabihf"); 2730 break; 2731 default: 2732 getFilePaths().push_back("=/usr/lib/oabi"); 2733 break; 2734 } 2735 break; 2736 case llvm::Triple::mips64: 2737 case llvm::Triple::mips64el: 2738 if (tools::mips::hasMipsAbiArg(Args, "o32")) 2739 getFilePaths().push_back("=/usr/lib/o32"); 2740 else if (tools::mips::hasMipsAbiArg(Args, "64")) 2741 getFilePaths().push_back("=/usr/lib/64"); 2742 break; 2743 case llvm::Triple::ppc: 2744 getFilePaths().push_back("=/usr/lib/powerpc"); 2745 break; 2746 case llvm::Triple::sparc: 2747 getFilePaths().push_back("=/usr/lib/sparc"); 2748 break; 2749 default: 2750 break; 2751 } 2752 2753 getFilePaths().push_back("=/usr/lib"); 2754 } 2755 } 2756 2757 Tool *NetBSD::buildAssembler() const { 2758 return new tools::netbsd::Assemble(*this); 2759 } 2760 2761 Tool *NetBSD::buildLinker() const { 2762 return new tools::netbsd::Link(*this); 2763 } 2764 2765 ToolChain::CXXStdlibType 2766 NetBSD::GetCXXStdlibType(const ArgList &Args) const { 2767 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { 2768 StringRef Value = A->getValue(); 2769 if (Value == "libstdc++") 2770 return ToolChain::CST_Libstdcxx; 2771 if (Value == "libc++") 2772 return ToolChain::CST_Libcxx; 2773 2774 getDriver().Diag(diag::err_drv_invalid_stdlib_name) 2775 << A->getAsString(Args); 2776 } 2777 2778 unsigned Major, Minor, Micro; 2779 getTriple().getOSVersion(Major, Minor, Micro); 2780 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) { 2781 switch (getArch()) { 2782 case llvm::Triple::aarch64: 2783 case llvm::Triple::arm: 2784 case llvm::Triple::armeb: 2785 case llvm::Triple::thumb: 2786 case llvm::Triple::thumbeb: 2787 case llvm::Triple::ppc: 2788 case llvm::Triple::ppc64: 2789 case llvm::Triple::ppc64le: 2790 case llvm::Triple::x86: 2791 case llvm::Triple::x86_64: 2792 return ToolChain::CST_Libcxx; 2793 default: 2794 break; 2795 } 2796 } 2797 return ToolChain::CST_Libstdcxx; 2798 } 2799 2800 void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 2801 ArgStringList &CC1Args) const { 2802 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 2803 DriverArgs.hasArg(options::OPT_nostdincxx)) 2804 return; 2805 2806 switch (GetCXXStdlibType(DriverArgs)) { 2807 case ToolChain::CST_Libcxx: 2808 addSystemInclude(DriverArgs, CC1Args, 2809 getDriver().SysRoot + "/usr/include/c++/"); 2810 break; 2811 case ToolChain::CST_Libstdcxx: 2812 addSystemInclude(DriverArgs, CC1Args, 2813 getDriver().SysRoot + "/usr/include/g++"); 2814 addSystemInclude(DriverArgs, CC1Args, 2815 getDriver().SysRoot + "/usr/include/g++/backward"); 2816 break; 2817 } 2818 } 2819 2820 /// Minix - Minix tool chain which can call as(1) and ld(1) directly. 2821 2822 Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) 2823 : Generic_ELF(D, Triple, Args) { 2824 getFilePaths().push_back(getDriver().Dir + "/../lib"); 2825 getFilePaths().push_back("/usr/lib"); 2826 } 2827 2828 Tool *Minix::buildAssembler() const { 2829 return new tools::minix::Assemble(*this); 2830 } 2831 2832 Tool *Minix::buildLinker() const { 2833 return new tools::minix::Link(*this); 2834 } 2835 2836 /// Solaris - Solaris tool chain which can call as(1) and ld(1) directly. 2837 2838 Solaris::Solaris(const Driver &D, const llvm::Triple& Triple, 2839 const ArgList &Args) 2840 : Generic_GCC(D, Triple, Args) { 2841 2842 getProgramPaths().push_back(getDriver().getInstalledDir()); 2843 if (getDriver().getInstalledDir() != getDriver().Dir) 2844 getProgramPaths().push_back(getDriver().Dir); 2845 2846 getFilePaths().push_back(getDriver().Dir + "/../lib"); 2847 getFilePaths().push_back("/usr/lib"); 2848 } 2849 2850 Tool *Solaris::buildAssembler() const { 2851 return new tools::solaris::Assemble(*this); 2852 } 2853 2854 Tool *Solaris::buildLinker() const { 2855 return new tools::solaris::Link(*this); 2856 } 2857 2858 /// Distribution (very bare-bones at the moment). 2859 2860 enum Distro { 2861 ArchLinux, 2862 DebianLenny, 2863 DebianSqueeze, 2864 DebianWheezy, 2865 DebianJessie, 2866 DebianStretch, 2867 Exherbo, 2868 RHEL4, 2869 RHEL5, 2870 RHEL6, 2871 RHEL7, 2872 Fedora, 2873 OpenSUSE, 2874 UbuntuHardy, 2875 UbuntuIntrepid, 2876 UbuntuJaunty, 2877 UbuntuKarmic, 2878 UbuntuLucid, 2879 UbuntuMaverick, 2880 UbuntuNatty, 2881 UbuntuOneiric, 2882 UbuntuPrecise, 2883 UbuntuQuantal, 2884 UbuntuRaring, 2885 UbuntuSaucy, 2886 UbuntuTrusty, 2887 UbuntuUtopic, 2888 UbuntuVivid, 2889 UnknownDistro 2890 }; 2891 2892 static bool IsRedhat(enum Distro Distro) { 2893 return Distro == Fedora || (Distro >= RHEL4 && Distro <= RHEL7); 2894 } 2895 2896 static bool IsOpenSUSE(enum Distro Distro) { 2897 return Distro == OpenSUSE; 2898 } 2899 2900 static bool IsDebian(enum Distro Distro) { 2901 return Distro >= DebianLenny && Distro <= DebianStretch; 2902 } 2903 2904 static bool IsUbuntu(enum Distro Distro) { 2905 return Distro >= UbuntuHardy && Distro <= UbuntuVivid; 2906 } 2907 2908 static Distro DetectDistro(llvm::Triple::ArchType Arch) { 2909 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File = 2910 llvm::MemoryBuffer::getFile("/etc/lsb-release"); 2911 if (File) { 2912 StringRef Data = File.get()->getBuffer(); 2913 SmallVector<StringRef, 16> Lines; 2914 Data.split(Lines, "\n"); 2915 Distro Version = UnknownDistro; 2916 for (unsigned i = 0, s = Lines.size(); i != s; ++i) 2917 if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME=")) 2918 Version = llvm::StringSwitch<Distro>(Lines[i].substr(17)) 2919 .Case("hardy", UbuntuHardy) 2920 .Case("intrepid", UbuntuIntrepid) 2921 .Case("jaunty", UbuntuJaunty) 2922 .Case("karmic", UbuntuKarmic) 2923 .Case("lucid", UbuntuLucid) 2924 .Case("maverick", UbuntuMaverick) 2925 .Case("natty", UbuntuNatty) 2926 .Case("oneiric", UbuntuOneiric) 2927 .Case("precise", UbuntuPrecise) 2928 .Case("quantal", UbuntuQuantal) 2929 .Case("raring", UbuntuRaring) 2930 .Case("saucy", UbuntuSaucy) 2931 .Case("trusty", UbuntuTrusty) 2932 .Case("utopic", UbuntuUtopic) 2933 .Case("vivid", UbuntuVivid) 2934 .Default(UnknownDistro); 2935 return Version; 2936 } 2937 2938 File = llvm::MemoryBuffer::getFile("/etc/redhat-release"); 2939 if (File) { 2940 StringRef Data = File.get()->getBuffer(); 2941 if (Data.startswith("Fedora release")) 2942 return Fedora; 2943 if (Data.startswith("Red Hat Enterprise Linux") || 2944 Data.startswith("CentOS")) { 2945 if (Data.find("release 7") != StringRef::npos) 2946 return RHEL7; 2947 else if (Data.find("release 6") != StringRef::npos) 2948 return RHEL6; 2949 else if (Data.find("release 5") != StringRef::npos) 2950 return RHEL5; 2951 else if (Data.find("release 4") != StringRef::npos) 2952 return RHEL4; 2953 } 2954 return UnknownDistro; 2955 } 2956 2957 File = llvm::MemoryBuffer::getFile("/etc/debian_version"); 2958 if (File) { 2959 StringRef Data = File.get()->getBuffer(); 2960 if (Data[0] == '5') 2961 return DebianLenny; 2962 else if (Data.startswith("squeeze/sid") || Data[0] == '6') 2963 return DebianSqueeze; 2964 else if (Data.startswith("wheezy/sid") || Data[0] == '7') 2965 return DebianWheezy; 2966 else if (Data.startswith("jessie/sid") || Data[0] == '8') 2967 return DebianJessie; 2968 else if (Data.startswith("stretch/sid") || Data[0] == '9') 2969 return DebianStretch; 2970 return UnknownDistro; 2971 } 2972 2973 if (llvm::sys::fs::exists("/etc/SuSE-release")) 2974 return OpenSUSE; 2975 2976 if (llvm::sys::fs::exists("/etc/exherbo-release")) 2977 return Exherbo; 2978 2979 if (llvm::sys::fs::exists("/etc/arch-release")) 2980 return ArchLinux; 2981 2982 return UnknownDistro; 2983 } 2984 2985 /// \brief Get our best guess at the multiarch triple for a target. 2986 /// 2987 /// Debian-based systems are starting to use a multiarch setup where they use 2988 /// a target-triple directory in the library and header search paths. 2989 /// Unfortunately, this triple does not align with the vanilla target triple, 2990 /// so we provide a rough mapping here. 2991 static std::string getMultiarchTriple(const llvm::Triple &TargetTriple, 2992 StringRef SysRoot) { 2993 // For most architectures, just use whatever we have rather than trying to be 2994 // clever. 2995 switch (TargetTriple.getArch()) { 2996 default: 2997 return TargetTriple.str(); 2998 2999 // We use the existence of '/lib/<triple>' as a directory to detect some 3000 // common linux triples that don't quite match the Clang triple for both 3001 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these 3002 // regardless of what the actual target triple is. 3003 case llvm::Triple::arm: 3004 case llvm::Triple::thumb: 3005 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) { 3006 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf")) 3007 return "arm-linux-gnueabihf"; 3008 } else { 3009 if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi")) 3010 return "arm-linux-gnueabi"; 3011 } 3012 return TargetTriple.str(); 3013 case llvm::Triple::armeb: 3014 case llvm::Triple::thumbeb: 3015 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) { 3016 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabihf")) 3017 return "armeb-linux-gnueabihf"; 3018 } else { 3019 if (llvm::sys::fs::exists(SysRoot + "/lib/armeb-linux-gnueabi")) 3020 return "armeb-linux-gnueabi"; 3021 } 3022 return TargetTriple.str(); 3023 case llvm::Triple::x86: 3024 if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu")) 3025 return "i386-linux-gnu"; 3026 return TargetTriple.str(); 3027 case llvm::Triple::x86_64: 3028 // We don't want this for x32, otherwise it will match x86_64 libs 3029 if (TargetTriple.getEnvironment() != llvm::Triple::GNUX32 && 3030 llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu")) 3031 return "x86_64-linux-gnu"; 3032 return TargetTriple.str(); 3033 case llvm::Triple::aarch64: 3034 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu")) 3035 return "aarch64-linux-gnu"; 3036 return TargetTriple.str(); 3037 case llvm::Triple::aarch64_be: 3038 if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64_be-linux-gnu")) 3039 return "aarch64_be-linux-gnu"; 3040 return TargetTriple.str(); 3041 case llvm::Triple::mips: 3042 if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu")) 3043 return "mips-linux-gnu"; 3044 return TargetTriple.str(); 3045 case llvm::Triple::mipsel: 3046 if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu")) 3047 return "mipsel-linux-gnu"; 3048 return TargetTriple.str(); 3049 case llvm::Triple::mips64: 3050 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnu")) 3051 return "mips64-linux-gnu"; 3052 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64-linux-gnuabi64")) 3053 return "mips64-linux-gnuabi64"; 3054 return TargetTriple.str(); 3055 case llvm::Triple::mips64el: 3056 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnu")) 3057 return "mips64el-linux-gnu"; 3058 if (llvm::sys::fs::exists(SysRoot + "/lib/mips64el-linux-gnuabi64")) 3059 return "mips64el-linux-gnuabi64"; 3060 return TargetTriple.str(); 3061 case llvm::Triple::ppc: 3062 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnuspe")) 3063 return "powerpc-linux-gnuspe"; 3064 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu")) 3065 return "powerpc-linux-gnu"; 3066 return TargetTriple.str(); 3067 case llvm::Triple::ppc64: 3068 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu")) 3069 return "powerpc64-linux-gnu"; 3070 case llvm::Triple::ppc64le: 3071 if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64le-linux-gnu")) 3072 return "powerpc64le-linux-gnu"; 3073 return TargetTriple.str(); 3074 } 3075 } 3076 3077 static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) { 3078 if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str()); 3079 } 3080 3081 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) { 3082 if (isMipsArch(Triple.getArch())) { 3083 // lib32 directory has a special meaning on MIPS targets. 3084 // It contains N32 ABI binaries. Use this folder if produce 3085 // code for N32 ABI only. 3086 if (tools::mips::hasMipsAbiArg(Args, "n32")) 3087 return "lib32"; 3088 return Triple.isArch32Bit() ? "lib" : "lib64"; 3089 } 3090 3091 // It happens that only x86 and PPC use the 'lib32' variant of oslibdir, and 3092 // using that variant while targeting other architectures causes problems 3093 // because the libraries are laid out in shared system roots that can't cope 3094 // with a 'lib32' library search path being considered. So we only enable 3095 // them when we know we may need it. 3096 // 3097 // FIXME: This is a bit of a hack. We should really unify this code for 3098 // reasoning about oslibdir spellings with the lib dir spellings in the 3099 // GCCInstallationDetector, but that is a more significant refactoring. 3100 if (Triple.getArch() == llvm::Triple::x86 || 3101 Triple.getArch() == llvm::Triple::ppc) 3102 return "lib32"; 3103 3104 if (Triple.getArch() == llvm::Triple::x86_64 && 3105 Triple.getEnvironment() == llvm::Triple::GNUX32) 3106 return "libx32"; 3107 3108 return Triple.isArch32Bit() ? "lib" : "lib64"; 3109 } 3110 3111 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) 3112 : Generic_ELF(D, Triple, Args) { 3113 GCCInstallation.init(D, Triple, Args); 3114 Multilibs = GCCInstallation.getMultilibs(); 3115 llvm::Triple::ArchType Arch = Triple.getArch(); 3116 std::string SysRoot = computeSysRoot(); 3117 3118 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at 3119 // least) put various tools in a triple-prefixed directory off of the parent 3120 // of the GCC installation. We use the GCC triple here to ensure that we end 3121 // up with tools that support the same amount of cross compiling as the 3122 // detected GCC installation. For example, if we find a GCC installation 3123 // targeting x86_64, but it is a bi-arch GCC installation, it can also be 3124 // used to target i386. 3125 // FIXME: This seems unlikely to be Linux-specific. 3126 ToolChain::path_list &PPaths = getProgramPaths(); 3127 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" + 3128 GCCInstallation.getTriple().str() + "/bin").str()); 3129 3130 Linker = GetLinkerPath(); 3131 3132 Distro Distro = DetectDistro(Arch); 3133 3134 if (IsOpenSUSE(Distro) || IsUbuntu(Distro)) { 3135 ExtraOpts.push_back("-z"); 3136 ExtraOpts.push_back("relro"); 3137 } 3138 3139 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) 3140 ExtraOpts.push_back("-X"); 3141 3142 const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android; 3143 const bool IsMips = isMipsArch(Arch); 3144 3145 if (IsMips && !SysRoot.empty()) 3146 ExtraOpts.push_back("--sysroot=" + SysRoot); 3147 3148 // Do not use 'gnu' hash style for Mips targets because .gnu.hash 3149 // and the MIPS ABI require .dynsym to be sorted in different ways. 3150 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS 3151 // ABI requires a mapping between the GOT and the symbol table. 3152 // Android loader does not support .gnu.hash. 3153 if (!IsMips && !IsAndroid) { 3154 if (IsRedhat(Distro) || IsOpenSUSE(Distro) || 3155 (IsUbuntu(Distro) && Distro >= UbuntuMaverick)) 3156 ExtraOpts.push_back("--hash-style=gnu"); 3157 3158 if (IsDebian(Distro) || IsOpenSUSE(Distro) || Distro == UbuntuLucid || 3159 Distro == UbuntuJaunty || Distro == UbuntuKarmic) 3160 ExtraOpts.push_back("--hash-style=both"); 3161 } 3162 3163 if (IsRedhat(Distro)) 3164 ExtraOpts.push_back("--no-add-needed"); 3165 3166 if ((IsDebian(Distro) && Distro >= DebianSqueeze) || IsOpenSUSE(Distro) || 3167 (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) || 3168 (IsUbuntu(Distro) && Distro >= UbuntuKarmic)) 3169 ExtraOpts.push_back("--build-id"); 3170 3171 if (IsOpenSUSE(Distro)) 3172 ExtraOpts.push_back("--enable-new-dtags"); 3173 3174 // The selection of paths to try here is designed to match the patterns which 3175 // the GCC driver itself uses, as this is part of the GCC-compatible driver. 3176 // This was determined by running GCC in a fake filesystem, creating all 3177 // possible permutations of these directories, and seeing which ones it added 3178 // to the link paths. 3179 path_list &Paths = getFilePaths(); 3180 3181 const std::string OSLibDir = getOSLibDir(Triple, Args); 3182 const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot); 3183 3184 // Add the multilib suffixed paths where they are available. 3185 if (GCCInstallation.isValid()) { 3186 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3187 const std::string &LibPath = GCCInstallation.getParentLibPath(); 3188 const Multilib &Multilib = GCCInstallation.getMultilib(); 3189 3190 // Sourcery CodeBench MIPS toolchain holds some libraries under 3191 // a biarch-like suffix of the GCC installation. 3192 addPathIfExists((GCCInstallation.getInstallPath() + 3193 Multilib.gccSuffix()), 3194 Paths); 3195 3196 // GCC cross compiling toolchains will install target libraries which ship 3197 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as 3198 // any part of the GCC installation in 3199 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat 3200 // debatable, but is the reality today. We need to search this tree even 3201 // when we have a sysroot somewhere else. It is the responsibility of 3202 // whomever is doing the cross build targeting a sysroot using a GCC 3203 // installation that is *not* within the system root to ensure two things: 3204 // 3205 // 1) Any DSOs that are linked in from this tree or from the install path 3206 // above must be present on the system root and found via an 3207 // appropriate rpath. 3208 // 2) There must not be libraries installed into 3209 // <prefix>/<triple>/<libdir> unless they should be preferred over 3210 // those within the system root. 3211 // 3212 // Note that this matches the GCC behavior. See the below comment for where 3213 // Clang diverges from GCC's behavior. 3214 addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir + 3215 Multilib.osSuffix(), 3216 Paths); 3217 3218 // If the GCC installation we found is inside of the sysroot, we want to 3219 // prefer libraries installed in the parent prefix of the GCC installation. 3220 // It is important to *not* use these paths when the GCC installation is 3221 // outside of the system root as that can pick up unintended libraries. 3222 // This usually happens when there is an external cross compiler on the 3223 // host system, and a more minimal sysroot available that is the target of 3224 // the cross. Note that GCC does include some of these directories in some 3225 // configurations but this seems somewhere between questionable and simply 3226 // a bug. 3227 if (StringRef(LibPath).startswith(SysRoot)) { 3228 addPathIfExists(LibPath + "/" + MultiarchTriple, Paths); 3229 addPathIfExists(LibPath + "/../" + OSLibDir, Paths); 3230 } 3231 } 3232 3233 // Similar to the logic for GCC above, if we currently running Clang inside 3234 // of the requested system root, add its parent library paths to 3235 // those searched. 3236 // FIXME: It's not clear whether we should use the driver's installed 3237 // directory ('Dir' below) or the ResourceDir. 3238 if (StringRef(D.Dir).startswith(SysRoot)) { 3239 addPathIfExists(D.Dir + "/../lib/" + MultiarchTriple, Paths); 3240 addPathIfExists(D.Dir + "/../" + OSLibDir, Paths); 3241 } 3242 3243 addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths); 3244 addPathIfExists(SysRoot + "/lib/../" + OSLibDir, Paths); 3245 addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths); 3246 addPathIfExists(SysRoot + "/usr/lib/../" + OSLibDir, Paths); 3247 3248 // Try walking via the GCC triple path in case of biarch or multiarch GCC 3249 // installations with strange symlinks. 3250 if (GCCInstallation.isValid()) { 3251 addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() + 3252 "/../../" + OSLibDir, Paths); 3253 3254 // Add the 'other' biarch variant path 3255 Multilib BiarchSibling; 3256 if (GCCInstallation.getBiarchSibling(BiarchSibling)) { 3257 addPathIfExists(GCCInstallation.getInstallPath() + 3258 BiarchSibling.gccSuffix(), Paths); 3259 } 3260 3261 // See comments above on the multilib variant for details of why this is 3262 // included even from outside the sysroot. 3263 const std::string &LibPath = GCCInstallation.getParentLibPath(); 3264 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3265 const Multilib &Multilib = GCCInstallation.getMultilib(); 3266 addPathIfExists(LibPath + "/../" + GCCTriple.str() + 3267 "/lib" + Multilib.osSuffix(), Paths); 3268 3269 // See comments above on the multilib variant for details of why this is 3270 // only included from within the sysroot. 3271 if (StringRef(LibPath).startswith(SysRoot)) 3272 addPathIfExists(LibPath, Paths); 3273 } 3274 3275 // Similar to the logic for GCC above, if we are currently running Clang 3276 // inside of the requested system root, add its parent library path to those 3277 // searched. 3278 // FIXME: It's not clear whether we should use the driver's installed 3279 // directory ('Dir' below) or the ResourceDir. 3280 if (StringRef(D.Dir).startswith(SysRoot)) 3281 addPathIfExists(D.Dir + "/../lib", Paths); 3282 3283 addPathIfExists(SysRoot + "/lib", Paths); 3284 addPathIfExists(SysRoot + "/usr/lib", Paths); 3285 } 3286 3287 bool Linux::HasNativeLLVMSupport() const { 3288 return true; 3289 } 3290 3291 Tool *Linux::buildLinker() const { 3292 return new tools::gnutools::Link(*this); 3293 } 3294 3295 Tool *Linux::buildAssembler() const { 3296 return new tools::gnutools::Assemble(*this); 3297 } 3298 3299 std::string Linux::computeSysRoot() const { 3300 if (!getDriver().SysRoot.empty()) 3301 return getDriver().SysRoot; 3302 3303 if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch())) 3304 return std::string(); 3305 3306 // Standalone MIPS toolchains use different names for sysroot folder 3307 // and put it into different places. Here we try to check some known 3308 // variants. 3309 3310 const StringRef InstallDir = GCCInstallation.getInstallPath(); 3311 const StringRef TripleStr = GCCInstallation.getTriple().str(); 3312 const Multilib &Multilib = GCCInstallation.getMultilib(); 3313 3314 std::string Path = (InstallDir + "/../../../../" + TripleStr + "/libc" + 3315 Multilib.osSuffix()).str(); 3316 3317 if (llvm::sys::fs::exists(Path)) 3318 return Path; 3319 3320 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str(); 3321 3322 if (llvm::sys::fs::exists(Path)) 3323 return Path; 3324 3325 return std::string(); 3326 } 3327 3328 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 3329 ArgStringList &CC1Args) const { 3330 const Driver &D = getDriver(); 3331 std::string SysRoot = computeSysRoot(); 3332 3333 if (DriverArgs.hasArg(options::OPT_nostdinc)) 3334 return; 3335 3336 if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) 3337 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include"); 3338 3339 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { 3340 SmallString<128> P(D.ResourceDir); 3341 llvm::sys::path::append(P, "include"); 3342 addSystemInclude(DriverArgs, CC1Args, P); 3343 } 3344 3345 if (DriverArgs.hasArg(options::OPT_nostdlibinc)) 3346 return; 3347 3348 // Check for configure-time C include directories. 3349 StringRef CIncludeDirs(C_INCLUDE_DIRS); 3350 if (CIncludeDirs != "") { 3351 SmallVector<StringRef, 5> dirs; 3352 CIncludeDirs.split(dirs, ":"); 3353 for (StringRef dir : dirs) { 3354 StringRef Prefix = 3355 llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : ""; 3356 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir); 3357 } 3358 return; 3359 } 3360 3361 // Lacking those, try to detect the correct set of system includes for the 3362 // target triple. 3363 3364 // Add include directories specific to the selected multilib set and multilib. 3365 if (GCCInstallation.isValid()) { 3366 const auto &Callback = Multilibs.includeDirsCallback(); 3367 if (Callback) { 3368 const auto IncludePaths = Callback(GCCInstallation.getInstallPath(), 3369 GCCInstallation.getTriple().str(), 3370 GCCInstallation.getMultilib()); 3371 for (const auto &Path : IncludePaths) 3372 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, Path); 3373 } 3374 } 3375 3376 // Implement generic Debian multiarch support. 3377 const StringRef X86_64MultiarchIncludeDirs[] = { 3378 "/usr/include/x86_64-linux-gnu", 3379 3380 // FIXME: These are older forms of multiarch. It's not clear that they're 3381 // in use in any released version of Debian, so we should consider 3382 // removing them. 3383 "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64" 3384 }; 3385 const StringRef X86MultiarchIncludeDirs[] = { 3386 "/usr/include/i386-linux-gnu", 3387 3388 // FIXME: These are older forms of multiarch. It's not clear that they're 3389 // in use in any released version of Debian, so we should consider 3390 // removing them. 3391 "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu", 3392 "/usr/include/i486-linux-gnu" 3393 }; 3394 const StringRef AArch64MultiarchIncludeDirs[] = { 3395 "/usr/include/aarch64-linux-gnu" 3396 }; 3397 const StringRef ARMMultiarchIncludeDirs[] = { 3398 "/usr/include/arm-linux-gnueabi" 3399 }; 3400 const StringRef ARMHFMultiarchIncludeDirs[] = { 3401 "/usr/include/arm-linux-gnueabihf" 3402 }; 3403 const StringRef MIPSMultiarchIncludeDirs[] = { 3404 "/usr/include/mips-linux-gnu" 3405 }; 3406 const StringRef MIPSELMultiarchIncludeDirs[] = { 3407 "/usr/include/mipsel-linux-gnu" 3408 }; 3409 const StringRef MIPS64MultiarchIncludeDirs[] = { 3410 "/usr/include/mips64-linux-gnu", 3411 "/usr/include/mips64-linux-gnuabi64" 3412 }; 3413 const StringRef MIPS64ELMultiarchIncludeDirs[] = { 3414 "/usr/include/mips64el-linux-gnu", 3415 "/usr/include/mips64el-linux-gnuabi64" 3416 }; 3417 const StringRef PPCMultiarchIncludeDirs[] = { 3418 "/usr/include/powerpc-linux-gnu" 3419 }; 3420 const StringRef PPC64MultiarchIncludeDirs[] = { 3421 "/usr/include/powerpc64-linux-gnu" 3422 }; 3423 const StringRef PPC64LEMultiarchIncludeDirs[] = { 3424 "/usr/include/powerpc64le-linux-gnu" 3425 }; 3426 ArrayRef<StringRef> MultiarchIncludeDirs; 3427 if (getTriple().getArch() == llvm::Triple::x86_64) { 3428 MultiarchIncludeDirs = X86_64MultiarchIncludeDirs; 3429 } else if (getTriple().getArch() == llvm::Triple::x86) { 3430 MultiarchIncludeDirs = X86MultiarchIncludeDirs; 3431 } else if (getTriple().getArch() == llvm::Triple::aarch64 || 3432 getTriple().getArch() == llvm::Triple::aarch64_be) { 3433 MultiarchIncludeDirs = AArch64MultiarchIncludeDirs; 3434 } else if (getTriple().getArch() == llvm::Triple::arm) { 3435 if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF) 3436 MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs; 3437 else 3438 MultiarchIncludeDirs = ARMMultiarchIncludeDirs; 3439 } else if (getTriple().getArch() == llvm::Triple::mips) { 3440 MultiarchIncludeDirs = MIPSMultiarchIncludeDirs; 3441 } else if (getTriple().getArch() == llvm::Triple::mipsel) { 3442 MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs; 3443 } else if (getTriple().getArch() == llvm::Triple::mips64) { 3444 MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs; 3445 } else if (getTriple().getArch() == llvm::Triple::mips64el) { 3446 MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs; 3447 } else if (getTriple().getArch() == llvm::Triple::ppc) { 3448 MultiarchIncludeDirs = PPCMultiarchIncludeDirs; 3449 } else if (getTriple().getArch() == llvm::Triple::ppc64) { 3450 MultiarchIncludeDirs = PPC64MultiarchIncludeDirs; 3451 } else if (getTriple().getArch() == llvm::Triple::ppc64le) { 3452 MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs; 3453 } 3454 for (StringRef Dir : MultiarchIncludeDirs) { 3455 if (llvm::sys::fs::exists(SysRoot + Dir)) { 3456 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir); 3457 break; 3458 } 3459 } 3460 3461 if (getTriple().getOS() == llvm::Triple::RTEMS) 3462 return; 3463 3464 // Add an include of '/include' directly. This isn't provided by default by 3465 // system GCCs, but is often used with cross-compiling GCCs, and harmless to 3466 // add even when Clang is acting as-if it were a system compiler. 3467 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include"); 3468 3469 addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include"); 3470 } 3471 3472 /// \brief Helper to add the variant paths of a libstdc++ installation. 3473 /*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix, 3474 StringRef GCCTriple, 3475 StringRef GCCMultiarchTriple, 3476 StringRef TargetMultiarchTriple, 3477 Twine IncludeSuffix, 3478 const ArgList &DriverArgs, 3479 ArgStringList &CC1Args) { 3480 if (!llvm::sys::fs::exists(Base + Suffix)) 3481 return false; 3482 3483 addSystemInclude(DriverArgs, CC1Args, Base + Suffix); 3484 3485 // The vanilla GCC layout of libstdc++ headers uses a triple subdirectory. If 3486 // that path exists or we have neither a GCC nor target multiarch triple, use 3487 // this vanilla search path. 3488 if ((GCCMultiarchTriple.empty() && TargetMultiarchTriple.empty()) || 3489 llvm::sys::fs::exists(Base + Suffix + "/" + GCCTriple + IncludeSuffix)) { 3490 addSystemInclude(DriverArgs, CC1Args, 3491 Base + Suffix + "/" + GCCTriple + IncludeSuffix); 3492 } else { 3493 // Otherwise try to use multiarch naming schemes which have normalized the 3494 // triples and put the triple before the suffix. 3495 // 3496 // GCC surprisingly uses *both* the GCC triple with a multilib suffix and 3497 // the target triple, so we support that here. 3498 addSystemInclude(DriverArgs, CC1Args, 3499 Base + "/" + GCCMultiarchTriple + Suffix + IncludeSuffix); 3500 addSystemInclude(DriverArgs, CC1Args, 3501 Base + "/" + TargetMultiarchTriple + Suffix); 3502 } 3503 3504 addSystemInclude(DriverArgs, CC1Args, Base + Suffix + "/backward"); 3505 return true; 3506 } 3507 3508 void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3509 ArgStringList &CC1Args) const { 3510 if (DriverArgs.hasArg(options::OPT_nostdlibinc) || 3511 DriverArgs.hasArg(options::OPT_nostdincxx)) 3512 return; 3513 3514 // Check if libc++ has been enabled and provide its include paths if so. 3515 if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) { 3516 const std::string LibCXXIncludePathCandidates[] = { 3517 // The primary location is within the Clang installation. 3518 // FIXME: We shouldn't hard code 'v1' here to make Clang future proof to 3519 // newer ABI versions. 3520 getDriver().Dir + "/../include/c++/v1", 3521 3522 // We also check the system as for a long time this is the only place Clang looked. 3523 // FIXME: We should really remove this. It doesn't make any sense. 3524 getDriver().SysRoot + "/usr/include/c++/v1" 3525 }; 3526 for (const auto &IncludePath : LibCXXIncludePathCandidates) { 3527 if (!llvm::sys::fs::exists(IncludePath)) 3528 continue; 3529 // Add the first candidate that exists. 3530 addSystemInclude(DriverArgs, CC1Args, IncludePath); 3531 break; 3532 } 3533 return; 3534 } 3535 3536 // We need a detected GCC installation on Linux to provide libstdc++'s 3537 // headers. We handled the libc++ case above. 3538 if (!GCCInstallation.isValid()) 3539 return; 3540 3541 // By default, look for the C++ headers in an include directory adjacent to 3542 // the lib directory of the GCC installation. Note that this is expect to be 3543 // equivalent to '/usr/include/c++/X.Y' in almost all cases. 3544 StringRef LibDir = GCCInstallation.getParentLibPath(); 3545 StringRef InstallDir = GCCInstallation.getInstallPath(); 3546 StringRef TripleStr = GCCInstallation.getTriple().str(); 3547 const Multilib &Multilib = GCCInstallation.getMultilib(); 3548 const std::string GCCMultiarchTriple = 3549 getMultiarchTriple(GCCInstallation.getTriple(), getDriver().SysRoot); 3550 const std::string TargetMultiarchTriple = 3551 getMultiarchTriple(getTriple(), getDriver().SysRoot); 3552 const GCCVersion &Version = GCCInstallation.getVersion(); 3553 3554 // The primary search for libstdc++ supports multiarch variants. 3555 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include", 3556 "/c++/" + Version.Text, TripleStr, GCCMultiarchTriple, 3557 TargetMultiarchTriple, 3558 Multilib.includeSuffix(), DriverArgs, CC1Args)) 3559 return; 3560 3561 // Otherwise, fall back on a bunch of options which don't use multiarch 3562 // layouts for simplicity. 3563 const std::string LibStdCXXIncludePathCandidates[] = { 3564 // Gentoo is weird and places its headers inside the GCC install, so if the 3565 // first attempt to find the headers fails, try these patterns. 3566 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." + 3567 Version.MinorStr, 3568 InstallDir.str() + "/include/g++-v" + Version.MajorStr, 3569 // Android standalone toolchain has C++ headers in yet another place. 3570 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text, 3571 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++, 3572 // without a subdirectory corresponding to the gcc version. 3573 LibDir.str() + "/../include/c++", 3574 }; 3575 3576 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) { 3577 if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr, 3578 /*GCCMultiarchTriple*/ "", 3579 /*TargetMultiarchTriple*/ "", 3580 Multilib.includeSuffix(), DriverArgs, CC1Args)) 3581 break; 3582 } 3583 } 3584 3585 bool Linux::isPIEDefault() const { 3586 return getSanitizerArgs().requiresPIE(); 3587 } 3588 3589 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly. 3590 3591 DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) 3592 : Generic_ELF(D, Triple, Args) { 3593 3594 // Path mangling to find libexec 3595 getProgramPaths().push_back(getDriver().getInstalledDir()); 3596 if (getDriver().getInstalledDir() != getDriver().Dir) 3597 getProgramPaths().push_back(getDriver().Dir); 3598 3599 getFilePaths().push_back(getDriver().Dir + "/../lib"); 3600 getFilePaths().push_back("/usr/lib"); 3601 if (llvm::sys::fs::exists("/usr/lib/gcc47")) 3602 getFilePaths().push_back("/usr/lib/gcc47"); 3603 else 3604 getFilePaths().push_back("/usr/lib/gcc44"); 3605 } 3606 3607 Tool *DragonFly::buildAssembler() const { 3608 return new tools::dragonfly::Assemble(*this); 3609 } 3610 3611 Tool *DragonFly::buildLinker() const { 3612 return new tools::dragonfly::Link(*this); 3613 } 3614 3615 3616 /// XCore tool chain 3617 XCore::XCore(const Driver &D, const llvm::Triple &Triple, 3618 const ArgList &Args) : ToolChain(D, Triple, Args) { 3619 // ProgramPaths are found via 'PATH' environment variable. 3620 } 3621 3622 Tool *XCore::buildAssembler() const { 3623 return new tools::XCore::Assemble(*this); 3624 } 3625 3626 Tool *XCore::buildLinker() const { 3627 return new tools::XCore::Link(*this); 3628 } 3629 3630 bool XCore::isPICDefault() const { 3631 return false; 3632 } 3633 3634 bool XCore::isPIEDefault() const { 3635 return false; 3636 } 3637 3638 bool XCore::isPICDefaultForced() const { 3639 return false; 3640 } 3641 3642 bool XCore::SupportsProfiling() const { 3643 return false; 3644 } 3645 3646 bool XCore::hasBlocksRuntime() const { 3647 return false; 3648 } 3649 3650 void XCore::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 3651 ArgStringList &CC1Args) const { 3652 if (DriverArgs.hasArg(options::OPT_nostdinc) || 3653 DriverArgs.hasArg(options::OPT_nostdlibinc)) 3654 return; 3655 if (const char *cl_include_dir = getenv("XCC_C_INCLUDE_PATH")) { 3656 SmallVector<StringRef, 4> Dirs; 3657 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'}; 3658 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr)); 3659 ArrayRef<StringRef> DirVec(Dirs); 3660 addSystemIncludes(DriverArgs, CC1Args, DirVec); 3661 } 3662 } 3663 3664 void XCore::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, 3665 llvm::opt::ArgStringList &CC1Args) const { 3666 CC1Args.push_back("-nostdsysteminc"); 3667 } 3668 3669 void XCore::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3670 ArgStringList &CC1Args) const { 3671 if (DriverArgs.hasArg(options::OPT_nostdinc) || 3672 DriverArgs.hasArg(options::OPT_nostdlibinc) || 3673 DriverArgs.hasArg(options::OPT_nostdincxx)) 3674 return; 3675 if (const char *cl_include_dir = getenv("XCC_CPLUS_INCLUDE_PATH")) { 3676 SmallVector<StringRef, 4> Dirs; 3677 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator,'\0'}; 3678 StringRef(cl_include_dir).split(Dirs, StringRef(EnvPathSeparatorStr)); 3679 ArrayRef<StringRef> DirVec(Dirs); 3680 addSystemIncludes(DriverArgs, CC1Args, DirVec); 3681 } 3682 } 3683 3684 void XCore::AddCXXStdlibLibArgs(const ArgList &Args, 3685 ArgStringList &CmdArgs) const { 3686 // We don't output any lib args. This is handled by xcc. 3687 } 3688