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