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