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 StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS(); 313 llvm::sys::path::append(Path, "lib", OSLibName); 314 return Path.str(); 315 } 316 317 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, 318 bool Shared) const { 319 const llvm::Triple &TT = getTriple(); 320 const char *Env = TT.isAndroid() ? "-android" : ""; 321 bool IsITANMSVCWindows = 322 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); 323 324 StringRef Arch = getArchNameForCompilerRTLib(*this, Args); 325 const char *Prefix = IsITANMSVCWindows ? "" : "lib"; 326 const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so") 327 : (IsITANMSVCWindows ? ".lib" : ".a"); 328 329 SmallString<128> Path(getCompilerRTPath()); 330 llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" + 331 Arch + Env + Suffix); 332 return Path.str(); 333 } 334 335 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, 336 StringRef Component, 337 bool Shared) const { 338 return Args.MakeArgString(getCompilerRT(Args, Component, Shared)); 339 } 340 341 std::string ToolChain::getArchSpecificLibPath() const { 342 SmallString<128> Path(getDriver().ResourceDir); 343 StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS(); 344 llvm::sys::path::append(Path, "lib", OSLibName, 345 llvm::Triple::getArchTypeName(getArch())); 346 return Path.str(); 347 } 348 349 bool ToolChain::needsProfileRT(const ArgList &Args) { 350 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 351 false) || 352 Args.hasArg(options::OPT_fprofile_generate) || 353 Args.hasArg(options::OPT_fprofile_generate_EQ) || 354 Args.hasArg(options::OPT_fprofile_instr_generate) || 355 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || 356 Args.hasArg(options::OPT_fcreate_profile) || 357 Args.hasArg(options::OPT_coverage)) 358 return true; 359 360 return false; 361 } 362 363 Tool *ToolChain::SelectTool(const JobAction &JA) const { 364 if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); 365 Action::ActionClass AC = JA.getKind(); 366 if (AC == Action::AssembleJobClass && useIntegratedAs()) 367 return getClangAs(); 368 return getTool(AC); 369 } 370 371 std::string ToolChain::GetFilePath(const char *Name) const { 372 return D.GetFilePath(Name, *this); 373 } 374 375 std::string ToolChain::GetProgramPath(const char *Name) const { 376 return D.GetProgramPath(Name, *this); 377 } 378 379 std::string ToolChain::GetLinkerPath() const { 380 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); 381 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; 382 383 if (llvm::sys::path::is_absolute(UseLinker)) { 384 // If we're passed what looks like an absolute path, don't attempt to 385 // second-guess that. 386 if (llvm::sys::fs::exists(UseLinker)) 387 return UseLinker; 388 } else if (UseLinker.empty() || UseLinker == "ld") { 389 // If we're passed -fuse-ld= with no argument, or with the argument ld, 390 // then use whatever the default system linker is. 391 return GetProgramPath(getDefaultLinker()); 392 } else { 393 llvm::SmallString<8> LinkerName; 394 if (Triple.isOSDarwin()) 395 LinkerName.append("ld64."); 396 else 397 LinkerName.append("ld."); 398 LinkerName.append(UseLinker); 399 400 std::string LinkerPath(GetProgramPath(LinkerName.c_str())); 401 if (llvm::sys::fs::exists(LinkerPath)) 402 return LinkerPath; 403 } 404 405 if (A) 406 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); 407 408 return GetProgramPath(getDefaultLinker()); 409 } 410 411 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { 412 return types::lookupTypeForExtension(Ext); 413 } 414 415 bool ToolChain::HasNativeLLVMSupport() const { 416 return false; 417 } 418 419 bool ToolChain::isCrossCompiling() const { 420 llvm::Triple HostTriple(LLVM_HOST_TRIPLE); 421 switch (HostTriple.getArch()) { 422 // The A32/T32/T16 instruction sets are not separate architectures in this 423 // context. 424 case llvm::Triple::arm: 425 case llvm::Triple::armeb: 426 case llvm::Triple::thumb: 427 case llvm::Triple::thumbeb: 428 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && 429 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; 430 default: 431 return HostTriple.getArch() != getArch(); 432 } 433 } 434 435 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { 436 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, 437 VersionTuple()); 438 } 439 440 bool ToolChain::isThreadModelSupported(const StringRef Model) const { 441 if (Model == "single") { 442 // FIXME: 'single' is only supported on ARM and WebAssembly so far. 443 return Triple.getArch() == llvm::Triple::arm || 444 Triple.getArch() == llvm::Triple::armeb || 445 Triple.getArch() == llvm::Triple::thumb || 446 Triple.getArch() == llvm::Triple::thumbeb || 447 Triple.getArch() == llvm::Triple::wasm32 || 448 Triple.getArch() == llvm::Triple::wasm64; 449 } else if (Model == "posix") 450 return true; 451 452 return false; 453 } 454 455 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 456 types::ID InputType) const { 457 switch (getTriple().getArch()) { 458 default: 459 return getTripleString(); 460 461 case llvm::Triple::x86_64: { 462 llvm::Triple Triple = getTriple(); 463 if (!Triple.isOSBinFormatMachO()) 464 return getTripleString(); 465 466 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { 467 // x86_64h goes in the triple. Other -march options just use the 468 // vanilla triple we already have. 469 StringRef MArch = A->getValue(); 470 if (MArch == "x86_64h") 471 Triple.setArchName(MArch); 472 } 473 return Triple.getTriple(); 474 } 475 case llvm::Triple::aarch64: { 476 llvm::Triple Triple = getTriple(); 477 if (!Triple.isOSBinFormatMachO()) 478 return getTripleString(); 479 480 // FIXME: older versions of ld64 expect the "arm64" component in the actual 481 // triple string and query it to determine whether an LTO file can be 482 // handled. Remove this when we don't care any more. 483 Triple.setArchName("arm64"); 484 return Triple.getTriple(); 485 } 486 case llvm::Triple::arm: 487 case llvm::Triple::armeb: 488 case llvm::Triple::thumb: 489 case llvm::Triple::thumbeb: { 490 // FIXME: Factor into subclasses. 491 llvm::Triple Triple = getTriple(); 492 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb || 493 getTriple().getArch() == llvm::Triple::thumbeb; 494 495 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 496 // '-mbig-endian'/'-EB'. 497 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 498 options::OPT_mbig_endian)) { 499 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian); 500 } 501 502 // Thumb2 is the default for V7 on Darwin. 503 // 504 // FIXME: Thumb should just be another -target-feaure, not in the triple. 505 StringRef MCPU, MArch; 506 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 507 MCPU = A->getValue(); 508 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) 509 MArch = A->getValue(); 510 std::string CPU = 511 Triple.isOSBinFormatMachO() 512 ? tools::arm::getARMCPUForMArch(MArch, Triple).str() 513 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple); 514 StringRef Suffix = 515 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple); 516 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M; 517 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 && 518 getTriple().isOSBinFormatMachO()); 519 // FIXME: this is invalid for WindowsCE 520 if (getTriple().isOSWindows()) 521 ThumbDefault = true; 522 std::string ArchName; 523 if (IsBigEndian) 524 ArchName = "armeb"; 525 else 526 ArchName = "arm"; 527 528 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for 529 // M-Class CPUs/architecture variants, which is not supported. 530 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb, 531 options::OPT_mno_thumb, ThumbDefault); 532 if (IsMProfile && ARMModeRequested) { 533 if (!MCPU.empty()) 534 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM"; 535 else 536 getDriver().Diag(diag::err_arch_unsupported_isa) 537 << tools::arm::getARMArch(MArch, getTriple()) << "ARM"; 538 } 539 540 // Assembly files should start in ARM mode, unless arch is M-profile. 541 // Windows is always thumb. 542 if ((InputType != types::TY_PP_Asm && Args.hasFlag(options::OPT_mthumb, 543 options::OPT_mno_thumb, ThumbDefault)) || IsMProfile || 544 getTriple().isOSWindows()) { 545 if (IsBigEndian) 546 ArchName = "thumbeb"; 547 else 548 ArchName = "thumb"; 549 } 550 Triple.setArchName(ArchName + Suffix.str()); 551 552 return Triple.getTriple(); 553 } 554 } 555 } 556 557 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 558 types::ID InputType) const { 559 return ComputeLLVMTriple(Args, InputType); 560 } 561 562 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 563 ArgStringList &CC1Args) const { 564 // Each toolchain should provide the appropriate include flags. 565 } 566 567 void ToolChain::addClangTargetOptions( 568 const ArgList &DriverArgs, ArgStringList &CC1Args, 569 Action::OffloadKind DeviceOffloadKind) const {} 570 571 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} 572 573 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, 574 llvm::opt::ArgStringList &CmdArgs) const { 575 if (!needsProfileRT(Args)) return; 576 577 CmdArgs.push_back(getCompilerRTArgString(Args, "profile")); 578 } 579 580 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( 581 const ArgList &Args) const { 582 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); 583 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; 584 585 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! 586 if (LibName == "compiler-rt") 587 return ToolChain::RLT_CompilerRT; 588 else if (LibName == "libgcc") 589 return ToolChain::RLT_Libgcc; 590 else if (LibName == "platform") 591 return GetDefaultRuntimeLibType(); 592 593 if (A) 594 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args); 595 596 return GetDefaultRuntimeLibType(); 597 } 598 599 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ 600 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); 601 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; 602 603 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! 604 if (LibName == "libc++") 605 return ToolChain::CST_Libcxx; 606 else if (LibName == "libstdc++") 607 return ToolChain::CST_Libstdcxx; 608 else if (LibName == "platform") 609 return GetDefaultCXXStdlibType(); 610 611 if (A) 612 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args); 613 614 return GetDefaultCXXStdlibType(); 615 } 616 617 /// \brief Utility function to add a system include directory to CC1 arguments. 618 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, 619 ArgStringList &CC1Args, 620 const Twine &Path) { 621 CC1Args.push_back("-internal-isystem"); 622 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 623 } 624 625 /// \brief Utility function to add a system include directory with extern "C" 626 /// semantics to CC1 arguments. 627 /// 628 /// Note that this should be used rarely, and only for directories that 629 /// historically and for legacy reasons are treated as having implicit extern 630 /// "C" semantics. These semantics are *ignored* by and large today, but its 631 /// important to preserve the preprocessor changes resulting from the 632 /// classification. 633 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, 634 ArgStringList &CC1Args, 635 const Twine &Path) { 636 CC1Args.push_back("-internal-externc-isystem"); 637 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 638 } 639 640 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, 641 ArgStringList &CC1Args, 642 const Twine &Path) { 643 if (llvm::sys::fs::exists(Path)) 644 addExternCSystemInclude(DriverArgs, CC1Args, Path); 645 } 646 647 /// \brief Utility function to add a list of system include directories to CC1. 648 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, 649 ArgStringList &CC1Args, 650 ArrayRef<StringRef> Paths) { 651 for (StringRef Path : Paths) { 652 CC1Args.push_back("-internal-isystem"); 653 CC1Args.push_back(DriverArgs.MakeArgString(Path)); 654 } 655 } 656 657 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 658 ArgStringList &CC1Args) const { 659 // Header search paths should be handled by each of the subclasses. 660 // Historically, they have not been, and instead have been handled inside of 661 // the CC1-layer frontend. As the logic is hoisted out, this generic function 662 // will slowly stop being called. 663 // 664 // While it is being called, replicate a bit of a hack to propagate the 665 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ 666 // header search paths with it. Once all systems are overriding this 667 // function, the CC1 flag and this line can be removed. 668 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); 669 } 670 671 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { 672 return getDriver().CCCIsCXX() && 673 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 674 options::OPT_nostdlibxx); 675 } 676 677 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, 678 ArgStringList &CmdArgs) const { 679 assert(!Args.hasArg(options::OPT_nostdlibxx) && 680 "should not have called this"); 681 CXXStdlibType Type = GetCXXStdlibType(Args); 682 683 switch (Type) { 684 case ToolChain::CST_Libcxx: 685 CmdArgs.push_back("-lc++"); 686 break; 687 688 case ToolChain::CST_Libstdcxx: 689 CmdArgs.push_back("-lstdc++"); 690 break; 691 } 692 } 693 694 void ToolChain::AddFilePathLibArgs(const ArgList &Args, 695 ArgStringList &CmdArgs) const { 696 for (const auto &LibPath : getFilePaths()) 697 if(LibPath.length() > 0) 698 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath)); 699 } 700 701 void ToolChain::AddCCKextLibArgs(const ArgList &Args, 702 ArgStringList &CmdArgs) const { 703 CmdArgs.push_back("-lcc_kext"); 704 } 705 706 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, 707 ArgStringList &CmdArgs) const { 708 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed 709 // (to keep the linker options consistent with gcc and clang itself). 710 if (!isOptimizationLevelFast(Args)) { 711 // Check if -ffast-math or -funsafe-math. 712 Arg *A = 713 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math, 714 options::OPT_funsafe_math_optimizations, 715 options::OPT_fno_unsafe_math_optimizations); 716 717 if (!A || A->getOption().getID() == options::OPT_fno_fast_math || 718 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) 719 return false; 720 } 721 // If crtfastmath.o exists add it to the arguments. 722 std::string Path = GetFilePath("crtfastmath.o"); 723 if (Path == "crtfastmath.o") // Not found. 724 return false; 725 726 CmdArgs.push_back(Args.MakeArgString(Path)); 727 return true; 728 } 729 730 SanitizerMask ToolChain::getSupportedSanitizers() const { 731 // Return sanitizers which don't require runtime support and are not 732 // platform dependent. 733 using namespace SanitizerKind; 734 SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) | 735 CFICastStrict | UnsignedIntegerOverflow | Nullability | 736 LocalBounds; 737 if (getTriple().getArch() == llvm::Triple::x86 || 738 getTriple().getArch() == llvm::Triple::x86_64 || 739 getTriple().getArch() == llvm::Triple::arm || 740 getTriple().getArch() == llvm::Triple::aarch64 || 741 getTriple().getArch() == llvm::Triple::wasm32 || 742 getTriple().getArch() == llvm::Triple::wasm64) 743 Res |= CFIICall; 744 return Res; 745 } 746 747 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 748 ArgStringList &CC1Args) const {} 749 750 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, 751 ArgStringList &CC1Args) const {} 752 753 static VersionTuple separateMSVCFullVersion(unsigned Version) { 754 if (Version < 100) 755 return VersionTuple(Version); 756 757 if (Version < 10000) 758 return VersionTuple(Version / 100, Version % 100); 759 760 unsigned Build = 0, Factor = 1; 761 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) 762 Build = Build + (Version % 10) * Factor; 763 return VersionTuple(Version / 100, Version % 100, Build); 764 } 765 766 VersionTuple 767 ToolChain::computeMSVCVersion(const Driver *D, 768 const llvm::opt::ArgList &Args) const { 769 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); 770 const Arg *MSCompatibilityVersion = 771 Args.getLastArg(options::OPT_fms_compatibility_version); 772 773 if (MSCVersion && MSCompatibilityVersion) { 774 if (D) 775 D->Diag(diag::err_drv_argument_not_allowed_with) 776 << MSCVersion->getAsString(Args) 777 << MSCompatibilityVersion->getAsString(Args); 778 return VersionTuple(); 779 } 780 781 if (MSCompatibilityVersion) { 782 VersionTuple MSVT; 783 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) { 784 if (D) 785 D->Diag(diag::err_drv_invalid_value) 786 << MSCompatibilityVersion->getAsString(Args) 787 << MSCompatibilityVersion->getValue(); 788 } else { 789 return MSVT; 790 } 791 } 792 793 if (MSCVersion) { 794 unsigned Version = 0; 795 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) { 796 if (D) 797 D->Diag(diag::err_drv_invalid_value) 798 << MSCVersion->getAsString(Args) << MSCVersion->getValue(); 799 } else { 800 return separateMSVCFullVersion(Version); 801 } 802 } 803 804 return VersionTuple(); 805 } 806 807 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( 808 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, 809 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { 810 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 811 const OptTable &Opts = getDriver().getOpts(); 812 bool Modified = false; 813 814 // Handle -Xopenmp-target flags 815 for (Arg *A : Args) { 816 // Exclude flags which may only apply to the host toolchain. 817 // Do not exclude flags when the host triple (AuxTriple) 818 // matches the current toolchain triple. If it is not present 819 // at all, target and host share a toolchain. 820 if (A->getOption().matches(options::OPT_m_Group)) { 821 if (SameTripleAsHost) 822 DAL->append(A); 823 else 824 Modified = true; 825 continue; 826 } 827 828 unsigned Index; 829 unsigned Prev; 830 bool XOpenMPTargetNoTriple = 831 A->getOption().matches(options::OPT_Xopenmp_target); 832 833 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { 834 // Passing device args: -Xopenmp-target=<triple> -opt=val. 835 if (A->getValue(0) == getTripleString()) 836 Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); 837 else 838 continue; 839 } else if (XOpenMPTargetNoTriple) { 840 // Passing device args: -Xopenmp-target -opt=val. 841 Index = Args.getBaseArgs().MakeIndex(A->getValue(0)); 842 } else { 843 DAL->append(A); 844 continue; 845 } 846 847 // Parse the argument to -Xopenmp-target. 848 Prev = Index; 849 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); 850 if (!XOpenMPTargetArg || Index > Prev + 1) { 851 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) 852 << A->getAsString(Args); 853 continue; 854 } 855 if (XOpenMPTargetNoTriple && XOpenMPTargetArg && 856 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) { 857 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); 858 continue; 859 } 860 XOpenMPTargetArg->setBaseArg(A); 861 A = XOpenMPTargetArg.release(); 862 AllocatedArgs.push_back(A); 863 DAL->append(A); 864 Modified = true; 865 } 866 867 if (Modified) 868 return DAL; 869 870 delete DAL; 871 return nullptr; 872 } 873