1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===// 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 "clang/Driver/ToolChain.h" 11 #include "ToolChains/CommonArgs.h" 12 #include "ToolChains/Arch/ARM.h" 13 #include "ToolChains/Clang.h" 14 #include "clang/Basic/ObjCRuntime.h" 15 #include "clang/Basic/VirtualFileSystem.h" 16 #include "clang/Config/config.h" 17 #include "clang/Driver/Action.h" 18 #include "clang/Driver/Driver.h" 19 #include "clang/Driver/DriverDiagnostic.h" 20 #include "clang/Driver/Options.h" 21 #include "clang/Driver/SanitizerArgs.h" 22 #include "clang/Driver/XRayArgs.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/Option/Arg.h" 25 #include "llvm/Option/ArgList.h" 26 #include "llvm/Option/Option.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/FileSystem.h" 29 #include "llvm/Support/Path.h" 30 #include "llvm/Support/TargetParser.h" 31 #include "llvm/Support/TargetRegistry.h" 32 33 using namespace clang::driver; 34 using namespace clang::driver::tools; 35 using namespace clang; 36 using namespace llvm; 37 using namespace llvm::opt; 38 39 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) { 40 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext, 41 options::OPT_fno_rtti, options::OPT_frtti); 42 } 43 44 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, 45 const llvm::Triple &Triple, 46 const Arg *CachedRTTIArg) { 47 // Explicit rtti/no-rtti args 48 if (CachedRTTIArg) { 49 if (CachedRTTIArg->getOption().matches(options::OPT_frtti)) 50 return ToolChain::RM_EnabledExplicitly; 51 else 52 return ToolChain::RM_DisabledExplicitly; 53 } 54 55 // -frtti is default, except for the PS4 CPU. 56 if (!Triple.isPS4CPU()) 57 return ToolChain::RM_EnabledImplicitly; 58 59 // On the PS4, turning on c++ exceptions turns on rtti. 60 // We're assuming that, if we see -fexceptions, rtti gets turned on. 61 Arg *Exceptions = Args.getLastArgNoClaim( 62 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions, 63 options::OPT_fexceptions, options::OPT_fno_exceptions); 64 if (Exceptions && 65 (Exceptions->getOption().matches(options::OPT_fexceptions) || 66 Exceptions->getOption().matches(options::OPT_fcxx_exceptions))) 67 return ToolChain::RM_EnabledImplicitly; 68 69 return ToolChain::RM_DisabledImplicitly; 70 } 71 72 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T, 73 const ArgList &Args) 74 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)), 75 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)), 76 EffectiveTriple() { 77 std::string CandidateLibPath = getArchSpecificLibPath(); 78 if (getVFS().exists(CandidateLibPath)) 79 getFilePaths().push_back(CandidateLibPath); 80 } 81 82 ToolChain::~ToolChain() { 83 } 84 85 vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); } 86 87 bool ToolChain::useIntegratedAs() const { 88 return Args.hasFlag(options::OPT_fintegrated_as, 89 options::OPT_fno_integrated_as, 90 IsIntegratedAssemblerDefault()); 91 } 92 93 const SanitizerArgs& ToolChain::getSanitizerArgs() const { 94 if (!SanitizerArguments.get()) 95 SanitizerArguments.reset(new SanitizerArgs(*this, Args)); 96 return *SanitizerArguments.get(); 97 } 98 99 const XRayArgs& ToolChain::getXRayArgs() const { 100 if (!XRayArguments.get()) 101 XRayArguments.reset(new XRayArgs(*this, Args)); 102 return *XRayArguments.get(); 103 } 104 105 namespace { 106 struct DriverSuffix { 107 const char *Suffix; 108 const char *ModeFlag; 109 }; 110 111 const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { 112 // A list of known driver suffixes. Suffixes are compared against the 113 // program name in order. If there is a match, the frontend type is updated as 114 // necessary by applying the ModeFlag. 115 static const DriverSuffix DriverSuffixes[] = { 116 {"clang", nullptr}, 117 {"clang++", "--driver-mode=g++"}, 118 {"clang-c++", "--driver-mode=g++"}, 119 {"clang-cc", nullptr}, 120 {"clang-cpp", "--driver-mode=cpp"}, 121 {"clang-g++", "--driver-mode=g++"}, 122 {"clang-gcc", nullptr}, 123 {"clang-cl", "--driver-mode=cl"}, 124 {"cc", nullptr}, 125 {"cpp", "--driver-mode=cpp"}, 126 {"cl", "--driver-mode=cl"}, 127 {"++", "--driver-mode=g++"}, 128 }; 129 130 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) { 131 StringRef Suffix(DriverSuffixes[i].Suffix); 132 if (ProgName.endswith(Suffix)) { 133 Pos = ProgName.size() - Suffix.size(); 134 return &DriverSuffixes[i]; 135 } 136 } 137 return nullptr; 138 } 139 140 /// Normalize the program name from argv[0] by stripping the file extension if 141 /// present and lower-casing the string on Windows. 142 std::string normalizeProgramName(llvm::StringRef Argv0) { 143 std::string ProgName = llvm::sys::path::stem(Argv0); 144 #ifdef LLVM_ON_WIN32 145 // Transform to lowercase for case insensitive file systems. 146 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower); 147 #endif 148 return ProgName; 149 } 150 151 const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { 152 // Try to infer frontend type and default target from the program name by 153 // comparing it against DriverSuffixes in order. 154 155 // If there is a match, the function tries to identify a target as prefix. 156 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target 157 // prefix "x86_64-linux". If such a target prefix is found, it may be 158 // added via -target as implicit first argument. 159 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); 160 161 if (!DS) { 162 // Try again after stripping any trailing version number: 163 // clang++3.5 -> clang++ 164 ProgName = ProgName.rtrim("0123456789."); 165 DS = FindDriverSuffix(ProgName, Pos); 166 } 167 168 if (!DS) { 169 // Try again after stripping trailing -component. 170 // clang++-tot -> clang++ 171 ProgName = ProgName.slice(0, ProgName.rfind('-')); 172 DS = FindDriverSuffix(ProgName, Pos); 173 } 174 return DS; 175 } 176 } // anonymous namespace 177 178 ParsedClangName 179 ToolChain::getTargetAndModeFromProgramName(StringRef PN) { 180 std::string ProgName = normalizeProgramName(PN); 181 size_t SuffixPos; 182 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos); 183 if (!DS) 184 return ParsedClangName(); 185 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix); 186 187 size_t LastComponent = ProgName.rfind('-', SuffixPos); 188 if (LastComponent == std::string::npos) 189 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag); 190 std::string ModeSuffix = ProgName.substr(LastComponent + 1, 191 SuffixEnd - LastComponent - 1); 192 193 // Infer target from the prefix. 194 StringRef Prefix(ProgName); 195 Prefix = Prefix.slice(0, LastComponent); 196 std::string IgnoredError; 197 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError); 198 return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered}; 199 } 200 201 StringRef ToolChain::getDefaultUniversalArchName() const { 202 // In universal driver terms, the arch name accepted by -arch isn't exactly 203 // the same as the ones that appear in the triple. Roughly speaking, this is 204 // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the 205 // only interesting special case is powerpc. 206 switch (Triple.getArch()) { 207 case llvm::Triple::ppc: 208 return "ppc"; 209 case llvm::Triple::ppc64: 210 return "ppc64"; 211 case llvm::Triple::ppc64le: 212 return "ppc64le"; 213 default: 214 return Triple.getArchName(); 215 } 216 } 217 218 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const { 219 return false; 220 } 221 222 Tool *ToolChain::getClang() const { 223 if (!Clang) 224 Clang.reset(new tools::Clang(*this)); 225 return Clang.get(); 226 } 227 228 Tool *ToolChain::buildAssembler() const { 229 return new tools::ClangAs(*this); 230 } 231 232 Tool *ToolChain::buildLinker() const { 233 llvm_unreachable("Linking is not supported by this toolchain"); 234 } 235 236 Tool *ToolChain::getAssemble() const { 237 if (!Assemble) 238 Assemble.reset(buildAssembler()); 239 return Assemble.get(); 240 } 241 242 Tool *ToolChain::getClangAs() const { 243 if (!Assemble) 244 Assemble.reset(new tools::ClangAs(*this)); 245 return Assemble.get(); 246 } 247 248 Tool *ToolChain::getLink() const { 249 if (!Link) 250 Link.reset(buildLinker()); 251 return Link.get(); 252 } 253 254 Tool *ToolChain::getOffloadBundler() const { 255 if (!OffloadBundler) 256 OffloadBundler.reset(new tools::OffloadBundler(*this)); 257 return OffloadBundler.get(); 258 } 259 260 Tool *ToolChain::getTool(Action::ActionClass AC) const { 261 switch (AC) { 262 case Action::AssembleJobClass: 263 return getAssemble(); 264 265 case Action::LinkJobClass: 266 return getLink(); 267 268 case Action::InputClass: 269 case Action::BindArchClass: 270 case Action::OffloadClass: 271 case Action::LipoJobClass: 272 case Action::DsymutilJobClass: 273 case Action::VerifyDebugInfoJobClass: 274 llvm_unreachable("Invalid tool kind."); 275 276 case Action::CompileJobClass: 277 case Action::PrecompileJobClass: 278 case Action::PreprocessJobClass: 279 case Action::AnalyzeJobClass: 280 case Action::MigrateJobClass: 281 case Action::VerifyPCHJobClass: 282 case Action::BackendJobClass: 283 return getClang(); 284 285 case Action::OffloadBundlingJobClass: 286 case Action::OffloadUnbundlingJobClass: 287 return getOffloadBundler(); 288 } 289 290 llvm_unreachable("Invalid tool kind."); 291 } 292 293 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, 294 const ArgList &Args) { 295 const llvm::Triple &Triple = TC.getTriple(); 296 bool IsWindows = Triple.isOSWindows(); 297 298 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) 299 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) 300 ? "armhf" 301 : "arm"; 302 303 // For historic reasons, Android library is using i686 instead of i386. 304 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) 305 return "i686"; 306 307 return llvm::Triple::getArchTypeName(TC.getArch()); 308 } 309 310 std::string ToolChain::getCompilerRTPath() const { 311 SmallString<128> Path(getDriver().ResourceDir); 312 if (Triple.isOSUnknown()) { 313 llvm::sys::path::append(Path, "lib"); 314 } else { 315 StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS(); 316 llvm::sys::path::append(Path, "lib", OSLibName); 317 } 318 return Path.str(); 319 } 320 321 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, 322 bool Shared) const { 323 const llvm::Triple &TT = getTriple(); 324 const char *Env = TT.isAndroid() ? "-android" : ""; 325 bool IsITANMSVCWindows = 326 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); 327 328 StringRef Arch = getArchNameForCompilerRTLib(*this, Args); 329 const char *Prefix = IsITANMSVCWindows ? "" : "lib"; 330 const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so") 331 : (IsITANMSVCWindows ? ".lib" : ".a"); 332 333 SmallString<128> Path(getCompilerRTPath()); 334 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" + 335 Arch + Env + Suffix); 336 return Path.str(); 337 } 338 339 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, 340 StringRef Component, 341 bool Shared) const { 342 return Args.MakeArgString(getCompilerRT(Args, Component, Shared)); 343 } 344 345 std::string ToolChain::getArchSpecificLibPath() const { 346 SmallString<128> Path(getDriver().ResourceDir); 347 StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS(); 348 llvm::sys::path::append(Path, "lib", OSLibName, 349 llvm::Triple::getArchTypeName(getArch())); 350 return Path.str(); 351 } 352 353 bool ToolChain::needsProfileRT(const ArgList &Args) { 354 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 355 false) || 356 Args.hasArg(options::OPT_fprofile_generate) || 357 Args.hasArg(options::OPT_fprofile_generate_EQ) || 358 Args.hasArg(options::OPT_fprofile_instr_generate) || 359 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || 360 Args.hasArg(options::OPT_fcreate_profile) || 361 Args.hasArg(options::OPT_coverage)) 362 return true; 363 364 return false; 365 } 366 367 Tool *ToolChain::SelectTool(const JobAction &JA) const { 368 if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); 369 Action::ActionClass AC = JA.getKind(); 370 if (AC == Action::AssembleJobClass && useIntegratedAs()) 371 return getClangAs(); 372 return getTool(AC); 373 } 374 375 std::string ToolChain::GetFilePath(const char *Name) const { 376 return D.GetFilePath(Name, *this); 377 } 378 379 std::string ToolChain::GetProgramPath(const char *Name) const { 380 return D.GetProgramPath(Name, *this); 381 } 382 383 std::string ToolChain::GetLinkerPath() const { 384 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); 385 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; 386 387 if (llvm::sys::path::is_absolute(UseLinker)) { 388 // If we're passed what looks like an absolute path, don't attempt to 389 // second-guess that. 390 if (llvm::sys::fs::exists(UseLinker)) 391 return UseLinker; 392 } else if (UseLinker.empty() || UseLinker == "ld") { 393 // If we're passed -fuse-ld= with no argument, or with the argument ld, 394 // then use whatever the default system linker is. 395 return GetProgramPath(getDefaultLinker()); 396 } else { 397 llvm::SmallString<8> LinkerName; 398 if (Triple.isOSDarwin()) 399 LinkerName.append("ld64."); 400 else 401 LinkerName.append("ld."); 402 LinkerName.append(UseLinker); 403 404 std::string LinkerPath(GetProgramPath(LinkerName.c_str())); 405 if (llvm::sys::fs::exists(LinkerPath)) 406 return LinkerPath; 407 } 408 409 if (A) 410 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 411 412 return GetProgramPath(getDefaultLinker()); 413 } 414 415 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { 416 return types::lookupTypeForExtension(Ext); 417 } 418 419 bool ToolChain::HasNativeLLVMSupport() const { 420 return false; 421 } 422 423 bool ToolChain::isCrossCompiling() const { 424 llvm::Triple HostTriple(LLVM_HOST_TRIPLE); 425 switch (HostTriple.getArch()) { 426 // The A32/T32/T16 instruction sets are not separate architectures in this 427 // context. 428 case llvm::Triple::arm: 429 case llvm::Triple::armeb: 430 case llvm::Triple::thumb: 431 case llvm::Triple::thumbeb: 432 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && 433 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; 434 default: 435 return HostTriple.getArch() != getArch(); 436 } 437 } 438 439 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { 440 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, 441 VersionTuple()); 442 } 443 444 bool ToolChain::isThreadModelSupported(const StringRef Model) const { 445 if (Model == "single") { 446 // FIXME: 'single' is only supported on ARM and WebAssembly so far. 447 return Triple.getArch() == llvm::Triple::arm || 448 Triple.getArch() == llvm::Triple::armeb || 449 Triple.getArch() == llvm::Triple::thumb || 450 Triple.getArch() == llvm::Triple::thumbeb || 451 Triple.getArch() == llvm::Triple::wasm32 || 452 Triple.getArch() == llvm::Triple::wasm64; 453 } else if (Model == "posix") 454 return true; 455 456 return false; 457 } 458 459 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 460 types::ID InputType) const { 461 switch (getTriple().getArch()) { 462 default: 463 return getTripleString(); 464 465 case llvm::Triple::x86_64: { 466 llvm::Triple Triple = getTriple(); 467 if (!Triple.isOSBinFormatMachO()) 468 return getTripleString(); 469 470 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { 471 // x86_64h goes in the triple. Other -march options just use the 472 // vanilla triple we already have. 473 StringRef MArch = A->getValue(); 474 if (MArch == "x86_64h") 475 Triple.setArchName(MArch); 476 } 477 return Triple.getTriple(); 478 } 479 case llvm::Triple::aarch64: { 480 llvm::Triple Triple = getTriple(); 481 if (!Triple.isOSBinFormatMachO()) 482 return getTripleString(); 483 484 // FIXME: older versions of ld64 expect the "arm64" component in the actual 485 // triple string and query it to determine whether an LTO file can be 486 // handled. Remove this when we don't care any more. 487 Triple.setArchName("arm64"); 488 return Triple.getTriple(); 489 } 490 case llvm::Triple::arm: 491 case llvm::Triple::armeb: 492 case llvm::Triple::thumb: 493 case llvm::Triple::thumbeb: { 494 // FIXME: Factor into subclasses. 495 llvm::Triple Triple = getTriple(); 496 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb || 497 getTriple().getArch() == llvm::Triple::thumbeb; 498 499 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 500 // '-mbig-endian'/'-EB'. 501 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 502 options::OPT_mbig_endian)) { 503 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian); 504 } 505 506 // Thumb2 is the default for V7 on Darwin. 507 // 508 // FIXME: Thumb should just be another -target-feaure, not in the triple. 509 StringRef MCPU, MArch; 510 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 511 MCPU = A->getValue(); 512 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 513 MArch = A->getValue(); 514 std::string CPU = 515 Triple.isOSBinFormatMachO() 516 ? tools::arm::getARMCPUForMArch(MArch, Triple).str() 517 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple); 518 StringRef Suffix = 519 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple); 520 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M; 521 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && 522 getTriple().isOSBinFormatMachO()); 523 // FIXME: this is invalid for WindowsCE 524 if (getTriple().isOSWindows()) 525 ThumbDefault = true; 526 std::string ArchName; 527 if (IsBigEndian) 528 ArchName = "armeb"; 529 else 530 ArchName = "arm"; 531 532 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for 533 // M-Class CPUs/architecture variants, which is not supported. 534 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb, 535 options::OPT_mno_thumb, ThumbDefault); 536 if (IsMProfile && ARMModeRequested) { 537 if (!MCPU.empty()) 538 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM"; 539 else 540 getDriver().Diag(diag::err_arch_unsupported_isa) 541 << tools::arm::getARMArch(MArch, getTriple()) << "ARM"; 542 } 543 544 // Assembly files should start in ARM mode, unless arch is M-profile. 545 // Windows is always thumb. 546 if ((InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb, 547 options::OPT_mno_thumb, ThumbDefault)) || IsMProfile || 548 getTriple().isOSWindows()) { 549 if (IsBigEndian) 550 ArchName = "thumbeb"; 551 else 552 ArchName = "thumb"; 553 } 554 Triple.setArchName(ArchName + Suffix.str()); 555 556 return Triple.getTriple(); 557 } 558 } 559 } 560 561 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 562 types::ID InputType) const { 563 return ComputeLLVMTriple(Args, InputType); 564 } 565 566 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 567 ArgStringList &CC1Args) const { 568 // Each toolchain should provide the appropriate include flags. 569 } 570 571 void ToolChain::addClangTargetOptions( 572 const ArgList &DriverArgs, ArgStringList &CC1Args, 573 Action::OffloadKind DeviceOffloadKind) const {} 574 575 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} 576 577 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, 578 llvm::opt::ArgStringList &CmdArgs) const { 579 if (!needsProfileRT(Args)) return; 580 581 CmdArgs.push_back(getCompilerRTArgString(Args, "profile")); 582 } 583 584 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( 585 const ArgList &Args) const { 586 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); 587 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; 588 589 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! 590 if (LibName == "compiler-rt") 591 return ToolChain::RLT_CompilerRT; 592 else if (LibName == "libgcc") 593 return ToolChain::RLT_Libgcc; 594 else if (LibName == "platform") 595 return GetDefaultRuntimeLibType(); 596 597 if (A) 598 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args); 599 600 return GetDefaultRuntimeLibType(); 601 } 602 603 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ 604 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 605 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; 606 607 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! 608 if (LibName == "libc++") 609 return ToolChain::CST_Libcxx; 610 else if (LibName == "libstdc++") 611 return ToolChain::CST_Libstdcxx; 612 else if (LibName == "platform") 613 return GetDefaultCXXStdlibType(); 614 615 if (A) 616 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 617 618 return GetDefaultCXXStdlibType(); 619 } 620 621 /// \brief Utility function to add a system include directory to CC1 arguments. 622 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, 623 ArgStringList &CC1Args, 624 const Twine &Path) { 625 CC1Args.push_back("-internal-isystem"); 626 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 627 } 628 629 /// \brief Utility function to add a system include directory with extern "C" 630 /// semantics to CC1 arguments. 631 /// 632 /// Note that this should be used rarely, and only for directories that 633 /// historically and for legacy reasons are treated as having implicit extern 634 /// "C" semantics. These semantics are *ignored* by and large today, but its 635 /// important to preserve the preprocessor changes resulting from the 636 /// classification. 637 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, 638 ArgStringList &CC1Args, 639 const Twine &Path) { 640 CC1Args.push_back("-internal-externc-isystem"); 641 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 642 } 643 644 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, 645 ArgStringList &CC1Args, 646 const Twine &Path) { 647 if (llvm::sys::fs::exists(Path)) 648 addExternCSystemInclude(DriverArgs, CC1Args, Path); 649 } 650 651 /// \brief Utility function to add a list of system include directories to CC1. 652 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, 653 ArgStringList &CC1Args, 654 ArrayRef<StringRef> Paths) { 655 for (StringRef Path : Paths) { 656 CC1Args.push_back("-internal-isystem"); 657 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 658 } 659 } 660 661 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 662 ArgStringList &CC1Args) const { 663 // Header search paths should be handled by each of the subclasses. 664 // Historically, they have not been, and instead have been handled inside of 665 // the CC1-layer frontend. As the logic is hoisted out, this generic function 666 // will slowly stop being called. 667 // 668 // While it is being called, replicate a bit of a hack to propagate the 669 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ 670 // header search paths with it. Once all systems are overriding this 671 // function, the CC1 flag and this line can be removed. 672 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); 673 } 674 675 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { 676 return getDriver().CCCIsCXX() && 677 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 678 options::OPT_nostdlibxx); 679 } 680 681 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 682 ArgStringList &CmdArgs) const { 683 assert(!Args.hasArg(options::OPT_nostdlibxx) && 684 "should not have called this"); 685 CXXStdlibType Type = GetCXXStdlibType(Args); 686 687 switch (Type) { 688 case ToolChain::CST_Libcxx: 689 CmdArgs.push_back("-lc++"); 690 break; 691 692 case ToolChain::CST_Libstdcxx: 693 CmdArgs.push_back("-lstdc++"); 694 break; 695 } 696 } 697 698 void ToolChain::AddFilePathLibArgs(const ArgList &Args, 699 ArgStringList &CmdArgs) const { 700 for (const auto &LibPath : getFilePaths()) 701 if(LibPath.length() > 0) 702 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath)); 703 } 704 705 void ToolChain::AddCCKextLibArgs(const ArgList &Args, 706 ArgStringList &CmdArgs) const { 707 CmdArgs.push_back("-lcc_kext"); 708 } 709 710 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, 711 ArgStringList &CmdArgs) const { 712 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed 713 // (to keep the linker options consistent with gcc and clang itself). 714 if (!isOptimizationLevelFast(Args)) { 715 // Check if -ffast-math or -funsafe-math. 716 Arg *A = 717 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, 718 options::OPT_funsafe_math_optimizations, 719 options::OPT_fno_unsafe_math_optimizations); 720 721 if (!A || A->getOption().getID() == options::OPT_fno_fast_math || 722 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) 723 return false; 724 } 725 // If crtfastmath.o exists add it to the arguments. 726 std::string Path = GetFilePath("crtfastmath.o"); 727 if (Path == "crtfastmath.o") // Not found. 728 return false; 729 730 CmdArgs.push_back(Args.MakeArgString(Path)); 731 return true; 732 } 733 734 SanitizerMask ToolChain::getSupportedSanitizers() const { 735 // Return sanitizers which don't require runtime support and are not 736 // platform dependent. 737 using namespace SanitizerKind; 738 SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) | 739 CFICastStrict | UnsignedIntegerOverflow | Nullability | 740 LocalBounds; 741 if (getTriple().getArch() == llvm::Triple::x86 || 742 getTriple().getArch() == llvm::Triple::x86_64 || 743 getTriple().getArch() == llvm::Triple::arm || 744 getTriple().getArch() == llvm::Triple::aarch64 || 745 getTriple().getArch() == llvm::Triple::wasm32 || 746 getTriple().getArch() == llvm::Triple::wasm64) 747 Res |= CFIICall; 748 return Res; 749 } 750 751 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 752 ArgStringList &CC1Args) const {} 753 754 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, 755 ArgStringList &CC1Args) const {} 756 757 static VersionTuple separateMSVCFullVersion(unsigned Version) { 758 if (Version < 100) 759 return VersionTuple(Version); 760 761 if (Version < 10000) 762 return VersionTuple(Version / 100, Version % 100); 763 764 unsigned Build = 0, Factor = 1; 765 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) 766 Build = Build + (Version % 10) * Factor; 767 return VersionTuple(Version / 100, Version % 100, Build); 768 } 769 770 VersionTuple 771 ToolChain::computeMSVCVersion(const Driver *D, 772 const llvm::opt::ArgList &Args) const { 773 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); 774 const Arg *MSCompatibilityVersion = 775 Args.getLastArg(options::OPT_fms_compatibility_version); 776 777 if (MSCVersion && MSCompatibilityVersion) { 778 if (D) 779 D->Diag(diag::err_drv_argument_not_allowed_with) 780 << MSCVersion->getAsString(Args) 781 << MSCompatibilityVersion->getAsString(Args); 782 return VersionTuple(); 783 } 784 785 if (MSCompatibilityVersion) { 786 VersionTuple MSVT; 787 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) { 788 if (D) 789 D->Diag(diag::err_drv_invalid_value) 790 << MSCompatibilityVersion->getAsString(Args) 791 << MSCompatibilityVersion->getValue(); 792 } else { 793 return MSVT; 794 } 795 } 796 797 if (MSCVersion) { 798 unsigned Version = 0; 799 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) { 800 if (D) 801 D->Diag(diag::err_drv_invalid_value) 802 << MSCVersion->getAsString(Args) << MSCVersion->getValue(); 803 } else { 804 return separateMSVCFullVersion(Version); 805 } 806 } 807 808 return VersionTuple(); 809 } 810 811 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( 812 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, 813 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { 814 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 815 const OptTable &Opts = getDriver().getOpts(); 816 bool Modified = false; 817 818 // Handle -Xopenmp-target flags 819 for (Arg *A : Args) { 820 // Exclude flags which may only apply to the host toolchain. 821 // Do not exclude flags when the host triple (AuxTriple) 822 // matches the current toolchain triple. If it is not present 823 // at all, target and host share a toolchain. 824 if (A->getOption().matches(options::OPT_m_Group)) { 825 if (SameTripleAsHost) 826 DAL->append(A); 827 else 828 Modified = true; 829 continue; 830 } 831 832 unsigned Index; 833 unsigned Prev; 834 bool XOpenMPTargetNoTriple = 835 A->getOption().matches(options::OPT_Xopenmp_target); 836 837 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { 838 // Passing device args: -Xopenmp-target=<triple> -opt=val. 839 if (A->getValue(0) == getTripleString()) 840 Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 841 else 842 continue; 843 } else if (XOpenMPTargetNoTriple) { 844 // Passing device args: -Xopenmp-target -opt=val. 845 Index = Args.getBaseArgs().MakeIndex(A->getValue(0)); 846 } else { 847 DAL->append(A); 848 continue; 849 } 850 851 // Parse the argument to -Xopenmp-target. 852 Prev = Index; 853 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); 854 if (!XOpenMPTargetArg || Index > Prev + 1) { 855 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) 856 << A->getAsString(Args); 857 continue; 858 } 859 if (XOpenMPTargetNoTriple && XOpenMPTargetArg && 860 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) { 861 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); 862 continue; 863 } 864 XOpenMPTargetArg->setBaseArg(A); 865 A = XOpenMPTargetArg.release(); 866 AllocatedArgs.push_back(A); 867 DAL->append(A); 868 Modified = true; 869 } 870 871 if (Modified) 872 return DAL; 873 874 delete DAL; 875 return nullptr; 876 } 877