| 1 | //===- ToolChain.cpp - Collections of tools for one platform --------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "clang/Driver/ToolChain.h" |
| 10 | #include "ToolChains/Arch/AArch64.h" |
| 11 | #include "ToolChains/Arch/AMDGPU.h" |
| 12 | #include "ToolChains/Arch/ARM.h" |
| 13 | #include "ToolChains/Arch/RISCV.h" |
| 14 | #include "ToolChains/Clang.h" |
| 15 | #include "ToolChains/Flang.h" |
| 16 | #include "ToolChains/InterfaceStubs.h" |
| 17 | #include "clang/Basic/ObjCRuntime.h" |
| 18 | #include "clang/Basic/Sanitizers.h" |
| 19 | #include "clang/Config/config.h" |
| 20 | #include "clang/Driver/Action.h" |
| 21 | #include "clang/Driver/CommonArgs.h" |
| 22 | #include "clang/Driver/Driver.h" |
| 23 | #include "clang/Driver/InputInfo.h" |
| 24 | #include "clang/Driver/Job.h" |
| 25 | #include "clang/Driver/SanitizerArgs.h" |
| 26 | #include "clang/Driver/XRayArgs.h" |
| 27 | #include "clang/Options/Options.h" |
| 28 | #include "llvm/ADT/SmallString.h" |
| 29 | #include "llvm/ADT/StringExtras.h" |
| 30 | #include "llvm/ADT/StringRef.h" |
| 31 | #include "llvm/ADT/Twine.h" |
| 32 | #include "llvm/Config/llvm-config.h" |
| 33 | #include "llvm/MC/MCTargetOptions.h" |
| 34 | #include "llvm/MC/TargetRegistry.h" |
| 35 | #include "llvm/Option/Arg.h" |
| 36 | #include "llvm/Option/ArgList.h" |
| 37 | #include "llvm/Option/OptTable.h" |
| 38 | #include "llvm/Option/Option.h" |
| 39 | #include "llvm/Support/ErrorHandling.h" |
| 40 | #include "llvm/Support/FileSystem.h" |
| 41 | #include "llvm/Support/FileUtilities.h" |
| 42 | #include "llvm/Support/MemoryBuffer.h" |
| 43 | #include "llvm/Support/Path.h" |
| 44 | #include "llvm/Support/Process.h" |
| 45 | #include "llvm/Support/VersionTuple.h" |
| 46 | #include "llvm/Support/VirtualFileSystem.h" |
| 47 | #include "llvm/TargetParser/AArch64TargetParser.h" |
| 48 | #include "llvm/TargetParser/RISCVISAInfo.h" |
| 49 | #include "llvm/TargetParser/TargetParser.h" |
| 50 | #include "llvm/TargetParser/Triple.h" |
| 51 | #include <cassert> |
| 52 | #include <cstddef> |
| 53 | #include <cstring> |
| 54 | #include <string> |
| 55 | |
| 56 | using namespace clang; |
| 57 | using namespace driver; |
| 58 | using namespace tools; |
| 59 | using namespace llvm; |
| 60 | using namespace llvm::opt; |
| 61 | |
| 62 | static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) { |
| 63 | return Args.getLastArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext, |
| 64 | Ids: options::OPT_fno_rtti, Ids: options::OPT_frtti); |
| 65 | } |
| 66 | |
| 67 | static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, |
| 68 | const llvm::Triple &Triple, |
| 69 | const Arg *CachedRTTIArg) { |
| 70 | // Explicit rtti/no-rtti args |
| 71 | if (CachedRTTIArg) { |
| 72 | if (CachedRTTIArg->getOption().matches(ID: options::OPT_frtti)) |
| 73 | return ToolChain::RM_Enabled; |
| 74 | else |
| 75 | return ToolChain::RM_Disabled; |
| 76 | } |
| 77 | |
| 78 | // -frtti is default, except for the PS4/PS5 and DriverKit. |
| 79 | bool NoRTTI = Triple.isPS() || Triple.isDriverKit(); |
| 80 | return NoRTTI ? ToolChain::RM_Disabled : ToolChain::RM_Enabled; |
| 81 | } |
| 82 | |
| 83 | static ToolChain::ExceptionsMode CalculateExceptionsMode(const ArgList &Args) { |
| 84 | if (Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions, |
| 85 | Default: true)) { |
| 86 | return ToolChain::EM_Enabled; |
| 87 | } |
| 88 | return ToolChain::EM_Disabled; |
| 89 | } |
| 90 | |
| 91 | ToolChain::ToolChain(const Driver &D, const llvm::Triple &T, |
| 92 | const ArgList &Args) |
| 93 | : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)), |
| 94 | CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)), |
| 95 | CachedExceptionsMode(CalculateExceptionsMode(Args)) { |
| 96 | assert(T.str() == T.normalize() && "triple should be normalized" ); |
| 97 | auto addIfExists = [this](path_list &List, const std::string &Path) { |
| 98 | if (getVFS().exists(Path)) |
| 99 | List.push_back(Elt: Path); |
| 100 | }; |
| 101 | |
| 102 | if (std::optional<std::string> Path = getRuntimePath()) |
| 103 | getLibraryPaths().push_back(Elt: *Path); |
| 104 | if (std::optional<std::string> Path = getStdlibPath()) |
| 105 | getFilePaths().push_back(Elt: *Path); |
| 106 | for (const auto &Path : getArchSpecificLibPaths()) |
| 107 | addIfExists(getFilePaths(), Path); |
| 108 | } |
| 109 | |
| 110 | ToolChain::OrderedMultilibs ToolChain::getOrderedMultilibs() const { |
| 111 | if (!SelectedMultilibs.empty()) |
| 112 | return llvm::reverse(C: SelectedMultilibs); |
| 113 | |
| 114 | static const llvm::SmallVector<Multilib> Default = {Multilib()}; |
| 115 | return llvm::reverse(C: Default); |
| 116 | } |
| 117 | |
| 118 | bool ToolChain::loadMultilibsFromYAML(const llvm::opt::ArgList &Args, |
| 119 | const Driver &D, StringRef Fallback) { |
| 120 | std::optional<std::string> MultilibPath = |
| 121 | findMultilibsYAML(Args, D, FallbackDir: Fallback); |
| 122 | if (!MultilibPath) |
| 123 | return false; |
| 124 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB = |
| 125 | D.getVFS().getBufferForFile(Name: *MultilibPath); |
| 126 | if (!MB) |
| 127 | return false; |
| 128 | |
| 129 | Multilib::flags_list Flags = getMultilibFlags(Args); |
| 130 | llvm::ErrorOr<MultilibSet> ErrorOrMultilibSet = |
| 131 | MultilibSet::parseYaml(*MB.get()); |
| 132 | if (ErrorOrMultilibSet.getError()) |
| 133 | return false; |
| 134 | |
| 135 | Multilibs = std::move(ErrorOrMultilibSet.get()); |
| 136 | |
| 137 | SmallVector<StringRef> CustomFlagMacroDefines; |
| 138 | bool Result = |
| 139 | Multilibs.select(D, Flags, SelectedMultilibs, &CustomFlagMacroDefines); |
| 140 | |
| 141 | // Custom flag macro defines are set by processCustomFlags regardless of |
| 142 | // whether variant selection succeeds. |
| 143 | MultilibMacroDefines.clear(); |
| 144 | for (StringRef Define : CustomFlagMacroDefines) |
| 145 | MultilibMacroDefines.push_back(Elt: Define.str()); |
| 146 | |
| 147 | if (!Result) { |
| 148 | D.Diag(DiagID: clang::diag::warn_drv_missing_multilib) << llvm::join(R&: Flags, Separator: " " ); |
| 149 | SmallString<0> Data; |
| 150 | raw_svector_ostream OS(Data); |
| 151 | for (const Multilib &M : Multilibs) |
| 152 | if (!M.isError()) |
| 153 | OS << "\n" << llvm::join(R: M.flags(), Separator: " " ); |
| 154 | D.Diag(DiagID: clang::diag::note_drv_available_multilibs) << OS.str(); |
| 155 | |
| 156 | for (const Multilib &M : SelectedMultilibs) |
| 157 | if (M.isError()) |
| 158 | D.Diag(DiagID: clang::diag::err_drv_multilib_custom_error) |
| 159 | << M.getErrorMessage(); |
| 160 | |
| 161 | SelectedMultilibs.clear(); |
| 162 | return false; |
| 163 | } |
| 164 | |
| 165 | // Prepend variant-specific library paths. The YAML's parent directory is |
| 166 | // the base for file paths; getRuntimePath() is the base for runtime paths. |
| 167 | StringRef YAMLBase = llvm::sys::path::parent_path(path: *MultilibPath); |
| 168 | std::optional<std::string> RuntimeDir = getRuntimePath(); |
| 169 | size_t FileInsertPos = 0; |
| 170 | size_t LibInsertPos = 0; |
| 171 | for (const Multilib &M : getOrderedMultilibs()) { |
| 172 | if (M.isDefault()) |
| 173 | continue; |
| 174 | SmallString<128> FilePath(YAMLBase); |
| 175 | llvm::sys::path::append(path&: FilePath, a: M.gccSuffix()); |
| 176 | getFilePaths().insert(I: getFilePaths().begin() + FileInsertPos, |
| 177 | Elt: std::string(FilePath)); |
| 178 | ++FileInsertPos; |
| 179 | if (RuntimeDir) { |
| 180 | SmallString<128> LibPath(*RuntimeDir); |
| 181 | llvm::sys::path::append(path&: LibPath, a: M.gccSuffix()); |
| 182 | getLibraryPaths().insert(I: getLibraryPaths().begin() + LibInsertPos, |
| 183 | Elt: std::string(LibPath)); |
| 184 | ++LibInsertPos; |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | return true; |
| 189 | } |
| 190 | |
| 191 | std::optional<std::string> |
| 192 | ToolChain::findMultilibsYAML(const llvm::opt::ArgList &Args, const Driver &D, |
| 193 | StringRef FallbackDir) { |
| 194 | if (Arg *A = Args.getLastArg(Ids: options::OPT_multi_lib_config)) { |
| 195 | SmallString<128> MultilibPath(A->getValue()); |
| 196 | if (!D.getVFS().exists(Path: MultilibPath)) { |
| 197 | D.Diag(DiagID: clang::diag::err_drv_no_such_file) << MultilibPath.str(); |
| 198 | return std::nullopt; |
| 199 | } |
| 200 | return std::string(MultilibPath); |
| 201 | } |
| 202 | |
| 203 | SmallString<128> MultilibPath; |
| 204 | if (!FallbackDir.empty()) |
| 205 | MultilibPath = FallbackDir; |
| 206 | else if (std::optional<std::string> StdlibDir = getStdlibPath()) |
| 207 | MultilibPath = *StdlibDir; |
| 208 | else |
| 209 | return std::nullopt; |
| 210 | llvm::sys::path::append(path&: MultilibPath, a: "multilib.yaml" ); |
| 211 | if (!D.getVFS().exists(Path: MultilibPath)) |
| 212 | return std::nullopt; |
| 213 | return std::string(MultilibPath); |
| 214 | } |
| 215 | |
| 216 | void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) { |
| 217 | Triple.setEnvironment(Env); |
| 218 | if (EffectiveTriple != llvm::Triple()) |
| 219 | EffectiveTriple.setEnvironment(Env); |
| 220 | } |
| 221 | |
| 222 | ToolChain::~ToolChain() = default; |
| 223 | |
| 224 | llvm::vfs::FileSystem &ToolChain::getVFS() const { |
| 225 | return getDriver().getVFS(); |
| 226 | } |
| 227 | |
| 228 | bool ToolChain::useIntegratedAs() const { |
| 229 | return Args.hasFlag(Pos: options::OPT_fintegrated_as, |
| 230 | Neg: options::OPT_fno_integrated_as, |
| 231 | Default: IsIntegratedAssemblerDefault()); |
| 232 | } |
| 233 | |
| 234 | bool ToolChain::useIntegratedBackend() const { |
| 235 | assert( |
| 236 | ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) || |
| 237 | (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) && |
| 238 | "(Non-)integrated backend set incorrectly!" ); |
| 239 | |
| 240 | bool IBackend = Args.hasFlag(Pos: options::OPT_fintegrated_objemitter, |
| 241 | Neg: options::OPT_fno_integrated_objemitter, |
| 242 | Default: IsIntegratedBackendDefault()); |
| 243 | |
| 244 | // Diagnose when integrated-objemitter options are not supported by this |
| 245 | // toolchain. |
| 246 | unsigned DiagID; |
| 247 | if ((IBackend && !IsIntegratedBackendSupported()) || |
| 248 | (!IBackend && !IsNonIntegratedBackendSupported())) |
| 249 | DiagID = clang::diag::err_drv_unsupported_opt_for_target; |
| 250 | else |
| 251 | DiagID = clang::diag::warn_drv_unsupported_opt_for_target; |
| 252 | Arg *A = Args.getLastArg(Ids: options::OPT_fno_integrated_objemitter); |
| 253 | if (A && !IsNonIntegratedBackendSupported()) |
| 254 | D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple(); |
| 255 | A = Args.getLastArg(Ids: options::OPT_fintegrated_objemitter); |
| 256 | if (A && !IsIntegratedBackendSupported()) |
| 257 | D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple(); |
| 258 | |
| 259 | return IBackend; |
| 260 | } |
| 261 | |
| 262 | bool ToolChain::useRelaxRelocations() const { |
| 263 | return ENABLE_X86_RELAX_RELOCATIONS; |
| 264 | } |
| 265 | |
| 266 | bool ToolChain::defaultToIEEELongDouble() const { |
| 267 | return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux(); |
| 268 | } |
| 269 | |
| 270 | static void processMultilibCustomFlags(Multilib::flags_list &List, |
| 271 | const llvm::opt::ArgList &Args) { |
| 272 | for (const Arg *MultilibFlagArg : |
| 273 | Args.filtered(Ids: options::OPT_fmultilib_flag)) { |
| 274 | List.push_back(x: MultilibFlagArg->getAsString(Args)); |
| 275 | MultilibFlagArg->claim(); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | static void getAArch64MultilibFlags(const Driver &D, |
| 280 | const llvm::Triple &Triple, |
| 281 | const llvm::opt::ArgList &Args, |
| 282 | Multilib::flags_list &Result) { |
| 283 | std::vector<StringRef> Features; |
| 284 | tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, |
| 285 | /*ForAS=*/false, |
| 286 | /*ForMultilib=*/true); |
| 287 | const auto UnifiedFeatures = tools::unifyTargetFeatures(Features); |
| 288 | llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(), |
| 289 | UnifiedFeatures.end()); |
| 290 | std::vector<std::string> MArch; |
| 291 | for (const auto &Ext : AArch64::Extensions) |
| 292 | if (!Ext.UserVisibleName.empty()) |
| 293 | if (FeatureSet.contains(V: Ext.PosTargetFeature)) |
| 294 | MArch.push_back(x: Ext.UserVisibleName.str()); |
| 295 | for (const auto &Ext : AArch64::Extensions) |
| 296 | if (!Ext.UserVisibleName.empty()) |
| 297 | if (FeatureSet.contains(V: Ext.NegTargetFeature)) |
| 298 | MArch.push_back(x: ("no" + Ext.UserVisibleName).str()); |
| 299 | StringRef ArchName; |
| 300 | for (const auto &ArchInfo : AArch64::ArchInfos) |
| 301 | if (FeatureSet.contains(V: ArchInfo->ArchFeature)) |
| 302 | ArchName = ArchInfo->Name; |
| 303 | if (!ArchName.empty()) { |
| 304 | MArch.insert(position: MArch.begin(), x: ("-march=" + ArchName).str()); |
| 305 | Result.push_back(x: llvm::join(R&: MArch, Separator: "+" )); |
| 306 | } |
| 307 | |
| 308 | const Arg *BranchProtectionArg = |
| 309 | Args.getLastArgNoClaim(Ids: options::OPT_mbranch_protection_EQ); |
| 310 | if (BranchProtectionArg) { |
| 311 | Result.push_back(x: BranchProtectionArg->getAsString(Args)); |
| 312 | } |
| 313 | |
| 314 | if (FeatureSet.contains(V: "+strict-align" )) |
| 315 | Result.push_back(x: "-mno-unaligned-access" ); |
| 316 | else |
| 317 | Result.push_back(x: "-munaligned-access" ); |
| 318 | |
| 319 | if (Arg *Endian = Args.getLastArg(Ids: options::OPT_mbig_endian, |
| 320 | Ids: options::OPT_mlittle_endian)) { |
| 321 | if (Endian->getOption().matches(ID: options::OPT_mbig_endian)) |
| 322 | Result.push_back(x: Endian->getAsString(Args)); |
| 323 | } |
| 324 | |
| 325 | const Arg *ABIArg = Args.getLastArgNoClaim(Ids: options::OPT_mabi_EQ); |
| 326 | if (ABIArg) { |
| 327 | Result.push_back(x: ABIArg->getAsString(Args)); |
| 328 | } |
| 329 | |
| 330 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group); |
| 331 | A && A->getOption().matches(ID: options::OPT_O)) { |
| 332 | switch (A->getValue()[0]) { |
| 333 | case 's': |
| 334 | Result.push_back(x: "-Os" ); |
| 335 | break; |
| 336 | case 'z': |
| 337 | Result.push_back(x: "-Oz" ); |
| 338 | break; |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | static void getARMMultilibFlags(const Driver &D, const llvm::Triple &Triple, |
| 344 | llvm::Reloc::Model RelocationModel, |
| 345 | const llvm::opt::ArgList &Args, |
| 346 | Multilib::flags_list &Result) { |
| 347 | std::vector<StringRef> Features; |
| 348 | llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures( |
| 349 | D, Triple, Args, Features, ForAS: false /*ForAs*/, ForMultilib: true /*ForMultilib*/); |
| 350 | const auto UnifiedFeatures = tools::unifyTargetFeatures(Features); |
| 351 | llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(), |
| 352 | UnifiedFeatures.end()); |
| 353 | std::vector<std::string> MArch; |
| 354 | for (const auto &Ext : ARM::ARCHExtNames) |
| 355 | if (!Ext.Name.empty()) |
| 356 | if (FeatureSet.contains(V: Ext.Feature)) |
| 357 | MArch.push_back(x: Ext.Name.str()); |
| 358 | for (const auto &Ext : ARM::ARCHExtNames) |
| 359 | if (!Ext.Name.empty()) |
| 360 | if (FeatureSet.contains(V: Ext.NegFeature)) |
| 361 | MArch.push_back(x: ("no" + Ext.Name).str()); |
| 362 | MArch.insert(position: MArch.begin(), x: ("-march=" + Triple.getArchName()).str()); |
| 363 | Result.push_back(x: llvm::join(R&: MArch, Separator: "+" )); |
| 364 | |
| 365 | switch (FPUKind) { |
| 366 | #define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION) \ |
| 367 | case llvm::ARM::KIND: \ |
| 368 | Result.push_back("-mfpu=" NAME); \ |
| 369 | break; |
| 370 | #include "llvm/TargetParser/ARMTargetParser.def" |
| 371 | default: |
| 372 | llvm_unreachable("Invalid FPUKind" ); |
| 373 | } |
| 374 | |
| 375 | switch (arm::getARMFloatABI(D, Triple, Args)) { |
| 376 | case arm::FloatABI::Soft: |
| 377 | Result.push_back(x: "-mfloat-abi=soft" ); |
| 378 | break; |
| 379 | case arm::FloatABI::SoftFP: |
| 380 | Result.push_back(x: "-mfloat-abi=softfp" ); |
| 381 | break; |
| 382 | case arm::FloatABI::Hard: |
| 383 | Result.push_back(x: "-mfloat-abi=hard" ); |
| 384 | break; |
| 385 | case arm::FloatABI::Invalid: |
| 386 | llvm_unreachable("Invalid float ABI" ); |
| 387 | } |
| 388 | |
| 389 | if (RelocationModel == llvm::Reloc::ROPI || |
| 390 | RelocationModel == llvm::Reloc::ROPI_RWPI) |
| 391 | Result.push_back(x: "-fropi" ); |
| 392 | else |
| 393 | Result.push_back(x: "-fno-ropi" ); |
| 394 | |
| 395 | if (RelocationModel == llvm::Reloc::RWPI || |
| 396 | RelocationModel == llvm::Reloc::ROPI_RWPI) |
| 397 | Result.push_back(x: "-frwpi" ); |
| 398 | else |
| 399 | Result.push_back(x: "-fno-rwpi" ); |
| 400 | |
| 401 | const Arg *BranchProtectionArg = |
| 402 | Args.getLastArgNoClaim(Ids: options::OPT_mbranch_protection_EQ); |
| 403 | if (BranchProtectionArg) { |
| 404 | Result.push_back(x: BranchProtectionArg->getAsString(Args)); |
| 405 | } |
| 406 | |
| 407 | if (FeatureSet.contains(V: "+strict-align" )) |
| 408 | Result.push_back(x: "-mno-unaligned-access" ); |
| 409 | else |
| 410 | Result.push_back(x: "-munaligned-access" ); |
| 411 | |
| 412 | if (Arg *Endian = Args.getLastArg(Ids: options::OPT_mbig_endian, |
| 413 | Ids: options::OPT_mlittle_endian)) { |
| 414 | if (Endian->getOption().matches(ID: options::OPT_mbig_endian)) |
| 415 | Result.push_back(x: Endian->getAsString(Args)); |
| 416 | } |
| 417 | |
| 418 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group); |
| 419 | A && A->getOption().matches(ID: options::OPT_O)) { |
| 420 | switch (A->getValue()[0]) { |
| 421 | case 's': |
| 422 | Result.push_back(x: "-Os" ); |
| 423 | break; |
| 424 | case 'z': |
| 425 | Result.push_back(x: "-Oz" ); |
| 426 | break; |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple, |
| 432 | const llvm::opt::ArgList &Args, |
| 433 | Multilib::flags_list &Result, |
| 434 | bool hasShadowCallStack) { |
| 435 | std::string Arch = riscv::getRISCVArch(Args, Triple); |
| 436 | // Canonicalize arch for easier matching |
| 437 | auto ISAInfo = llvm::RISCVISAInfo::parseArchString( |
| 438 | Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true); |
| 439 | if (!llvm::errorToBool(Err: ISAInfo.takeError())) |
| 440 | Result.push_back(x: "-march=" + (*ISAInfo)->toString()); |
| 441 | |
| 442 | Result.push_back(x: ("-mabi=" + riscv::getRISCVABI(Args, Triple)).str()); |
| 443 | |
| 444 | if (hasShadowCallStack) |
| 445 | Result.push_back(x: "-fsanitize=shadow-call-stack" ); |
| 446 | else |
| 447 | Result.push_back(x: "-fno-sanitize=shadow-call-stack" ); |
| 448 | |
| 449 | const Arg *CFProtectionArg = |
| 450 | Args.getLastArgNoClaim(Ids: options::OPT_fcf_protection_EQ); |
| 451 | StringRef CFProtectionVal = |
| 452 | CFProtectionArg ? CFProtectionArg->getValue() : "none" ; |
| 453 | Result.push_back(x: ("-fcf-protection=" + CFProtectionVal).str()); |
| 454 | |
| 455 | if (CFProtectionVal == "branch" || CFProtectionVal == "full" ) { |
| 456 | if (const Arg *SchemeArg = |
| 457 | Args.getLastArgNoClaim(Ids: options::OPT_mcf_branch_label_scheme_EQ)) |
| 458 | Result.push_back(x: SchemeArg->getAsString(Args)); |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | Multilib::flags_list |
| 463 | ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const { |
| 464 | using namespace clang::options; |
| 465 | |
| 466 | std::vector<std::string> Result; |
| 467 | const llvm::Triple Triple(ComputeEffectiveClangTriple(Args)); |
| 468 | Result.push_back(x: "--target=" + Triple.str()); |
| 469 | |
| 470 | // A difference of relocation model (absolutely addressed data, PIC, Arm |
| 471 | // ROPI/RWPI) is likely to change whether a particular multilib variant is |
| 472 | // compatible with a given link. Determine the relocation model of the |
| 473 | // current link, so as to add appropriate multilib flags. |
| 474 | llvm::Reloc::Model RelocationModel; |
| 475 | unsigned PICLevel; |
| 476 | bool IsPIE; |
| 477 | { |
| 478 | RegisterEffectiveTriple TripleRAII(*this, Triple); |
| 479 | std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: *this, Args); |
| 480 | } |
| 481 | |
| 482 | switch (Triple.getArch()) { |
| 483 | case llvm::Triple::aarch64: |
| 484 | case llvm::Triple::aarch64_32: |
| 485 | case llvm::Triple::aarch64_be: |
| 486 | getAArch64MultilibFlags(D, Triple, Args, Result); |
| 487 | break; |
| 488 | case llvm::Triple::arm: |
| 489 | case llvm::Triple::armeb: |
| 490 | case llvm::Triple::thumb: |
| 491 | case llvm::Triple::thumbeb: |
| 492 | getARMMultilibFlags(D, Triple, RelocationModel, Args, Result); |
| 493 | break; |
| 494 | case llvm::Triple::riscv32: |
| 495 | case llvm::Triple::riscv64: |
| 496 | case llvm::Triple::riscv32be: |
| 497 | case llvm::Triple::riscv64be: |
| 498 | getRISCVMultilibFlags(D, Triple, Args, Result, |
| 499 | hasShadowCallStack: getSanitizerArgs(JobArgs: Args).hasShadowCallStack()); |
| 500 | break; |
| 501 | default: |
| 502 | break; |
| 503 | } |
| 504 | |
| 505 | processMultilibCustomFlags(List&: Result, Args); |
| 506 | |
| 507 | if (Arg *CStdLibArg = Args.getLastArg(Ids: options::OPT_cstdlib_EQ)) |
| 508 | Result.push_back(x: std::string(CStdLibArg->getOption().getPrefixedName()) + |
| 509 | CStdLibArg->getValue()); |
| 510 | |
| 511 | // Include fno-exceptions and fno-rtti |
| 512 | // to improve multilib selection |
| 513 | if (getRTTIMode() == ToolChain::RTTIMode::RM_Disabled) |
| 514 | Result.push_back(x: "-fno-rtti" ); |
| 515 | else |
| 516 | Result.push_back(x: "-frtti" ); |
| 517 | |
| 518 | if (getExceptionsMode() == ToolChain::ExceptionsMode::EM_Disabled) |
| 519 | Result.push_back(x: "-fno-exceptions" ); |
| 520 | else |
| 521 | Result.push_back(x: "-fexceptions" ); |
| 522 | |
| 523 | if (RelocationModel == llvm::Reloc::PIC_) |
| 524 | Result.push_back(x: IsPIE ? (PICLevel > 1 ? "-fPIE" : "-fpie" ) |
| 525 | : (PICLevel > 1 ? "-fPIC" : "-fpic" )); |
| 526 | else |
| 527 | Result.push_back(x: "-fno-pic" ); |
| 528 | |
| 529 | // Sort and remove duplicates. |
| 530 | std::sort(first: Result.begin(), last: Result.end()); |
| 531 | Result.erase(first: llvm::unique(R&: Result), last: Result.end()); |
| 532 | return Result; |
| 533 | } |
| 534 | |
| 535 | SanitizerArgs |
| 536 | ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA, |
| 537 | Action::OffloadKind DeviceOffloadKind) const { |
| 538 | // When -fno-gpu-sanitize is specified for GPU targets, don't emit |
| 539 | // diagnostics about unsupported sanitizers for specific GPU arches, |
| 540 | // since sanitizers are disabled for the GPU anyway. |
| 541 | bool DiagnoseBoundArchErrors = |
| 542 | BoundArchSanitizerArgsChecked.insert(V: BA.ArchName).second; |
| 543 | if (BA && getTriple().isGPU() && |
| 544 | !JobArgs.hasFlag(Pos: options::OPT_fgpu_sanitize, |
| 545 | Neg: options::OPT_fno_gpu_sanitize, Default: true)) { |
| 546 | DiagnoseBoundArchErrors = false; |
| 547 | } |
| 548 | |
| 549 | SanitizerArgs SanArgs(*this, JobArgs, |
| 550 | /*DiagnoseErrors=*/!SanitizerArgsChecked, |
| 551 | DiagnoseBoundArchErrors, BA, DeviceOffloadKind); |
| 552 | |
| 553 | SanitizerArgsChecked = true; |
| 554 | return SanArgs; |
| 555 | } |
| 556 | |
| 557 | const XRayArgs ToolChain::getXRayArgs(const llvm::opt::ArgList &JobArgs) const { |
| 558 | XRayArgs XRayArguments(*this, JobArgs); |
| 559 | return XRayArguments; |
| 560 | } |
| 561 | |
| 562 | namespace { |
| 563 | |
| 564 | struct DriverSuffix { |
| 565 | const char *Suffix; |
| 566 | const char *ModeFlag; |
| 567 | }; |
| 568 | |
| 569 | } // namespace |
| 570 | |
| 571 | static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { |
| 572 | // A list of known driver suffixes. Suffixes are compared against the |
| 573 | // program name in order. If there is a match, the frontend type is updated as |
| 574 | // necessary by applying the ModeFlag. |
| 575 | static const DriverSuffix DriverSuffixes[] = { |
| 576 | {.Suffix: "clang" , .ModeFlag: nullptr}, |
| 577 | {.Suffix: "clang++" , .ModeFlag: "--driver-mode=g++" }, |
| 578 | {.Suffix: "clang-c++" , .ModeFlag: "--driver-mode=g++" }, |
| 579 | {.Suffix: "clang-cc" , .ModeFlag: nullptr}, |
| 580 | {.Suffix: "clang-cpp" , .ModeFlag: "--driver-mode=cpp" }, |
| 581 | {.Suffix: "clang-g++" , .ModeFlag: "--driver-mode=g++" }, |
| 582 | {.Suffix: "clang-gcc" , .ModeFlag: nullptr}, |
| 583 | {.Suffix: "clang-cl" , .ModeFlag: "--driver-mode=cl" }, |
| 584 | {.Suffix: "cc" , .ModeFlag: nullptr}, |
| 585 | {.Suffix: "cpp" , .ModeFlag: "--driver-mode=cpp" }, |
| 586 | {.Suffix: "cl" , .ModeFlag: "--driver-mode=cl" }, |
| 587 | {.Suffix: "++" , .ModeFlag: "--driver-mode=g++" }, |
| 588 | {.Suffix: "flang" , .ModeFlag: "--driver-mode=flang" }, |
| 589 | // For backwards compatibility, we create a symlink for `flang` called |
| 590 | // `flang-new`. This will be removed in the future. |
| 591 | {.Suffix: "flang-new" , .ModeFlag: "--driver-mode=flang" }, |
| 592 | {.Suffix: "clang-dxc" , .ModeFlag: "--driver-mode=dxc" }, |
| 593 | }; |
| 594 | |
| 595 | for (const auto &DS : DriverSuffixes) { |
| 596 | StringRef Suffix(DS.Suffix); |
| 597 | if (ProgName.ends_with(Suffix)) { |
| 598 | Pos = ProgName.size() - Suffix.size(); |
| 599 | return &DS; |
| 600 | } |
| 601 | } |
| 602 | return nullptr; |
| 603 | } |
| 604 | |
| 605 | /// Normalize the program name from argv[0] by stripping the file extension if |
| 606 | /// present and lower-casing the string on Windows. |
| 607 | static std::string normalizeProgramName(llvm::StringRef Argv0) { |
| 608 | std::string ProgName = std::string(llvm::sys::path::filename(path: Argv0)); |
| 609 | if (is_style_windows(S: llvm::sys::path::Style::native)) { |
| 610 | // Transform to lowercase for case insensitive file systems. |
| 611 | std::transform(first: ProgName.begin(), last: ProgName.end(), result: ProgName.begin(), |
| 612 | unary_op: ::tolower); |
| 613 | } |
| 614 | return ProgName; |
| 615 | } |
| 616 | |
| 617 | static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { |
| 618 | // Try to infer frontend type and default target from the program name by |
| 619 | // comparing it against DriverSuffixes in order. |
| 620 | |
| 621 | // If there is a match, the function tries to identify a target as prefix. |
| 622 | // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target |
| 623 | // prefix "x86_64-linux". If such a target prefix is found, it may be |
| 624 | // added via -target as implicit first argument. |
| 625 | const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); |
| 626 | |
| 627 | if (!DS && ProgName.ends_with(Suffix: ".exe" )) { |
| 628 | // Try again after stripping the executable suffix: |
| 629 | // clang++.exe -> clang++ |
| 630 | ProgName = ProgName.drop_back(N: StringRef(".exe" ).size()); |
| 631 | DS = FindDriverSuffix(ProgName, Pos); |
| 632 | } |
| 633 | |
| 634 | if (!DS) { |
| 635 | // Try again after stripping any trailing version number: |
| 636 | // clang++3.5 -> clang++ |
| 637 | ProgName = ProgName.rtrim(Chars: "0123456789." ); |
| 638 | DS = FindDriverSuffix(ProgName, Pos); |
| 639 | } |
| 640 | |
| 641 | if (!DS) { |
| 642 | // Try again after stripping trailing -component. |
| 643 | // clang++-tot -> clang++ |
| 644 | ProgName = ProgName.slice(Start: 0, End: ProgName.rfind(C: '-')); |
| 645 | DS = FindDriverSuffix(ProgName, Pos); |
| 646 | } |
| 647 | return DS; |
| 648 | } |
| 649 | |
| 650 | ParsedClangName |
| 651 | ToolChain::getTargetAndModeFromProgramName(StringRef PN) { |
| 652 | std::string ProgName = normalizeProgramName(Argv0: PN); |
| 653 | size_t SuffixPos; |
| 654 | const DriverSuffix *DS = parseDriverSuffix(ProgName, Pos&: SuffixPos); |
| 655 | if (!DS) |
| 656 | return {}; |
| 657 | size_t SuffixEnd = SuffixPos + strlen(s: DS->Suffix); |
| 658 | |
| 659 | size_t LastComponent = ProgName.rfind(c: '-', pos: SuffixPos); |
| 660 | if (LastComponent == std::string::npos) |
| 661 | return ParsedClangName(ProgName.substr(pos: 0, n: SuffixEnd), DS->ModeFlag); |
| 662 | std::string ModeSuffix = ProgName.substr(pos: LastComponent + 1, |
| 663 | n: SuffixEnd - LastComponent - 1); |
| 664 | |
| 665 | // Infer target from the prefix. |
| 666 | StringRef Prefix(ProgName); |
| 667 | Prefix = Prefix.slice(Start: 0, End: LastComponent); |
| 668 | std::string IgnoredError; |
| 669 | |
| 670 | llvm::Triple Triple(Prefix); |
| 671 | bool IsRegistered = llvm::TargetRegistry::lookupTarget(TheTriple: Triple, Error&: IgnoredError); |
| 672 | return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag, |
| 673 | IsRegistered}; |
| 674 | } |
| 675 | |
| 676 | StringRef ToolChain::getDefaultUniversalArchName() const { |
| 677 | // In universal driver terms, the arch name accepted by -arch isn't exactly |
| 678 | // the same as the ones that appear in the triple. Roughly speaking, this is |
| 679 | // an inverse of the darwin::getArchTypeForDarwinArchName() function. |
| 680 | switch (Triple.getArch()) { |
| 681 | case llvm::Triple::aarch64: { |
| 682 | if (getTriple().isArm64e()) |
| 683 | return "arm64e" ; |
| 684 | return "arm64" ; |
| 685 | } |
| 686 | case llvm::Triple::aarch64_32: |
| 687 | return "arm64_32" ; |
| 688 | case llvm::Triple::ppc: |
| 689 | return "ppc" ; |
| 690 | case llvm::Triple::ppcle: |
| 691 | return "ppcle" ; |
| 692 | case llvm::Triple::ppc64: |
| 693 | return "ppc64" ; |
| 694 | case llvm::Triple::ppc64le: |
| 695 | return "ppc64le" ; |
| 696 | default: |
| 697 | return Triple.getArchName(); |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | std::string ToolChain::getInputFilename(const InputInfo &Input) const { |
| 702 | return Input.getFilename(); |
| 703 | } |
| 704 | |
| 705 | ToolChain::UnwindTableLevel |
| 706 | ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const { |
| 707 | return UnwindTableLevel::None; |
| 708 | } |
| 709 | |
| 710 | Tool *ToolChain::getClang() const { |
| 711 | if (!Clang) |
| 712 | Clang.reset(p: new tools::Clang(*this, useIntegratedBackend())); |
| 713 | return Clang.get(); |
| 714 | } |
| 715 | |
| 716 | Tool *ToolChain::getFlang() const { |
| 717 | if (!Flang) |
| 718 | Flang.reset(p: new tools::Flang(*this)); |
| 719 | return Flang.get(); |
| 720 | } |
| 721 | |
| 722 | Tool *ToolChain::buildAssembler() const { |
| 723 | return new tools::ClangAs(*this); |
| 724 | } |
| 725 | |
| 726 | Tool *ToolChain::buildLinker() const { |
| 727 | llvm_unreachable("Linking is not supported by this toolchain" ); |
| 728 | } |
| 729 | |
| 730 | Tool *ToolChain::buildStaticLibTool() const { |
| 731 | llvm_unreachable("Creating static lib is not supported by this toolchain" ); |
| 732 | } |
| 733 | |
| 734 | Tool *ToolChain::getAssemble() const { |
| 735 | if (!Assemble) |
| 736 | Assemble.reset(p: buildAssembler()); |
| 737 | return Assemble.get(); |
| 738 | } |
| 739 | |
| 740 | Tool *ToolChain::getClangAs() const { |
| 741 | if (!Assemble) |
| 742 | Assemble.reset(p: new tools::ClangAs(*this)); |
| 743 | return Assemble.get(); |
| 744 | } |
| 745 | |
| 746 | Tool *ToolChain::getLink() const { |
| 747 | if (!Link) |
| 748 | Link.reset(p: buildLinker()); |
| 749 | return Link.get(); |
| 750 | } |
| 751 | |
| 752 | Tool *ToolChain::getStaticLibTool() const { |
| 753 | if (!StaticLibTool) |
| 754 | StaticLibTool.reset(p: buildStaticLibTool()); |
| 755 | return StaticLibTool.get(); |
| 756 | } |
| 757 | |
| 758 | Tool *ToolChain::getIfsMerge() const { |
| 759 | if (!IfsMerge) |
| 760 | IfsMerge.reset(p: new tools::ifstool::Merger(*this)); |
| 761 | return IfsMerge.get(); |
| 762 | } |
| 763 | |
| 764 | Tool *ToolChain::getOffloadBundler() const { |
| 765 | if (!OffloadBundler) |
| 766 | OffloadBundler.reset(p: new tools::OffloadBundler(*this)); |
| 767 | return OffloadBundler.get(); |
| 768 | } |
| 769 | |
| 770 | Tool *ToolChain::getOffloadPackager() const { |
| 771 | if (!OffloadPackager) |
| 772 | OffloadPackager.reset(p: new tools::OffloadPackager(*this)); |
| 773 | return OffloadPackager.get(); |
| 774 | } |
| 775 | |
| 776 | Tool *ToolChain::getLinkerWrapper() const { |
| 777 | if (!LinkerWrapper) |
| 778 | LinkerWrapper.reset(p: new tools::LinkerWrapper(*this, getLink())); |
| 779 | return LinkerWrapper.get(); |
| 780 | } |
| 781 | |
| 782 | Tool *ToolChain::getTool(Action::ActionClass AC) const { |
| 783 | switch (AC) { |
| 784 | case Action::AssembleJobClass: |
| 785 | return getAssemble(); |
| 786 | |
| 787 | case Action::IfsMergeJobClass: |
| 788 | return getIfsMerge(); |
| 789 | |
| 790 | case Action::LinkJobClass: |
| 791 | return getLink(); |
| 792 | |
| 793 | case Action::StaticLibJobClass: |
| 794 | return getStaticLibTool(); |
| 795 | |
| 796 | case Action::InputClass: |
| 797 | case Action::BindArchClass: |
| 798 | case Action::OffloadClass: |
| 799 | case Action::LipoJobClass: |
| 800 | case Action::DsymutilJobClass: |
| 801 | case Action::VerifyDebugInfoJobClass: |
| 802 | case Action::BinaryAnalyzeJobClass: |
| 803 | case Action::BinaryTranslatorJobClass: |
| 804 | case Action::ObjcopyJobClass: |
| 805 | llvm_unreachable("Invalid tool kind." ); |
| 806 | |
| 807 | case Action::CompileJobClass: |
| 808 | case Action::PrecompileJobClass: |
| 809 | case Action::PreprocessJobClass: |
| 810 | case Action::ExtractAPIJobClass: |
| 811 | case Action::AnalyzeJobClass: |
| 812 | case Action::VerifyPCHJobClass: |
| 813 | case Action::BackendJobClass: |
| 814 | return getClang(); |
| 815 | |
| 816 | case Action::OffloadBundlingJobClass: |
| 817 | case Action::OffloadUnbundlingJobClass: |
| 818 | return getOffloadBundler(); |
| 819 | |
| 820 | case Action::OffloadPackagerJobClass: |
| 821 | return getOffloadPackager(); |
| 822 | case Action::LinkerWrapperJobClass: |
| 823 | return getLinkerWrapper(); |
| 824 | } |
| 825 | |
| 826 | llvm_unreachable("Invalid tool kind." ); |
| 827 | } |
| 828 | |
| 829 | static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, |
| 830 | const ArgList &Args) { |
| 831 | const llvm::Triple &Triple = TC.getTriple(); |
| 832 | bool IsWindows = Triple.isOSWindows(); |
| 833 | |
| 834 | if (TC.isBareMetal()) |
| 835 | return Triple.getArchName(); |
| 836 | |
| 837 | if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) |
| 838 | return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) |
| 839 | ? "armhf" |
| 840 | : "arm" ; |
| 841 | |
| 842 | // For historic reasons, Android library is using i686 instead of i386. |
| 843 | if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) |
| 844 | return "i686" ; |
| 845 | |
| 846 | if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32()) |
| 847 | return "x32" ; |
| 848 | |
| 849 | return llvm::Triple::getArchTypeName(Kind: TC.getArch()); |
| 850 | } |
| 851 | |
| 852 | StringRef ToolChain::getOSLibName() const { |
| 853 | if (Triple.isOSDarwin()) |
| 854 | return "darwin" ; |
| 855 | |
| 856 | switch (Triple.getOS()) { |
| 857 | case llvm::Triple::FreeBSD: |
| 858 | return "freebsd" ; |
| 859 | case llvm::Triple::NetBSD: |
| 860 | return "netbsd" ; |
| 861 | case llvm::Triple::OpenBSD: |
| 862 | return "openbsd" ; |
| 863 | case llvm::Triple::Solaris: |
| 864 | return "sunos" ; |
| 865 | case llvm::Triple::AIX: |
| 866 | return "aix" ; |
| 867 | case llvm::Triple::Serenity: |
| 868 | return "serenity" ; |
| 869 | default: |
| 870 | return getOS(); |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | std::string ToolChain::getCompilerRTPath() const { |
| 875 | SmallString<128> Path(getDriver().ResourceDir); |
| 876 | if (isBareMetal()) { |
| 877 | llvm::sys::path::append(path&: Path, a: "lib" , b: getOSLibName()); |
| 878 | if (!SelectedMultilibs.empty()) { |
| 879 | Path += SelectedMultilibs.back().gccSuffix(); |
| 880 | } |
| 881 | } else if (Triple.isOSUnknown()) { |
| 882 | llvm::sys::path::append(path&: Path, a: "lib" ); |
| 883 | } else { |
| 884 | llvm::sys::path::append(path&: Path, a: "lib" , b: getOSLibName()); |
| 885 | } |
| 886 | return std::string(Path); |
| 887 | } |
| 888 | |
| 889 | std::string ToolChain::getCompilerRTBasename(const ArgList &Args, |
| 890 | StringRef Component, |
| 891 | FileType Type) const { |
| 892 | std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type); |
| 893 | return llvm::sys::path::filename(path: CRTAbsolutePath).str(); |
| 894 | } |
| 895 | |
| 896 | std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args, |
| 897 | StringRef Component, |
| 898 | FileType Type, bool AddArch, |
| 899 | bool IsFortran) const { |
| 900 | const llvm::Triple &TT = getTriple(); |
| 901 | bool IsITANMSVCWindows = |
| 902 | TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); |
| 903 | |
| 904 | const char *Prefix = |
| 905 | IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib" ; |
| 906 | const char *Suffix; |
| 907 | switch (Type) { |
| 908 | case ToolChain::FT_Object: |
| 909 | Suffix = IsITANMSVCWindows ? ".obj" : ".o" ; |
| 910 | break; |
| 911 | case ToolChain::FT_Static: |
| 912 | Suffix = IsITANMSVCWindows ? ".lib" : ".a" ; |
| 913 | break; |
| 914 | case ToolChain::FT_Shared: |
| 915 | if (TT.isOSWindows()) |
| 916 | Suffix = TT.isOSCygMing() ? ".dll.a" : ".lib" ; |
| 917 | else if (TT.isOSAIX()) |
| 918 | Suffix = ".a" ; |
| 919 | else |
| 920 | Suffix = ".so" ; |
| 921 | break; |
| 922 | } |
| 923 | |
| 924 | std::string ArchAndEnv; |
| 925 | if (AddArch) { |
| 926 | StringRef Arch = getArchNameForCompilerRTLib(TC: *this, Args); |
| 927 | const char *Env = TT.isAndroid() ? "-android" : "" ; |
| 928 | ArchAndEnv = ("-" + Arch + Env).str(); |
| 929 | } |
| 930 | |
| 931 | std::string LibName = IsFortran ? "flang_rt." : "clang_rt." ; |
| 932 | return (Prefix + Twine(LibName) + Component + ArchAndEnv + Suffix).str(); |
| 933 | } |
| 934 | |
| 935 | std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, |
| 936 | FileType Type, bool IsFortran) const { |
| 937 | // Check for runtime files in the new layout without the architecture first. |
| 938 | std::string CRTBasename = buildCompilerRTBasename( |
| 939 | Args, Component, Type, /*AddArch=*/false, IsFortran); |
| 940 | SmallString<128> Path; |
| 941 | for (const auto &LibPath : getLibraryPaths()) { |
| 942 | SmallString<128> P(LibPath); |
| 943 | llvm::sys::path::append(path&: P, a: CRTBasename); |
| 944 | if (getVFS().exists(Path: P)) |
| 945 | return std::string(P); |
| 946 | if (Path.empty()) |
| 947 | Path = P; |
| 948 | } |
| 949 | |
| 950 | // Check the filename for the old layout if the new one does not exist. |
| 951 | CRTBasename = buildCompilerRTBasename(Args, Component, Type, |
| 952 | /*AddArch=*/!IsFortran, IsFortran); |
| 953 | SmallString<128> OldPath(getCompilerRTPath()); |
| 954 | llvm::sys::path::append(path&: OldPath, a: CRTBasename); |
| 955 | if (Path.empty() || getVFS().exists(Path: OldPath)) |
| 956 | return std::string(OldPath); |
| 957 | |
| 958 | // If none is found, use a file name from the new layout, which may get |
| 959 | // printed in an error message, aiding users in knowing what Clang is |
| 960 | // looking for. |
| 961 | return std::string(Path); |
| 962 | } |
| 963 | |
| 964 | const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, |
| 965 | StringRef Component, |
| 966 | FileType Type, |
| 967 | bool isFortran) const { |
| 968 | return Args.MakeArgString(Str: getCompilerRT(Args, Component, Type, IsFortran: isFortran)); |
| 969 | } |
| 970 | |
| 971 | /// Add Fortran runtime libs |
| 972 | void ToolChain::addFortranRuntimeLibs(const ArgList &Args, |
| 973 | llvm::opt::ArgStringList &CmdArgs) const { |
| 974 | // Link flang_rt.runtime |
| 975 | // These are handled earlier on Windows by telling the frontend driver to |
| 976 | // add the correct libraries to link against as dependents in the object |
| 977 | // file. |
| 978 | if (!getTriple().isKnownWindowsMSVCEnvironment()) { |
| 979 | StringRef F128LibName = getDriver().getFlangF128MathLibrary(); |
| 980 | F128LibName.consume_front_insensitive(Prefix: "lib" ); |
| 981 | if (!F128LibName.empty()) { |
| 982 | bool AsNeeded = !getTriple().isOSAIX(); |
| 983 | CmdArgs.push_back(Elt: "-lflang_rt.quadmath" ); |
| 984 | if (AsNeeded) |
| 985 | addAsNeededOption(TC: *this, Args, CmdArgs, /*as_needed=*/true); |
| 986 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-l" + F128LibName)); |
| 987 | if (AsNeeded) |
| 988 | addAsNeededOption(TC: *this, Args, CmdArgs, /*as_needed=*/false); |
| 989 | } |
| 990 | addFlangRTLibPath(Args, CmdArgs); |
| 991 | |
| 992 | // needs libexecinfo for backtrace functions |
| 993 | if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() || |
| 994 | getTriple().isOSOpenBSD() || getTriple().isOSDragonFly()) |
| 995 | CmdArgs.push_back(Elt: "-lexecinfo" ); |
| 996 | } |
| 997 | |
| 998 | // libomp needs libatomic for atomic operations if using libgcc |
| 999 | if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ, |
| 1000 | Neg: options::OPT_fno_openmp, Default: false)) { |
| 1001 | Driver::OpenMPRuntimeKind OMPRuntime = getDriver().getOpenMPRuntime(Args); |
| 1002 | ToolChain::RuntimeLibType RuntimeLib = GetRuntimeLibType(Args); |
| 1003 | if ((OMPRuntime == Driver::OMPRT_OMP && |
| 1004 | RuntimeLib == ToolChain::RLT_Libgcc) && |
| 1005 | !getTriple().isKnownWindowsMSVCEnvironment()) { |
| 1006 | if (getTriple().isOSAIX()) |
| 1007 | CmdArgs.push_back(Elt: "-lcompiler_rt" ); |
| 1008 | else |
| 1009 | CmdArgs.push_back(Elt: "-latomic" ); |
| 1010 | } |
| 1011 | } |
| 1012 | } |
| 1013 | |
| 1014 | void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args, |
| 1015 | ArgStringList &CmdArgs) const { |
| 1016 | auto AddLibSearchPathIfExists = [&](const Twine &Path) { |
| 1017 | // Linker may emit warnings about non-existing directories |
| 1018 | if (!llvm::sys::fs::is_directory(Path)) |
| 1019 | return; |
| 1020 | |
| 1021 | if (getTriple().isKnownWindowsMSVCEnvironment()) |
| 1022 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-libpath:" + Path)); |
| 1023 | else |
| 1024 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-L" + Path)); |
| 1025 | }; |
| 1026 | |
| 1027 | // Search for flang_rt.* at the same location as clang_rt.* with |
| 1028 | // LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is |
| 1029 | // located at the path returned by getRuntimePath() which is already added to |
| 1030 | // the library search path. This exception is for Apple-Darwin. |
| 1031 | AddLibSearchPathIfExists(getCompilerRTPath()); |
| 1032 | |
| 1033 | // Fall back to the non-resource directory <driver-path>/../lib. We will |
| 1034 | // probably have to refine this in the future. In particular, on some |
| 1035 | // platforms, we may need to use lib64 instead of lib. |
| 1036 | SmallString<256> DefaultLibPath = |
| 1037 | llvm::sys::path::parent_path(path: getDriver().Dir); |
| 1038 | llvm::sys::path::append(path&: DefaultLibPath, a: "lib" ); |
| 1039 | AddLibSearchPathIfExists(DefaultLibPath); |
| 1040 | } |
| 1041 | |
| 1042 | void ToolChain::addFlangRTLibPath(const ArgList &Args, |
| 1043 | llvm::opt::ArgStringList &CmdArgs) const { |
| 1044 | // Link static flang_rt.runtime.a or shared flang_rt.runtime.so. |
| 1045 | // On AIX, default to static flang-rt. |
| 1046 | if (Args.hasFlag(Pos: options::OPT_static_libflangrt, |
| 1047 | Neg: options::OPT_shared_libflangrt, Default: getTriple().isOSAIX())) |
| 1048 | CmdArgs.push_back( |
| 1049 | Elt: getCompilerRTArgString(Args, Component: "runtime" , Type: ToolChain::FT_Static, isFortran: true)); |
| 1050 | else { |
| 1051 | CmdArgs.push_back(Elt: "-lflang_rt.runtime" ); |
| 1052 | addArchSpecificRPath(TC: *this, Args, CmdArgs); |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | // Android target triples contain a target version. If we don't have libraries |
| 1057 | // for the exact target version, we should fall back to the next newest version |
| 1058 | // or a versionless path, if any. |
| 1059 | std::optional<std::string> |
| 1060 | ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const { |
| 1061 | llvm::Triple TripleWithoutLevel(getTriple()); |
| 1062 | TripleWithoutLevel.setEnvironmentName("android" ); // remove any version number |
| 1063 | const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str(); |
| 1064 | unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor(); |
| 1065 | unsigned BestVersion = 0; |
| 1066 | |
| 1067 | SmallString<32> TripleDir; |
| 1068 | bool UsingUnversionedDir = false; |
| 1069 | std::error_code EC; |
| 1070 | for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Dir: BaseDir, EC), LE; |
| 1071 | !EC && LI != LE; LI = LI.increment(EC)) { |
| 1072 | StringRef DirName = llvm::sys::path::filename(path: LI->path()); |
| 1073 | StringRef DirNameSuffix = DirName; |
| 1074 | if (DirNameSuffix.consume_front(Prefix: TripleWithoutLevelStr)) { |
| 1075 | if (DirNameSuffix.empty() && TripleDir.empty()) { |
| 1076 | TripleDir = DirName; |
| 1077 | UsingUnversionedDir = true; |
| 1078 | } else { |
| 1079 | unsigned Version; |
| 1080 | if (!DirNameSuffix.getAsInteger(Radix: 10, Result&: Version) && Version > BestVersion && |
| 1081 | Version < TripleVersion) { |
| 1082 | BestVersion = Version; |
| 1083 | TripleDir = DirName; |
| 1084 | UsingUnversionedDir = false; |
| 1085 | } |
| 1086 | } |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | if (TripleDir.empty()) |
| 1091 | return {}; |
| 1092 | |
| 1093 | SmallString<128> P(BaseDir); |
| 1094 | llvm::sys::path::append(path&: P, a: TripleDir); |
| 1095 | if (UsingUnversionedDir) |
| 1096 | D.Diag(DiagID: diag::warn_android_unversioned_fallback) << P << getTripleString(); |
| 1097 | return std::string(P); |
| 1098 | } |
| 1099 | |
| 1100 | llvm::Triple ToolChain::getTripleWithoutOSVersion() const { |
| 1101 | return (Triple.hasEnvironment() |
| 1102 | ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(), |
| 1103 | llvm::Triple::getOSTypeName(Kind: Triple.getOS()), |
| 1104 | llvm::Triple::getEnvironmentTypeName( |
| 1105 | Kind: Triple.getEnvironment())) |
| 1106 | : llvm::Triple(Triple.getArchName(), Triple.getVendorName(), |
| 1107 | llvm::Triple::getOSTypeName(Kind: Triple.getOS()))); |
| 1108 | } |
| 1109 | |
| 1110 | std::optional<std::string> |
| 1111 | ToolChain::getTargetSubDirPath(StringRef BaseDir) const { |
| 1112 | auto getPathForTriple = |
| 1113 | [&](const llvm::Triple &Triple) -> std::optional<std::string> { |
| 1114 | SmallString<128> P(BaseDir); |
| 1115 | llvm::sys::path::append(path&: P, a: Triple.str()); |
| 1116 | if (getVFS().exists(Path: P)) |
| 1117 | return std::string(P); |
| 1118 | return {}; |
| 1119 | }; |
| 1120 | |
| 1121 | const llvm::Triple &T = getTriple(); |
| 1122 | if (auto Path = getPathForTriple(T)) |
| 1123 | return *Path; |
| 1124 | |
| 1125 | if (T.isOSAIX()) { |
| 1126 | llvm::Triple AIXTriple; |
| 1127 | if (T.getEnvironment() == Triple::UnknownEnvironment) { |
| 1128 | // Strip unknown environment and the OS version from the triple. |
| 1129 | AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(), |
| 1130 | llvm::Triple::getOSTypeName(Kind: T.getOS())); |
| 1131 | } else { |
| 1132 | // Strip the OS version from the triple. |
| 1133 | AIXTriple = getTripleWithoutOSVersion(); |
| 1134 | } |
| 1135 | if (auto Path = getPathForTriple(AIXTriple)) |
| 1136 | return *Path; |
| 1137 | } |
| 1138 | |
| 1139 | if (T.isOSzOS() && |
| 1140 | (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) { |
| 1141 | // Build the triple without version information |
| 1142 | const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion(); |
| 1143 | if (auto Path = getPathForTriple(TripleWithoutVersion)) |
| 1144 | return *Path; |
| 1145 | } |
| 1146 | |
| 1147 | // When building with per target runtime directories, various ways of naming |
| 1148 | // the Arm architecture may have been normalised to simply "arm". |
| 1149 | // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm". |
| 1150 | // Since an armv8l system can use libraries built for earlier architecture |
| 1151 | // versions assuming endian and float ABI match. |
| 1152 | // |
| 1153 | // Original triple: armv8l-unknown-linux-gnueabihf |
| 1154 | // Runtime triple: arm-unknown-linux-gnueabihf |
| 1155 | // |
| 1156 | // We do not do this for armeb (big endian) because doing so could make us |
| 1157 | // select little endian libraries. In addition, all known armeb triples only |
| 1158 | // use the "armeb" architecture name. |
| 1159 | // |
| 1160 | // M profile Arm is bare metal and we know they will not be using the per |
| 1161 | // target runtime directory layout. |
| 1162 | if (T.getArch() == Triple::arm && !T.isArmMClass()) { |
| 1163 | llvm::Triple ArmTriple = T; |
| 1164 | ArmTriple.setArch(Kind: Triple::arm); |
| 1165 | if (auto Path = getPathForTriple(ArmTriple)) |
| 1166 | return *Path; |
| 1167 | } |
| 1168 | |
| 1169 | if (T.isAndroid()) |
| 1170 | return getFallbackAndroidTargetPath(BaseDir); |
| 1171 | |
| 1172 | return {}; |
| 1173 | } |
| 1174 | |
| 1175 | std::optional<std::string> ToolChain::getDefaultIntrinsicModuleDir() const { |
| 1176 | SmallString<128> P(D.ResourceDir); |
| 1177 | llvm::sys::path::append(path&: P, a: "finclude" , b: "flang" ); |
| 1178 | return getTargetSubDirPath(BaseDir: P); |
| 1179 | } |
| 1180 | |
| 1181 | std::optional<std::string> ToolChain::getRuntimePath() const { |
| 1182 | SmallString<128> P(D.ResourceDir); |
| 1183 | llvm::sys::path::append(path&: P, a: "lib" ); |
| 1184 | if (auto Ret = getTargetSubDirPath(BaseDir: P)) |
| 1185 | return Ret; |
| 1186 | // Darwin does not use per-target runtime directory. |
| 1187 | if (Triple.isOSDarwin()) |
| 1188 | return {}; |
| 1189 | |
| 1190 | llvm::sys::path::append(path&: P, a: Triple.str()); |
| 1191 | return std::string(P); |
| 1192 | } |
| 1193 | |
| 1194 | std::optional<std::string> ToolChain::getStdlibPath() const { |
| 1195 | SmallString<128> P(D.Dir); |
| 1196 | llvm::sys::path::append(path&: P, a: ".." , b: "lib" ); |
| 1197 | return getTargetSubDirPath(BaseDir: P); |
| 1198 | } |
| 1199 | |
| 1200 | std::optional<std::string> ToolChain::getStdlibIncludePath() const { |
| 1201 | SmallString<128> P(D.Dir); |
| 1202 | llvm::sys::path::append(path&: P, a: ".." , b: "include" ); |
| 1203 | return getTargetSubDirPath(BaseDir: P); |
| 1204 | } |
| 1205 | |
| 1206 | ToolChain::path_list ToolChain::getArchSpecificLibPaths() const { |
| 1207 | path_list Paths; |
| 1208 | |
| 1209 | auto AddPath = [&](const ArrayRef<StringRef> &SS) { |
| 1210 | SmallString<128> Path(getDriver().ResourceDir); |
| 1211 | llvm::sys::path::append(path&: Path, a: "lib" ); |
| 1212 | for (auto &S : SS) |
| 1213 | llvm::sys::path::append(path&: Path, a: S); |
| 1214 | Paths.push_back(Elt: std::string(Path)); |
| 1215 | }; |
| 1216 | |
| 1217 | AddPath({getTriple().str()}); |
| 1218 | AddPath({getOSLibName(), llvm::Triple::getArchTypeName(Kind: getArch())}); |
| 1219 | return Paths; |
| 1220 | } |
| 1221 | |
| 1222 | bool ToolChain::needsProfileRT(const ArgList &Args) { |
| 1223 | if (Args.hasArg(Ids: options::OPT_noprofilelib)) |
| 1224 | return false; |
| 1225 | |
| 1226 | return Args.hasArg(Ids: options::OPT_fprofile_generate) || |
| 1227 | Args.hasArg(Ids: options::OPT_fprofile_generate_EQ) || |
| 1228 | Args.hasArg(Ids: options::OPT_fcs_profile_generate) || |
| 1229 | Args.hasArg(Ids: options::OPT_fcs_profile_generate_EQ) || |
| 1230 | Args.hasArg(Ids: options::OPT_fprofile_instr_generate) || |
| 1231 | Args.hasArg(Ids: options::OPT_fprofile_instr_generate_EQ) || |
| 1232 | Args.hasArg(Ids: options::OPT_fcreate_profile) || |
| 1233 | Args.hasArg(Ids: options::OPT_fprofile_generate_cold_function_coverage) || |
| 1234 | Args.hasArg(Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ); |
| 1235 | } |
| 1236 | |
| 1237 | bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) { |
| 1238 | return Args.hasArg(Ids: options::OPT_coverage) || |
| 1239 | Args.hasFlag(Pos: options::OPT_fprofile_arcs, Neg: options::OPT_fno_profile_arcs, |
| 1240 | Default: false); |
| 1241 | } |
| 1242 | |
| 1243 | Tool *ToolChain::SelectTool(const JobAction &JA) const { |
| 1244 | if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang(); |
| 1245 | if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); |
| 1246 | Action::ActionClass AC = JA.getKind(); |
| 1247 | if (AC == Action::AssembleJobClass && useIntegratedAs() && |
| 1248 | !getTriple().isOSAIX()) |
| 1249 | return getClangAs(); |
| 1250 | return getTool(AC); |
| 1251 | } |
| 1252 | |
| 1253 | std::string ToolChain::GetFilePath(const char *Name) const { |
| 1254 | return D.GetFilePath(Name, TC: *this); |
| 1255 | } |
| 1256 | |
| 1257 | std::string ToolChain::GetProgramPath(const char *Name) const { |
| 1258 | return D.GetProgramPath(Name, TC: *this); |
| 1259 | } |
| 1260 | |
| 1261 | std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const { |
| 1262 | if (LinkerIsLLD) |
| 1263 | *LinkerIsLLD = false; |
| 1264 | |
| 1265 | // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is |
| 1266 | // considered as the linker flavor, e.g. "bfd", "gold", or "lld". |
| 1267 | const Arg* A = Args.getLastArg(Ids: options::OPT_fuse_ld_EQ); |
| 1268 | StringRef UseLinker = A ? A->getValue() : getDriver().getPreferredLinker(); |
| 1269 | |
| 1270 | // --ld-path= takes precedence over -fuse-ld= and specifies the executable |
| 1271 | // name. -B, COMPILER_PATH and PATH and consulted if the value does not |
| 1272 | // contain a path component separator. |
| 1273 | // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary |
| 1274 | // that --ld-path= points to is lld. |
| 1275 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_ld_path_EQ)) { |
| 1276 | std::string Path(A->getValue()); |
| 1277 | if (!Path.empty()) { |
| 1278 | if (llvm::sys::path::parent_path(path: Path).empty()) |
| 1279 | Path = GetProgramPath(Name: A->getValue()); |
| 1280 | if (llvm::sys::fs::can_execute(Path)) { |
| 1281 | if (LinkerIsLLD) |
| 1282 | *LinkerIsLLD = UseLinker == "lld" ; |
| 1283 | return std::string(Path); |
| 1284 | } |
| 1285 | } |
| 1286 | getDriver().Diag(DiagID: diag::err_drv_invalid_linker_name) << A->getAsString(Args); |
| 1287 | return GetProgramPath(Name: getDefaultLinker()); |
| 1288 | } |
| 1289 | // If we're passed -fuse-ld= with no argument, or with the argument ld, |
| 1290 | // then use whatever the default system linker is. |
| 1291 | if (UseLinker.empty() || UseLinker == "ld" ) { |
| 1292 | const char *DefaultLinker = getDefaultLinker(); |
| 1293 | if (llvm::sys::path::is_absolute(path: DefaultLinker)) |
| 1294 | return std::string(DefaultLinker); |
| 1295 | else |
| 1296 | return GetProgramPath(Name: DefaultLinker); |
| 1297 | } |
| 1298 | |
| 1299 | // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking |
| 1300 | // for the linker flavor is brittle. In addition, prepending "ld." or "ld64." |
| 1301 | // to a relative path is surprising. This is more complex due to priorities |
| 1302 | // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead. |
| 1303 | if (UseLinker.contains(C: '/')) |
| 1304 | getDriver().Diag(DiagID: diag::warn_drv_fuse_ld_path); |
| 1305 | |
| 1306 | if (llvm::sys::path::is_absolute(path: UseLinker)) { |
| 1307 | // If we're passed what looks like an absolute path, don't attempt to |
| 1308 | // second-guess that. |
| 1309 | if (llvm::sys::fs::can_execute(Path: UseLinker)) |
| 1310 | return std::string(UseLinker); |
| 1311 | } else { |
| 1312 | llvm::SmallString<8> LinkerName; |
| 1313 | if (Triple.isOSDarwin()) |
| 1314 | LinkerName.append(RHS: "ld64." ); |
| 1315 | else |
| 1316 | LinkerName.append(RHS: "ld." ); |
| 1317 | LinkerName.append(RHS: UseLinker); |
| 1318 | |
| 1319 | std::string LinkerPath(GetProgramPath(Name: LinkerName.c_str())); |
| 1320 | if (llvm::sys::fs::can_execute(Path: LinkerPath)) { |
| 1321 | if (LinkerIsLLD) |
| 1322 | *LinkerIsLLD = UseLinker == "lld" ; |
| 1323 | return LinkerPath; |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | if (A) |
| 1328 | getDriver().Diag(DiagID: diag::err_drv_invalid_linker_name) << A->getAsString(Args); |
| 1329 | |
| 1330 | return GetProgramPath(Name: getDefaultLinker()); |
| 1331 | } |
| 1332 | |
| 1333 | std::string ToolChain::GetStaticLibToolPath() const { |
| 1334 | // TODO: Add support for static lib archiving on Windows |
| 1335 | if (Triple.isOSDarwin()) |
| 1336 | return GetProgramPath(Name: "libtool" ); |
| 1337 | return GetProgramPath(Name: "llvm-ar" ); |
| 1338 | } |
| 1339 | |
| 1340 | types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { |
| 1341 | types::ID id = types::lookupTypeForExtension(Ext); |
| 1342 | |
| 1343 | // Flang always runs the preprocessor and has no notion of "preprocessed |
| 1344 | // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating |
| 1345 | // them differently. |
| 1346 | if (D.IsFlangMode() && id == types::TY_PP_Fortran) |
| 1347 | id = types::TY_Fortran; |
| 1348 | |
| 1349 | return id; |
| 1350 | } |
| 1351 | |
| 1352 | bool ToolChain::HasNativeLLVMSupport() const { |
| 1353 | return false; |
| 1354 | } |
| 1355 | |
| 1356 | LTOKind ToolChain::getDefaultLTOMode() const { return LTOK_None; } |
| 1357 | |
| 1358 | bool ToolChain::isUsingLTO(const llvm::opt::ArgList &Args, |
| 1359 | Action::OffloadKind Kind) const { |
| 1360 | return getLTOMode(Args, Kind) != LTOK_None; |
| 1361 | } |
| 1362 | |
| 1363 | static LTOKind parseLTOMode(const llvm::opt::ArgList &Args, |
| 1364 | llvm::opt::OptSpecifier OptEq, |
| 1365 | llvm::opt::OptSpecifier OptNeg) { |
| 1366 | if (!Args.hasFlag(Pos: OptEq, Neg: OptNeg, Default: false)) |
| 1367 | return LTOK_None; |
| 1368 | |
| 1369 | const Arg *A = Args.getLastArg(Ids: OptEq); |
| 1370 | StringRef LTOName = A->getValue(); |
| 1371 | |
| 1372 | return llvm::StringSwitch<LTOKind>(LTOName) |
| 1373 | .Case(S: "full" , Value: LTOK_Full) |
| 1374 | .Case(S: "thin" , Value: LTOK_Thin) |
| 1375 | .Case(S: "none" , Value: LTOK_None) |
| 1376 | .Default(Value: LTOK_Unknown); |
| 1377 | } |
| 1378 | |
| 1379 | LTOKind ToolChain::getLTOMode(const llvm::opt::ArgList &Args, |
| 1380 | Action::OffloadKind Kind) const { |
| 1381 | bool IsOffload = Kind != Action::OFK_None; |
| 1382 | auto OptEq = IsOffload ? options::OPT_foffload_lto_EQ : options::OPT_flto_EQ; |
| 1383 | auto OptNeg = IsOffload ? options::OPT_fno_offload_lto : options::OPT_fno_lto; |
| 1384 | |
| 1385 | // -fopenmp-target-jit implies -foffload-lto=full for device compilations, |
| 1386 | // overriding any explicit -fno-offload-lto. |
| 1387 | if (IsOffload && Args.hasFlag(Pos: options::OPT_fopenmp_target_jit, |
| 1388 | Neg: options::OPT_fno_openmp_target_jit, Default: false)) { |
| 1389 | if (Arg *A = Args.getLastArg(Ids: OptEq, Ids: OptNeg)) |
| 1390 | if (parseLTOMode(Args, OptEq, OptNeg) != LTOK_Full) |
| 1391 | getDriver().Diag(DiagID: diag::err_drv_incompatible_options) |
| 1392 | << A->getSpelling() << "-fopenmp-target-jit" ; |
| 1393 | return LTOK_Full; |
| 1394 | } |
| 1395 | |
| 1396 | if (!Args.hasArg(Ids: OptEq, Ids: OptNeg)) |
| 1397 | return getDefaultLTOMode(); |
| 1398 | |
| 1399 | LTOKind Mode = parseLTOMode(Args, OptEq, OptNeg); |
| 1400 | |
| 1401 | if (Mode == LTOK_Unknown) { |
| 1402 | const Arg *A = Args.getLastArg(Ids: OptEq); |
| 1403 | getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 1404 | << A->getSpelling() << A->getValue(); |
| 1405 | return LTOK_None; |
| 1406 | } |
| 1407 | return Mode; |
| 1408 | } |
| 1409 | |
| 1410 | bool ToolChain::isCrossCompiling() const { |
| 1411 | llvm::Triple HostTriple(LLVM_HOST_TRIPLE); |
| 1412 | switch (HostTriple.getArch()) { |
| 1413 | // The A32/T32/T16 instruction sets are not separate architectures in this |
| 1414 | // context. |
| 1415 | case llvm::Triple::arm: |
| 1416 | case llvm::Triple::armeb: |
| 1417 | case llvm::Triple::thumb: |
| 1418 | case llvm::Triple::thumbeb: |
| 1419 | return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && |
| 1420 | getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; |
| 1421 | default: |
| 1422 | return HostTriple.getArch() != getArch(); |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { |
| 1427 | return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, |
| 1428 | VersionTuple()); |
| 1429 | } |
| 1430 | |
| 1431 | llvm::ExceptionHandling |
| 1432 | ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const { |
| 1433 | return llvm::ExceptionHandling::None; |
| 1434 | } |
| 1435 | |
| 1436 | bool ToolChain::isThreadModelSupported(const StringRef Model) const { |
| 1437 | if (Model == "single" ) { |
| 1438 | // FIXME: 'single' is only supported on ARM and WebAssembly so far. |
| 1439 | return Triple.getArch() == llvm::Triple::arm || |
| 1440 | Triple.getArch() == llvm::Triple::armeb || |
| 1441 | Triple.getArch() == llvm::Triple::thumb || |
| 1442 | Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm(); |
| 1443 | } else if (Model == "posix" ) |
| 1444 | return true; |
| 1445 | |
| 1446 | return false; |
| 1447 | } |
| 1448 | |
| 1449 | std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, BoundArch BA, |
| 1450 | types::ID InputType) const { |
| 1451 | switch (getTriple().getArch()) { |
| 1452 | default: |
| 1453 | return getTripleString().str(); |
| 1454 | |
| 1455 | case llvm::Triple::x86_64: { |
| 1456 | llvm::Triple Triple = getTriple(); |
| 1457 | if (!Triple.isOSBinFormatMachO()) |
| 1458 | return getTripleString().str(); |
| 1459 | |
| 1460 | if (Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ)) { |
| 1461 | // x86_64h goes in the triple. Other -march options just use the |
| 1462 | // vanilla triple we already have. |
| 1463 | StringRef MArch = A->getValue(); |
| 1464 | if (MArch == "x86_64h" ) |
| 1465 | Triple.setArchName(MArch); |
| 1466 | } |
| 1467 | return Triple.getTriple(); |
| 1468 | } |
| 1469 | case llvm::Triple::aarch64: { |
| 1470 | llvm::Triple Triple = getTriple(); |
| 1471 | if (!Triple.isOSBinFormatMachO()) |
| 1472 | return Triple.getTriple(); |
| 1473 | |
| 1474 | if (Triple.isArm64e()) |
| 1475 | return Triple.getTriple(); |
| 1476 | |
| 1477 | // FIXME: older versions of ld64 expect the "arm64" component in the actual |
| 1478 | // triple string and query it to determine whether an LTO file can be |
| 1479 | // handled. Remove this when we don't care any more. |
| 1480 | Triple.setArchName("arm64" ); |
| 1481 | return Triple.getTriple(); |
| 1482 | } |
| 1483 | case llvm::Triple::aarch64_32: |
| 1484 | return getTripleString().str(); |
| 1485 | case llvm::Triple::amdgcn: { |
| 1486 | llvm::Triple Triple = getTriple(); |
| 1487 | tools::AMDGPU::setArchNameInTriple(D: getDriver(), Args, InputType, Triple); |
| 1488 | return Triple.getTriple(); |
| 1489 | } |
| 1490 | case llvm::Triple::arm: |
| 1491 | case llvm::Triple::armeb: |
| 1492 | case llvm::Triple::thumb: |
| 1493 | case llvm::Triple::thumbeb: { |
| 1494 | llvm::Triple Triple = getTriple(); |
| 1495 | tools::arm::setArchNameInTriple(D: getDriver(), Args, InputType, Triple); |
| 1496 | tools::arm::setFloatABIInTriple(D: getDriver(), Args, triple&: Triple); |
| 1497 | return Triple.getTriple(); |
| 1498 | } |
| 1499 | } |
| 1500 | } |
| 1501 | |
| 1502 | std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, |
| 1503 | BoundArch BA, |
| 1504 | types::ID InputType) const { |
| 1505 | return ComputeLLVMTriple(Args, BA, InputType); |
| 1506 | } |
| 1507 | |
| 1508 | std::string ToolChain::computeSysRoot() const { |
| 1509 | return D.SysRoot; |
| 1510 | } |
| 1511 | |
| 1512 | void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, |
| 1513 | ArgStringList &CC1Args) const { |
| 1514 | // Each toolchain should provide the appropriate include flags. |
| 1515 | } |
| 1516 | |
| 1517 | void ToolChain::addClangTargetOptions( |
| 1518 | const ArgList &DriverArgs, ArgStringList &CC1Args, BoundArch BA, |
| 1519 | Action::OffloadKind DeviceOffloadKind) const {} |
| 1520 | |
| 1521 | void ToolChain::addClangCC1ASTargetOptions(const ArgList &Args, |
| 1522 | ArgStringList &CC1ASArgs) const {} |
| 1523 | |
| 1524 | void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} |
| 1525 | |
| 1526 | void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, |
| 1527 | llvm::opt::ArgStringList &CmdArgs) const { |
| 1528 | if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args)) |
| 1529 | return; |
| 1530 | |
| 1531 | CmdArgs.push_back(Elt: getCompilerRTArgString(Args, Component: "profile" )); |
| 1532 | } |
| 1533 | |
| 1534 | ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( |
| 1535 | const ArgList &Args) const { |
| 1536 | if (runtimeLibType) |
| 1537 | return *runtimeLibType; |
| 1538 | |
| 1539 | const Arg* A = Args.getLastArg(Ids: options::OPT_rtlib_EQ); |
| 1540 | StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; |
| 1541 | |
| 1542 | // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! |
| 1543 | if (LibName == "compiler-rt" ) |
| 1544 | runtimeLibType = ToolChain::RLT_CompilerRT; |
| 1545 | else if (LibName == "libgcc" ) |
| 1546 | runtimeLibType = ToolChain::RLT_Libgcc; |
| 1547 | else if (LibName == "platform" ) |
| 1548 | runtimeLibType = GetDefaultRuntimeLibType(); |
| 1549 | else { |
| 1550 | if (A) |
| 1551 | getDriver().Diag(DiagID: diag::err_drv_invalid_rtlib_name) |
| 1552 | << A->getAsString(Args); |
| 1553 | |
| 1554 | runtimeLibType = GetDefaultRuntimeLibType(); |
| 1555 | } |
| 1556 | |
| 1557 | return *runtimeLibType; |
| 1558 | } |
| 1559 | |
| 1560 | ToolChain::UnwindLibType ToolChain::GetUnwindLibType( |
| 1561 | const ArgList &Args) const { |
| 1562 | if (unwindLibType) |
| 1563 | return *unwindLibType; |
| 1564 | |
| 1565 | const Arg *A = Args.getLastArg(Ids: options::OPT_unwindlib_EQ); |
| 1566 | StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB; |
| 1567 | |
| 1568 | if (LibName == "none" ) |
| 1569 | unwindLibType = ToolChain::UNW_None; |
| 1570 | else if (LibName == "platform" || LibName == "" ) { |
| 1571 | ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args); |
| 1572 | if (RtLibType == ToolChain::RLT_CompilerRT) { |
| 1573 | if (getTriple().isAndroid() || getTriple().isOSAIX() || |
| 1574 | getTriple().isOSSerenity()) |
| 1575 | unwindLibType = ToolChain::UNW_CompilerRT; |
| 1576 | else |
| 1577 | unwindLibType = ToolChain::UNW_None; |
| 1578 | } else if (RtLibType == ToolChain::RLT_Libgcc) |
| 1579 | unwindLibType = ToolChain::UNW_Libgcc; |
| 1580 | } else if (LibName == "libunwind" ) { |
| 1581 | if (GetRuntimeLibType(Args) == RLT_Libgcc) |
| 1582 | getDriver().Diag(DiagID: diag::err_drv_incompatible_unwindlib); |
| 1583 | unwindLibType = ToolChain::UNW_CompilerRT; |
| 1584 | } else if (LibName == "libgcc" ) |
| 1585 | unwindLibType = ToolChain::UNW_Libgcc; |
| 1586 | else { |
| 1587 | if (A) |
| 1588 | getDriver().Diag(DiagID: diag::err_drv_invalid_unwindlib_name) |
| 1589 | << A->getAsString(Args); |
| 1590 | |
| 1591 | unwindLibType = GetDefaultUnwindLibType(); |
| 1592 | } |
| 1593 | |
| 1594 | return *unwindLibType; |
| 1595 | } |
| 1596 | |
| 1597 | ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ |
| 1598 | if (cxxStdlibType) |
| 1599 | return *cxxStdlibType; |
| 1600 | |
| 1601 | const Arg *A = Args.getLastArg(Ids: options::OPT_stdlib_EQ); |
| 1602 | StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; |
| 1603 | |
| 1604 | // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! |
| 1605 | if (LibName == "libc++" ) |
| 1606 | cxxStdlibType = ToolChain::CST_Libcxx; |
| 1607 | else if (LibName == "libstdc++" ) |
| 1608 | cxxStdlibType = ToolChain::CST_Libstdcxx; |
| 1609 | else if (LibName == "platform" ) |
| 1610 | cxxStdlibType = GetDefaultCXXStdlibType(); |
| 1611 | else { |
| 1612 | if (A) |
| 1613 | getDriver().Diag(DiagID: diag::err_drv_invalid_stdlib_name) |
| 1614 | << A->getAsString(Args); |
| 1615 | |
| 1616 | cxxStdlibType = GetDefaultCXXStdlibType(); |
| 1617 | } |
| 1618 | |
| 1619 | return *cxxStdlibType; |
| 1620 | } |
| 1621 | |
| 1622 | ToolChain::CStdlibType ToolChain::GetCStdlibType(const ArgList &Args) const { |
| 1623 | if (cStdlibType) |
| 1624 | return *cStdlibType; |
| 1625 | |
| 1626 | const Arg *A = Args.getLastArg(Ids: options::OPT_cstdlib_EQ); |
| 1627 | StringRef LibName = A ? A->getValue() : "system" ; |
| 1628 | |
| 1629 | if (LibName == "newlib" ) |
| 1630 | cStdlibType = ToolChain::CST_Newlib; |
| 1631 | else if (LibName == "picolibc" ) |
| 1632 | cStdlibType = ToolChain::CST_Picolibc; |
| 1633 | else if (LibName == "llvm-libc" ) |
| 1634 | cStdlibType = ToolChain::CST_LLVMLibC; |
| 1635 | else if (LibName == "system" ) |
| 1636 | cStdlibType = ToolChain::CST_System; |
| 1637 | else { |
| 1638 | if (A) |
| 1639 | getDriver().Diag(DiagID: diag::err_drv_invalid_cstdlib_name) |
| 1640 | << A->getAsString(Args); |
| 1641 | cStdlibType = ToolChain::CST_System; |
| 1642 | } |
| 1643 | |
| 1644 | return *cStdlibType; |
| 1645 | } |
| 1646 | |
| 1647 | /// Utility function to add a system framework directory to CC1 arguments. |
| 1648 | void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs, |
| 1649 | llvm::opt::ArgStringList &CC1Args, |
| 1650 | const Twine &Path) { |
| 1651 | CC1Args.push_back(Elt: "-internal-iframework" ); |
| 1652 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
| 1653 | } |
| 1654 | |
| 1655 | /// Utility function to add a system include directory with extern "C" |
| 1656 | /// semantics to CC1 arguments. |
| 1657 | /// |
| 1658 | /// Note that this should be used rarely, and only for directories that |
| 1659 | /// historically and for legacy reasons are treated as having implicit extern |
| 1660 | /// "C" semantics. These semantics are *ignored* by and large today, but its |
| 1661 | /// important to preserve the preprocessor changes resulting from the |
| 1662 | /// classification. |
| 1663 | void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, |
| 1664 | ArgStringList &CC1Args, |
| 1665 | const Twine &Path) { |
| 1666 | CC1Args.push_back(Elt: "-internal-externc-isystem" ); |
| 1667 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
| 1668 | } |
| 1669 | |
| 1670 | void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, |
| 1671 | ArgStringList &CC1Args, |
| 1672 | const Twine &Path) { |
| 1673 | if (llvm::sys::fs::exists(Path)) |
| 1674 | addExternCSystemInclude(DriverArgs, CC1Args, Path); |
| 1675 | } |
| 1676 | |
| 1677 | /// Utility function to add a system include directory to CC1 arguments. |
| 1678 | /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, |
| 1679 | ArgStringList &CC1Args, |
| 1680 | const Twine &Path) { |
| 1681 | CC1Args.push_back(Elt: "-internal-isystem" ); |
| 1682 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
| 1683 | } |
| 1684 | |
| 1685 | /// Utility function to add a list of system framework directories to CC1. |
| 1686 | void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs, |
| 1687 | ArgStringList &CC1Args, |
| 1688 | ArrayRef<StringRef> Paths) { |
| 1689 | for (const auto &Path : Paths) { |
| 1690 | CC1Args.push_back(Elt: "-internal-iframework" ); |
| 1691 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
| 1692 | } |
| 1693 | } |
| 1694 | |
| 1695 | /// Utility function to add a list of system include directories to CC1. |
| 1696 | void ToolChain::addSystemIncludes(const ArgList &DriverArgs, |
| 1697 | ArgStringList &CC1Args, |
| 1698 | ArrayRef<StringRef> Paths) { |
| 1699 | for (const auto &Path : Paths) { |
| 1700 | CC1Args.push_back(Elt: "-internal-isystem" ); |
| 1701 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
| 1702 | } |
| 1703 | } |
| 1704 | |
| 1705 | std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B, |
| 1706 | const Twine &C, const Twine &D) { |
| 1707 | SmallString<128> Result(Path); |
| 1708 | llvm::sys::path::append(path&: Result, style: llvm::sys::path::Style::posix, a: A, b: B, c: C, d: D); |
| 1709 | return std::string(Result); |
| 1710 | } |
| 1711 | |
| 1712 | std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const { |
| 1713 | std::error_code EC; |
| 1714 | int MaxVersion = 0; |
| 1715 | std::string MaxVersionString; |
| 1716 | SmallString<128> Path(IncludePath); |
| 1717 | llvm::sys::path::append(path&: Path, a: "c++" ); |
| 1718 | for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Dir: Path, EC), LE; |
| 1719 | !EC && LI != LE; LI = LI.increment(EC)) { |
| 1720 | StringRef VersionText = llvm::sys::path::filename(path: LI->path()); |
| 1721 | int Version; |
| 1722 | if (VersionText[0] == 'v' && |
| 1723 | !VersionText.substr(Start: 1).getAsInteger(Radix: 10, Result&: Version)) { |
| 1724 | if (Version > MaxVersion) { |
| 1725 | MaxVersion = Version; |
| 1726 | MaxVersionString = std::string(VersionText); |
| 1727 | } |
| 1728 | } |
| 1729 | } |
| 1730 | if (!MaxVersion) |
| 1731 | return "" ; |
| 1732 | return MaxVersionString; |
| 1733 | } |
| 1734 | |
| 1735 | void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, |
| 1736 | ArgStringList &CC1Args) const { |
| 1737 | // Header search paths should be handled by each of the subclasses. |
| 1738 | // Historically, they have not been, and instead have been handled inside of |
| 1739 | // the CC1-layer frontend. As the logic is hoisted out, this generic function |
| 1740 | // will slowly stop being called. |
| 1741 | // |
| 1742 | // While it is being called, replicate a bit of a hack to propagate the |
| 1743 | // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ |
| 1744 | // header search paths with it. Once all systems are overriding this |
| 1745 | // function, the CC1 flag and this line can be removed. |
| 1746 | DriverArgs.AddAllArgs(Output&: CC1Args, Id0: options::OPT_stdlib_EQ); |
| 1747 | } |
| 1748 | |
| 1749 | void ToolChain::AddClangCXXStdlibIsystemArgs( |
| 1750 | const llvm::opt::ArgList &DriverArgs, |
| 1751 | llvm::opt::ArgStringList &CC1Args) const { |
| 1752 | DriverArgs.ClaimAllArgs(Id0: options::OPT_stdlibxx_isystem); |
| 1753 | // This intentionally only looks at -nostdinc++, and not -nostdinc or |
| 1754 | // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain |
| 1755 | // setups with non-standard search logic for the C++ headers, while still |
| 1756 | // allowing users of the toolchain to bring their own C++ headers. Such a |
| 1757 | // toolchain likely also has non-standard search logic for the C headers and |
| 1758 | // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should |
| 1759 | // still work in that case and only be suppressed by an explicit -nostdinc++ |
| 1760 | // in a project using the toolchain. |
| 1761 | if (!DriverArgs.hasArg(Ids: options::OPT_nostdincxx)) |
| 1762 | for (const auto &P : |
| 1763 | DriverArgs.getAllArgValues(Id: options::OPT_stdlibxx_isystem)) |
| 1764 | addSystemInclude(DriverArgs, CC1Args, Path: P); |
| 1765 | } |
| 1766 | |
| 1767 | bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { |
| 1768 | return getDriver().CCCIsCXX() && |
| 1769 | !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs, |
| 1770 | Ids: options::OPT_nostdlibxx); |
| 1771 | } |
| 1772 | |
| 1773 | void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, |
| 1774 | ArgStringList &CmdArgs) const { |
| 1775 | assert(!Args.hasArg(options::OPT_nostdlibxx) && |
| 1776 | "should not have called this" ); |
| 1777 | CXXStdlibType Type = GetCXXStdlibType(Args); |
| 1778 | |
| 1779 | switch (Type) { |
| 1780 | case ToolChain::CST_Libcxx: |
| 1781 | CmdArgs.push_back(Elt: "-lc++" ); |
| 1782 | if (Args.hasArg(Ids: options::OPT_fexperimental_library)) |
| 1783 | CmdArgs.push_back(Elt: "-lc++experimental" ); |
| 1784 | break; |
| 1785 | |
| 1786 | case ToolChain::CST_Libstdcxx: |
| 1787 | CmdArgs.push_back(Elt: "-lstdc++" ); |
| 1788 | break; |
| 1789 | } |
| 1790 | } |
| 1791 | |
| 1792 | void ToolChain::AddFilePathLibArgs(const ArgList &Args, |
| 1793 | ArgStringList &CmdArgs) const { |
| 1794 | for (const auto &LibPath : getFilePaths()) |
| 1795 | if(LibPath.length() > 0) |
| 1796 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: StringRef("-L" ) + LibPath)); |
| 1797 | } |
| 1798 | |
| 1799 | void ToolChain::AddCCKextLibArgs(const ArgList &Args, |
| 1800 | ArgStringList &CmdArgs) const { |
| 1801 | CmdArgs.push_back(Elt: "-lcc_kext" ); |
| 1802 | } |
| 1803 | |
| 1804 | bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args, |
| 1805 | std::string &Path) const { |
| 1806 | // Don't implicitly link in mode-changing libraries in a shared library, since |
| 1807 | // this can have very deleterious effects. See the various links from |
| 1808 | // https://github.com/llvm/llvm-project/issues/57589 for more information. |
| 1809 | bool Default = !Args.hasArgNoClaim(Ids: options::OPT_shared); |
| 1810 | |
| 1811 | // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed |
| 1812 | // (to keep the linker options consistent with gcc and clang itself). |
| 1813 | if (Default && !isOptimizationLevelFast(Args)) { |
| 1814 | // Check if -ffast-math or -funsafe-math. |
| 1815 | Arg *A = Args.getLastArg( |
| 1816 | Ids: options::OPT_ffast_math, Ids: options::OPT_fno_fast_math, |
| 1817 | Ids: options::OPT_funsafe_math_optimizations, |
| 1818 | Ids: options::OPT_fno_unsafe_math_optimizations, Ids: options::OPT_ffp_model_EQ); |
| 1819 | |
| 1820 | if (!A || A->getOption().getID() == options::OPT_fno_fast_math || |
| 1821 | A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) |
| 1822 | Default = false; |
| 1823 | if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) { |
| 1824 | StringRef Model = A->getValue(); |
| 1825 | if (Model != "fast" && Model != "aggressive" ) |
| 1826 | Default = false; |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | // Whatever decision came as a result of the above implicit settings, either |
| 1831 | // -mdaz-ftz or -mno-daz-ftz is capable of overriding it. |
| 1832 | if (!Args.hasFlag(Pos: options::OPT_mdaz_ftz, Neg: options::OPT_mno_daz_ftz, Default)) |
| 1833 | return false; |
| 1834 | |
| 1835 | // If crtfastmath.o exists add it to the arguments. |
| 1836 | Path = GetFilePath(Name: "crtfastmath.o" ); |
| 1837 | return (Path != "crtfastmath.o" ); // Not found. |
| 1838 | } |
| 1839 | |
| 1840 | bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args, |
| 1841 | ArgStringList &CmdArgs) const { |
| 1842 | std::string Path; |
| 1843 | if (isFastMathRuntimeAvailable(Args, Path)) { |
| 1844 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path)); |
| 1845 | return true; |
| 1846 | } |
| 1847 | |
| 1848 | return false; |
| 1849 | } |
| 1850 | |
| 1851 | Expected<SmallVector<std::string>> |
| 1852 | ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const { |
| 1853 | return SmallVector<std::string>(); |
| 1854 | } |
| 1855 | |
| 1856 | SanitizerMask |
| 1857 | ToolChain::getSupportedSanitizers(BoundArch BA, |
| 1858 | Action::OffloadKind DeviceOffloadKind) const { |
| 1859 | // Return sanitizers which don't require runtime support and are not |
| 1860 | // platform dependent. |
| 1861 | |
| 1862 | SanitizerMask Res = |
| 1863 | (SanitizerKind::Undefined & ~SanitizerKind::Vptr) | |
| 1864 | (SanitizerKind::CFI & ~SanitizerKind::CFIICall) | |
| 1865 | SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero | |
| 1866 | SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow | |
| 1867 | SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion | |
| 1868 | SanitizerKind::Nullability | SanitizerKind::LocalBounds | |
| 1869 | SanitizerKind::AllocToken; |
| 1870 | if (getTriple().getArch() == llvm::Triple::x86 || |
| 1871 | getTriple().getArch() == llvm::Triple::x86_64 || |
| 1872 | getTriple().getArch() == llvm::Triple::arm || |
| 1873 | getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() || |
| 1874 | getTriple().isAArch64() || getTriple().isRISCV() || |
| 1875 | getTriple().isLoongArch64() || |
| 1876 | getTriple().getArch() == llvm::Triple::hexagon) |
| 1877 | Res |= SanitizerKind::CFIICall; |
| 1878 | if (getTriple().getArch() == llvm::Triple::x86_64 || |
| 1879 | getTriple().isAArch64(PointerWidth: 64) || getTriple().isRISCV()) |
| 1880 | Res |= SanitizerKind::ShadowCallStack; |
| 1881 | if (getTriple().isAArch64(PointerWidth: 64)) |
| 1882 | Res |= SanitizerKind::MemTag; |
| 1883 | if (getTriple().isBPF()) |
| 1884 | Res |= SanitizerKind::KernelAddress; |
| 1885 | return Res; |
| 1886 | } |
| 1887 | |
| 1888 | void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, |
| 1889 | ArgStringList &CC1Args) const {} |
| 1890 | |
| 1891 | void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs, |
| 1892 | ArgStringList &CC1Args) const {} |
| 1893 | |
| 1894 | void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs, |
| 1895 | ArgStringList &CC1Args) const {} |
| 1896 | |
| 1897 | llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12> |
| 1898 | ToolChain::getDeviceLibs(const ArgList &DriverArgs, BoundArch BA, |
| 1899 | const Action::OffloadKind DeviceOffloadingKind) const { |
| 1900 | return {}; |
| 1901 | } |
| 1902 | |
| 1903 | void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, |
| 1904 | ArgStringList &CC1Args) const {} |
| 1905 | |
| 1906 | static VersionTuple separateMSVCFullVersion(unsigned Version) { |
| 1907 | if (Version < 100) |
| 1908 | return VersionTuple(Version); |
| 1909 | |
| 1910 | if (Version < 10000) |
| 1911 | return VersionTuple(Version / 100, Version % 100); |
| 1912 | |
| 1913 | unsigned Build = 0, Factor = 1; |
| 1914 | for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) |
| 1915 | Build = Build + (Version % 10) * Factor; |
| 1916 | return VersionTuple(Version / 100, Version % 100, Build); |
| 1917 | } |
| 1918 | |
| 1919 | VersionTuple |
| 1920 | ToolChain::computeMSVCVersion(const Driver *D, |
| 1921 | const llvm::opt::ArgList &Args) const { |
| 1922 | const Arg *MSCVersion = Args.getLastArg(Ids: options::OPT_fmsc_version); |
| 1923 | const Arg *MSCompatibilityVersion = |
| 1924 | Args.getLastArg(Ids: options::OPT_fms_compatibility_version); |
| 1925 | |
| 1926 | if (MSCVersion && MSCompatibilityVersion) { |
| 1927 | if (D) |
| 1928 | D->Diag(DiagID: diag::err_drv_argument_not_allowed_with) |
| 1929 | << MSCVersion->getAsString(Args) |
| 1930 | << MSCompatibilityVersion->getAsString(Args); |
| 1931 | return VersionTuple(); |
| 1932 | } |
| 1933 | |
| 1934 | if (MSCompatibilityVersion) { |
| 1935 | VersionTuple MSVT; |
| 1936 | if (MSVT.tryParse(string: MSCompatibilityVersion->getValue())) { |
| 1937 | if (D) |
| 1938 | D->Diag(DiagID: diag::err_drv_invalid_value) |
| 1939 | << MSCompatibilityVersion->getAsString(Args) |
| 1940 | << MSCompatibilityVersion->getValue(); |
| 1941 | } else { |
| 1942 | return MSVT; |
| 1943 | } |
| 1944 | } |
| 1945 | |
| 1946 | if (MSCVersion) { |
| 1947 | unsigned Version = 0; |
| 1948 | if (StringRef(MSCVersion->getValue()).getAsInteger(Radix: 10, Result&: Version)) { |
| 1949 | if (D) |
| 1950 | D->Diag(DiagID: diag::err_drv_invalid_value) |
| 1951 | << MSCVersion->getAsString(Args) << MSCVersion->getValue(); |
| 1952 | } else { |
| 1953 | return separateMSVCFullVersion(Version); |
| 1954 | } |
| 1955 | } |
| 1956 | |
| 1957 | return VersionTuple(); |
| 1958 | } |
| 1959 | |
| 1960 | llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( |
| 1961 | const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, |
| 1962 | SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { |
| 1963 | DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); |
| 1964 | const OptTable &Opts = getDriver().getOpts(); |
| 1965 | bool Modified = false; |
| 1966 | |
| 1967 | // Handle -Xopenmp-target flags |
| 1968 | for (auto *A : Args) { |
| 1969 | // Exclude flags which may only apply to the host toolchain. |
| 1970 | // Do not exclude flags when the host triple (AuxTriple) |
| 1971 | // matches the current toolchain triple. If it is not present |
| 1972 | // at all, target and host share a toolchain. |
| 1973 | if (A->getOption().matches(ID: options::OPT_m_Group)) { |
| 1974 | // Pass certain options to the device toolchain even when the triple |
| 1975 | // differs from the host: code object version must be passed to correctly |
| 1976 | // set metadata in intermediate files; linker version must be passed |
| 1977 | // because the Darwin toolchain requires the host and device linker |
| 1978 | // versions to match (the host version is cached in |
| 1979 | // MachO::getLinkerVersion). |
| 1980 | if (SameTripleAsHost || |
| 1981 | A->getOption().matches(ID: options::OPT_mcode_object_version_EQ) || |
| 1982 | A->getOption().matches(ID: options::OPT_mlinker_version_EQ)) |
| 1983 | DAL->append(A); |
| 1984 | else |
| 1985 | Modified = true; |
| 1986 | continue; |
| 1987 | } |
| 1988 | |
| 1989 | unsigned Index; |
| 1990 | unsigned Prev; |
| 1991 | bool XOpenMPTargetNoTriple = |
| 1992 | A->getOption().matches(ID: options::OPT_Xopenmp_target); |
| 1993 | |
| 1994 | if (A->getOption().matches(ID: options::OPT_Xopenmp_target_EQ)) { |
| 1995 | llvm::Triple TT = normalizeOffloadTriple(OrigTT: A->getValue(N: 0)); |
| 1996 | |
| 1997 | // Passing device args: -Xopenmp-target=<triple> -opt=val. |
| 1998 | if (TT.isCompatibleWith(Other: getTriple())) |
| 1999 | Index = Args.getBaseArgs().MakeIndex(String0: A->getValue(N: 1)); |
| 2000 | else |
| 2001 | continue; |
| 2002 | } else if (XOpenMPTargetNoTriple) { |
| 2003 | // Passing device args: -Xopenmp-target -opt=val. |
| 2004 | Index = Args.getBaseArgs().MakeIndex(String0: A->getValue(N: 0)); |
| 2005 | } else { |
| 2006 | DAL->append(A); |
| 2007 | continue; |
| 2008 | } |
| 2009 | |
| 2010 | // Parse the argument to -Xopenmp-target. |
| 2011 | Prev = Index; |
| 2012 | std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); |
| 2013 | if (!XOpenMPTargetArg || Index > Prev + 1) { |
| 2014 | if (!A->isClaimed()) { |
| 2015 | getDriver().Diag(DiagID: diag::err_drv_invalid_Xopenmp_target_with_args) |
| 2016 | << A->getAsString(Args); |
| 2017 | } |
| 2018 | continue; |
| 2019 | } |
| 2020 | if (XOpenMPTargetNoTriple && XOpenMPTargetArg && |
| 2021 | Args.getAllArgValues(Id: options::OPT_offload_targets_EQ).size() != 1) { |
| 2022 | getDriver().Diag(DiagID: diag::err_drv_Xopenmp_target_missing_triple); |
| 2023 | continue; |
| 2024 | } |
| 2025 | XOpenMPTargetArg->setBaseArg(A); |
| 2026 | A = XOpenMPTargetArg.release(); |
| 2027 | AllocatedArgs.push_back(Elt: A); |
| 2028 | DAL->append(A); |
| 2029 | Modified = true; |
| 2030 | } |
| 2031 | |
| 2032 | if (Modified) |
| 2033 | return DAL; |
| 2034 | |
| 2035 | delete DAL; |
| 2036 | return nullptr; |
| 2037 | } |
| 2038 | |
| 2039 | // TODO: Currently argument values separated by space e.g. |
| 2040 | // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be |
| 2041 | // fixed. |
| 2042 | void ToolChain::TranslateXarchArgs( |
| 2043 | const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, |
| 2044 | llvm::opt::DerivedArgList *DAL, |
| 2045 | SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { |
| 2046 | const OptTable &Opts = getDriver().getOpts(); |
| 2047 | unsigned ValuePos = 1; |
| 2048 | if (A->getOption().matches(ID: options::OPT_Xarch_device) || |
| 2049 | A->getOption().matches(ID: options::OPT_Xarch_host)) |
| 2050 | ValuePos = 0; |
| 2051 | |
| 2052 | const InputArgList &BaseArgs = Args.getBaseArgs(); |
| 2053 | unsigned Index = BaseArgs.MakeIndex(String0: A->getValue(N: ValuePos)); |
| 2054 | unsigned Prev = Index; |
| 2055 | std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg( |
| 2056 | Args, Index, VisibilityMask: llvm::opt::Visibility(options::ClangOption))); |
| 2057 | |
| 2058 | // If the argument parsing failed or more than one argument was |
| 2059 | // consumed, the -Xarch_ argument's parameter tried to consume |
| 2060 | // extra arguments. Emit an error and ignore. |
| 2061 | // |
| 2062 | // We also want to disallow any options which would alter the |
| 2063 | // driver behavior; that isn't going to work in our model. We |
| 2064 | // use options::NoXarchOption to control this. |
| 2065 | if (!XarchArg || Index > Prev + 1) { |
| 2066 | getDriver().Diag(DiagID: diag::err_drv_invalid_Xarch_argument_with_args) |
| 2067 | << A->getAsString(Args); |
| 2068 | return; |
| 2069 | } else if (XarchArg->getOption().hasFlag(Val: options::NoXarchOption)) { |
| 2070 | auto &Diags = getDriver().getDiags(); |
| 2071 | unsigned DiagID = |
| 2072 | Diags.getCustomDiagID(L: DiagnosticsEngine::Error, |
| 2073 | FormatString: "invalid Xarch argument: '%0', not all driver " |
| 2074 | "options can be forwared via Xarch argument" ); |
| 2075 | Diags.Report(DiagID) << A->getAsString(Args); |
| 2076 | return; |
| 2077 | } |
| 2078 | |
| 2079 | XarchArg->setBaseArg(A); |
| 2080 | A = XarchArg.release(); |
| 2081 | |
| 2082 | // Linker input arguments require custom handling. The problem is that we |
| 2083 | // have already constructed the phase actions, so we can not treat them as |
| 2084 | // "input arguments". |
| 2085 | if (A->getOption().hasFlag(Val: options::LinkerInput)) { |
| 2086 | // Convert the argument into individual Zlinker_input_args. Need to do this |
| 2087 | // manually to avoid memory leaks with the allocated arguments. |
| 2088 | for (const char *Value : A->getValues()) { |
| 2089 | auto Opt = Opts.getOption(Opt: options::OPT_Zlinker_input); |
| 2090 | unsigned Index = BaseArgs.MakeIndex(String0: Opt.getName(), String1: Value); |
| 2091 | auto NewArg = |
| 2092 | new Arg(Opt, BaseArgs.MakeArgString(Str: Opt.getPrefix() + Opt.getName()), |
| 2093 | Index, BaseArgs.getArgString(Index: Index + 1), A); |
| 2094 | |
| 2095 | DAL->append(A: NewArg); |
| 2096 | if (!AllocatedArgs) |
| 2097 | DAL->AddSynthesizedArg(A: NewArg); |
| 2098 | else |
| 2099 | AllocatedArgs->push_back(Elt: NewArg); |
| 2100 | } |
| 2101 | } |
| 2102 | |
| 2103 | if (!AllocatedArgs) |
| 2104 | DAL->AddSynthesizedArg(A); |
| 2105 | else |
| 2106 | AllocatedArgs->push_back(Elt: A); |
| 2107 | } |
| 2108 | |
| 2109 | /// Match any triple recognized arch aliases. |
| 2110 | static bool isXArchCompatibleTripleArch(const llvm::Triple &TT, |
| 2111 | StringRef XArchVal) { |
| 2112 | llvm::Triple ParsedTriple(XArchVal); |
| 2113 | return TT.getArch() == ParsedTriple.getArch() && |
| 2114 | TT.getSubArch() == ParsedTriple.getSubArch(); |
| 2115 | } |
| 2116 | |
| 2117 | llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs( |
| 2118 | const llvm::opt::DerivedArgList &Args, BoundArch BA, |
| 2119 | Action::OffloadKind OFK, |
| 2120 | SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { |
| 2121 | DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); |
| 2122 | bool Modified = false; |
| 2123 | |
| 2124 | bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host; |
| 2125 | for (Arg *A : Args) { |
| 2126 | bool NeedTrans = false; |
| 2127 | bool Skip = false; |
| 2128 | if (A->getOption().matches(ID: options::OPT_Xarch_device)) { |
| 2129 | NeedTrans = IsDevice; |
| 2130 | Skip = !IsDevice; |
| 2131 | } else if (A->getOption().matches(ID: options::OPT_Xarch_host)) { |
| 2132 | NeedTrans = !IsDevice; |
| 2133 | Skip = IsDevice; |
| 2134 | } else if (A->getOption().matches(ID: options::OPT_Xarch__)) { |
| 2135 | StringRef Val = A->getValue(); |
| 2136 | NeedTrans = Val == getArchName() || (BA && Val == BA.ArchName) || |
| 2137 | isXArchCompatibleTripleArch(TT: Triple, XArchVal: Val); |
| 2138 | Skip = !NeedTrans; |
| 2139 | } |
| 2140 | if (NeedTrans || Skip) |
| 2141 | Modified = true; |
| 2142 | if (NeedTrans) { |
| 2143 | A->claim(); |
| 2144 | TranslateXarchArgs(Args, A, DAL, AllocatedArgs); |
| 2145 | } |
| 2146 | if (!Skip) |
| 2147 | DAL->append(A); |
| 2148 | } |
| 2149 | |
| 2150 | if (Modified) |
| 2151 | return DAL; |
| 2152 | |
| 2153 | delete DAL; |
| 2154 | return nullptr; |
| 2155 | } |
| 2156 | |