1//===--- TargetInfo.cpp - Information about Target machine ----------------===//
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// This file implements the TargetInfo interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Basic/TargetInfo.h"
14#include "clang/Basic/AddressSpaces.h"
15#include "clang/Basic/CharInfo.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticFrontend.h"
18#include "clang/Basic/LangOptions.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/ErrorHandling.h"
23#include "llvm/TargetParser/TargetParser.h"
24#include <cstdlib>
25using namespace clang;
26
27static constexpr LangASMap DefaultAddrSpaceMap;
28// The fake address space map must have a distinct entry for each
29// language-specific address space.
30static constexpr LangASMap FakeAddrSpaceMap = {
31 {LangAS::Default, 0},
32 {LangAS::opencl_global, 1},
33 {LangAS::opencl_local, 3},
34 {LangAS::opencl_constant, 2},
35 {LangAS::opencl_private, 0},
36 {LangAS::opencl_generic, 4},
37 {LangAS::opencl_global_device, 5},
38 {LangAS::opencl_global_host, 6},
39 {LangAS::cuda_device, 7},
40 {LangAS::cuda_constant, 8},
41 {LangAS::cuda_shared, 9},
42 {LangAS::sycl_global, 1},
43 {LangAS::sycl_global_device, 5},
44 {LangAS::sycl_global_host, 6},
45 {LangAS::sycl_local, 3},
46 {LangAS::sycl_private, 0},
47 {LangAS::ptr32_sptr, 10},
48 {LangAS::ptr32_uptr, 11},
49 {LangAS::ptr64, 12},
50 {LangAS::hlsl_groupshared, 13},
51 {LangAS::hlsl_constant, 14},
52 {LangAS::hlsl_private, 15},
53 {LangAS::hlsl_device, 16},
54 {LangAS::hlsl_input, 17},
55 {LangAS::hlsl_output, 18},
56 {LangAS::hlsl_push_constant, 19},
57 {LangAS::wasm_funcref, 20},
58};
59
60// TargetInfo Constructor.
61TargetInfo::TargetInfo(const llvm::Triple &T) : Triple(T) {
62 // Set defaults. Defaults are set for a 32-bit RISC platform, like PPC or
63 // SPARC. These should be overridden by concrete targets as needed.
64 HasMustTail = true;
65 BigEndian = !T.isLittleEndian();
66 TLSSupported = true;
67 VLASupported = true;
68 NoAsmVariants = false;
69 HasFastHalfType = false;
70 HalfArgsAndReturns = false;
71 HasFloat128 = false;
72 HasIbm128 = false;
73 HasFloat16 = false;
74 HasBFloat16 = false;
75 HasFullBFloat16 = false;
76 HasLongDouble = true;
77 HasFPReturn = true;
78 HasStrictFP = false;
79 PointerWidth = PointerAlign = 32;
80 BoolWidth = BoolAlign = 8;
81 ShortWidth = ShortAlign = 16;
82 IntWidth = IntAlign = 32;
83 LongWidth = LongAlign = 32;
84 LongLongWidth = LongLongAlign = 64;
85 Int128Align = 128;
86
87 // Fixed point default bit widths
88 ShortAccumWidth = ShortAccumAlign = 16;
89 AccumWidth = AccumAlign = 32;
90 LongAccumWidth = LongAccumAlign = 64;
91 ShortFractWidth = ShortFractAlign = 8;
92 FractWidth = FractAlign = 16;
93 LongFractWidth = LongFractAlign = 32;
94
95 // Fixed point default integral and fractional bit sizes
96 // We give the _Accum 1 fewer fractional bits than their corresponding _Fract
97 // types by default to have the same number of fractional bits between _Accum
98 // and _Fract types.
99 PaddingOnUnsignedFixedPoint = false;
100 ShortAccumScale = 7;
101 AccumScale = 15;
102 LongAccumScale = 31;
103
104 SuitableAlign = 64;
105 DefaultAlignForAttributeAligned = 128;
106 MinGlobalAlign = 0;
107 // From the glibc documentation, on GNU systems, malloc guarantees 16-byte
108 // alignment on 64-bit systems and 8-byte alignment on 32-bit systems. See
109 // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html.
110 // This alignment guarantee also applies to Windows and Android. On Darwin
111 // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit systems.
112 if (T.isGNUEnvironment() || T.isWindowsMSVCEnvironment() || T.isAndroid() ||
113 T.isOHOSFamily())
114 NewAlign = Triple.isArch64Bit() ? 128 : Triple.isArch32Bit() ? 64 : 0;
115 else if (T.isOSDarwin() || T.isOSOpenBSD())
116 NewAlign = 128;
117 else
118 NewAlign = 0; // Infer from basic type alignment.
119 HalfWidth = 16;
120 HalfAlign = 16;
121 FloatWidth = 32;
122 FloatAlign = 32;
123 DoubleWidth = 64;
124 DoubleAlign = 64;
125 LongDoubleWidth = 64;
126 LongDoubleAlign = 64;
127 Float128Align = 128;
128 Ibm128Align = 128;
129 LargeArrayMinWidth = 0;
130 LargeArrayAlign = 0;
131 MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0;
132 MaxVectorAlign = 0;
133 MaxTLSAlign = 0;
134 VectorsAreElementAligned = false;
135 SizeType = UnsignedLong;
136 PtrDiffType = SignedLong;
137 IntMaxType = SignedLongLong;
138 IntPtrType = SignedLong;
139 WCharType = SignedInt;
140 WIntType = SignedInt;
141 Char16Type = UnsignedShort;
142 Char32Type = UnsignedInt;
143 Int64Type = SignedLongLong;
144 Int16Type = SignedShort;
145 SigAtomicType = SignedInt;
146 ProcessIDType = SignedInt;
147 UseSignedCharForObjCBool = true;
148 UseBitFieldTypeAlignment = true;
149 UseZeroLengthBitfieldAlignment = false;
150 UseLeadingZeroLengthBitfield = true;
151 UseExplicitBitFieldAlignment = true;
152 ZeroLengthBitfieldBoundary = 0;
153 LargestOverSizedBitfieldContainer = 64;
154 MaxAlignedAttribute = 0;
155 HalfFormat = &llvm::APFloat::IEEEhalf();
156 FloatFormat = &llvm::APFloat::IEEEsingle();
157 DoubleFormat = &llvm::APFloat::IEEEdouble();
158 LongDoubleFormat = &llvm::APFloat::IEEEdouble();
159 Float128Format = &llvm::APFloat::IEEEquad();
160 Ibm128Format = &llvm::APFloat::PPCDoubleDouble();
161 MCountName = "mcount";
162 UserLabelPrefix = Triple.isOSBinFormatMachO() ? "_" : "";
163 RegParmMax = 0;
164 SSERegParmMax = 0;
165 HasAlignMac68kSupport = false;
166 HasBuiltinMSVaList = false;
167 HasBuiltinZOSVaList = false;
168 HasAArch64ACLETypes = false;
169 HasRISCVVTypes = false;
170 AllowAMDGPUUnsafeFPAtomics = false;
171 HasUnalignedAccess = false;
172 ARMCDECoprocMask = 0;
173
174 // Default to no types using fpret.
175 RealTypeUsesObjCFPRetMask = 0;
176
177 // Default to not using fp2ret for __Complex long double
178 ComplexLongDoubleUsesFP2Ret = false;
179
180 // Set the C++ ABI based on the triple.
181 TheCXXABI.set(Triple.isKnownWindowsMSVCEnvironment() || Triple.isUEFI()
182 ? TargetCXXABI::Microsoft
183 : TargetCXXABI::GenericItanium);
184
185 HasMicrosoftRecordLayout = TheCXXABI.isMicrosoft();
186
187 // Default to an empty address space map.
188 AddrSpaceMap = &DefaultAddrSpaceMap;
189 UseAddrSpaceMapMangling = false;
190
191 // Default to an unknown platform name.
192 PlatformName = "unknown";
193 PlatformMinVersion = VersionTuple();
194
195 MaxOpenCLWorkGroupSize = 1024;
196
197 MaxBitIntWidth.reset();
198}
199
200// Out of line virtual dtor for TargetInfo.
201TargetInfo::~TargetInfo() {}
202
203void TargetInfo::resetDataLayout(StringRef DL) { DataLayoutString = DL.str(); }
204
205void TargetInfo::resetDataLayout() {
206 DataLayoutString = Triple.computeDataLayout(ABIName: getABI());
207}
208
209bool
210TargetInfo::checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const {
211 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "cf-protection=branch";
212 return false;
213}
214
215CFBranchLabelSchemeKind TargetInfo::getDefaultCFBranchLabelScheme() const {
216 // if this hook is called, the target should override it to return a
217 // non-default scheme
218 llvm::report_fatal_error(reason: "not implemented");
219}
220
221bool TargetInfo::checkCFBranchLabelSchemeSupported(
222 const CFBranchLabelSchemeKind Scheme, DiagnosticsEngine &Diags) const {
223 if (Scheme != CFBranchLabelSchemeKind::Default)
224 Diags.Report(DiagID: diag::err_opt_not_valid_on_target)
225 << (Twine("mcf-branch-label-scheme=") +
226 getCFBranchLabelSchemeFlagVal(Scheme))
227 .str();
228 return false;
229}
230
231bool
232TargetInfo::checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const {
233 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "cf-protection=return";
234 return false;
235}
236
237/// getTypeName - Return the user string for the specified integer type enum.
238/// For example, SignedShort -> "short".
239const char *TargetInfo::getTypeName(IntType T) {
240 switch (T) {
241 default: llvm_unreachable("not an integer!");
242 case SignedChar: return "signed char";
243 case UnsignedChar: return "unsigned char";
244 case SignedShort: return "short";
245 case UnsignedShort: return "unsigned short";
246 case SignedInt: return "int";
247 case UnsignedInt: return "unsigned int";
248 case SignedLong: return "long int";
249 case UnsignedLong: return "long unsigned int";
250 case SignedLongLong: return "long long int";
251 case UnsignedLongLong: return "long long unsigned int";
252 }
253}
254
255/// getTypeConstantSuffix - Return the constant suffix for the specified
256/// integer type enum. For example, SignedLong -> "L".
257const char *TargetInfo::getTypeConstantSuffix(IntType T) const {
258 switch (T) {
259 default: llvm_unreachable("not an integer!");
260 case SignedChar:
261 case SignedShort:
262 case SignedInt: return "";
263 case SignedLong: return "L";
264 case SignedLongLong: return "LL";
265 case UnsignedChar:
266 if (getCharWidth() < getIntWidth())
267 return "";
268 [[fallthrough]];
269 case UnsignedShort:
270 if (getShortWidth() < getIntWidth())
271 return "";
272 [[fallthrough]];
273 case UnsignedInt: return "U";
274 case UnsignedLong: return "UL";
275 case UnsignedLongLong: return "ULL";
276 }
277}
278
279/// getTypeFormatModifier - Return the printf format modifier for the
280/// specified integer type enum. For example, SignedLong -> "l".
281
282const char *TargetInfo::getTypeFormatModifier(IntType T) {
283 switch (T) {
284 default: llvm_unreachable("not an integer!");
285 case SignedChar:
286 case UnsignedChar: return "hh";
287 case SignedShort:
288 case UnsignedShort: return "h";
289 case SignedInt:
290 case UnsignedInt: return "";
291 case SignedLong:
292 case UnsignedLong: return "l";
293 case SignedLongLong:
294 case UnsignedLongLong: return "ll";
295 }
296}
297
298/// getTypeWidth - Return the width (in bits) of the specified integer type
299/// enum. For example, SignedInt -> getIntWidth().
300unsigned TargetInfo::getTypeWidth(IntType T) const {
301 switch (T) {
302 default: llvm_unreachable("not an integer!");
303 case SignedChar:
304 case UnsignedChar: return getCharWidth();
305 case SignedShort:
306 case UnsignedShort: return getShortWidth();
307 case SignedInt:
308 case UnsignedInt: return getIntWidth();
309 case SignedLong:
310 case UnsignedLong: return getLongWidth();
311 case SignedLongLong:
312 case UnsignedLongLong: return getLongLongWidth();
313 };
314}
315
316TargetInfo::IntType TargetInfo::getIntTypeByWidth(
317 unsigned BitWidth, bool IsSigned) const {
318 if (getCharWidth() == BitWidth)
319 return IsSigned ? SignedChar : UnsignedChar;
320 if (getShortWidth() == BitWidth)
321 return IsSigned ? SignedShort : UnsignedShort;
322 if (getIntWidth() == BitWidth)
323 return IsSigned ? SignedInt : UnsignedInt;
324 if (getLongWidth() == BitWidth)
325 return IsSigned ? SignedLong : UnsignedLong;
326 if (getLongLongWidth() == BitWidth)
327 return IsSigned ? SignedLongLong : UnsignedLongLong;
328 return NoInt;
329}
330
331TargetInfo::IntType TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth,
332 bool IsSigned) const {
333 if (getCharWidth() >= BitWidth)
334 return IsSigned ? SignedChar : UnsignedChar;
335 if (getShortWidth() >= BitWidth)
336 return IsSigned ? SignedShort : UnsignedShort;
337 if (getIntWidth() >= BitWidth)
338 return IsSigned ? SignedInt : UnsignedInt;
339 if (getLongWidth() >= BitWidth)
340 return IsSigned ? SignedLong : UnsignedLong;
341 if (getLongLongWidth() >= BitWidth)
342 return IsSigned ? SignedLongLong : UnsignedLongLong;
343 return NoInt;
344}
345
346FloatModeKind TargetInfo::getRealTypeByWidth(unsigned BitWidth,
347 FloatModeKind ExplicitType) const {
348 if (getHalfWidth() == BitWidth)
349 return FloatModeKind::Half;
350 if (getFloatWidth() == BitWidth)
351 return FloatModeKind::Float;
352 if (getDoubleWidth() == BitWidth)
353 return FloatModeKind::Double;
354
355 switch (BitWidth) {
356 case 96:
357 if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
358 return FloatModeKind::LongDouble;
359 break;
360 case 128:
361 // The caller explicitly asked for an IEEE compliant type but we still
362 // have to check if the target supports it.
363 if (ExplicitType == FloatModeKind::Float128)
364 return hasFloat128Type() ? FloatModeKind::Float128
365 : FloatModeKind::NoFloat;
366 if (ExplicitType == FloatModeKind::Ibm128)
367 return hasIbm128Type() ? FloatModeKind::Ibm128
368 : FloatModeKind::NoFloat;
369 if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble() ||
370 &getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
371 return FloatModeKind::LongDouble;
372 if (hasFloat128Type())
373 return FloatModeKind::Float128;
374 break;
375 }
376
377 return FloatModeKind::NoFloat;
378}
379
380/// getTypeAlign - Return the alignment (in bits) of the specified integer type
381/// enum. For example, SignedInt -> getIntAlign().
382unsigned TargetInfo::getTypeAlign(IntType T) const {
383 switch (T) {
384 default: llvm_unreachable("not an integer!");
385 case SignedChar:
386 case UnsignedChar: return getCharAlign();
387 case SignedShort:
388 case UnsignedShort: return getShortAlign();
389 case SignedInt:
390 case UnsignedInt: return getIntAlign();
391 case SignedLong:
392 case UnsignedLong: return getLongAlign();
393 case SignedLongLong:
394 case UnsignedLongLong: return getLongLongAlign();
395 };
396}
397
398/// isTypeSigned - Return whether an integer types is signed. Returns true if
399/// the type is signed; false otherwise.
400bool TargetInfo::isTypeSigned(IntType T) {
401 switch (T) {
402 default: llvm_unreachable("not an integer!");
403 case SignedChar:
404 case SignedShort:
405 case SignedInt:
406 case SignedLong:
407 case SignedLongLong:
408 return true;
409 case UnsignedChar:
410 case UnsignedShort:
411 case UnsignedInt:
412 case UnsignedLong:
413 case UnsignedLongLong:
414 return false;
415 };
416}
417
418/// adjust - Set forced language options.
419/// Apply changes to the target information with respect to certain
420/// language options which change the target configuration and adjust
421/// the language based on the target options where applicable.
422void TargetInfo::adjust(DiagnosticsEngine &Diags, LangOptions &Opts,
423 const TargetInfo *Aux) {
424 if (Opts.NoBitFieldTypeAlign)
425 UseBitFieldTypeAlignment = false;
426
427 switch (Opts.WCharSize) {
428 default: llvm_unreachable("invalid wchar_t width");
429 case 0: break;
430 case 1: WCharType = Opts.WCharIsSigned ? SignedChar : UnsignedChar; break;
431 case 2: WCharType = Opts.WCharIsSigned ? SignedShort : UnsignedShort; break;
432 case 4: WCharType = Opts.WCharIsSigned ? SignedInt : UnsignedInt; break;
433 }
434
435 if (Opts.AlignDouble) {
436 DoubleAlign = LongLongAlign = 64;
437 LongDoubleAlign = 64;
438 }
439
440 // HLSL explicitly defines the sizes and formats of some data types, and we
441 // need to conform to those regardless of what architecture you are targeting.
442 if (Opts.HLSL) {
443 BoolWidth = BoolAlign = 32;
444 LongWidth = LongAlign = 64;
445 if (!Opts.NativeHalfType) {
446 HalfFormat = &llvm::APFloat::IEEEsingle();
447 HalfWidth = HalfAlign = 32;
448 }
449 }
450
451 if (Opts.OpenCL) {
452 // OpenCL C requires specific widths for types, irrespective of
453 // what these normally are for the target.
454 // We also define long long and long double here, although the
455 // OpenCL standard only mentions these as "reserved".
456 ShortWidth = ShortAlign = 16;
457 IntWidth = IntAlign = 32;
458 LongWidth = LongAlign = 64;
459 LongLongWidth = LongLongAlign = 128;
460 HalfWidth = HalfAlign = 16;
461 FloatWidth = FloatAlign = 32;
462
463 // Embedded 32-bit targets (OpenCL EP) might have double C type
464 // defined as float. Let's not override this as it might lead
465 // to generating illegal code that uses 64bit doubles.
466 if (DoubleWidth != FloatWidth) {
467 DoubleWidth = DoubleAlign = 64;
468 DoubleFormat = &llvm::APFloat::IEEEdouble();
469 }
470 LongDoubleWidth = LongDoubleAlign = 128;
471
472 unsigned MaxPointerWidth = getMaxPointerWidth();
473 assert(MaxPointerWidth == 32 || MaxPointerWidth == 64);
474 bool Is32BitArch = MaxPointerWidth == 32;
475 SizeType = Is32BitArch ? UnsignedInt : UnsignedLong;
476 PtrDiffType = Is32BitArch ? SignedInt : SignedLong;
477 IntPtrType = Is32BitArch ? SignedInt : SignedLong;
478
479 IntMaxType = SignedLongLong;
480 Int64Type = SignedLong;
481
482 HalfFormat = &llvm::APFloat::IEEEhalf();
483 FloatFormat = &llvm::APFloat::IEEEsingle();
484 LongDoubleFormat = &llvm::APFloat::IEEEquad();
485
486 // OpenCL C v3.0 s6.7.5 - The generic address space requires support for
487 // OpenCL C 2.0 or OpenCL C 3.0 with the __opencl_c_generic_address_space
488 // feature
489 // OpenCL C v3.0 s6.2.1 - OpenCL pipes require support of OpenCL C 2.0
490 // or later and __opencl_c_pipes feature
491 // FIXME: These language options are also defined in setLangDefaults()
492 // for OpenCL C 2.0 but with no access to target capabilities. Target
493 // should be immutable once created and thus these language options need
494 // to be defined only once.
495 if (Opts.getOpenCLCompatibleVersion() >= 300) {
496 const auto &OpenCLFeaturesMap = getSupportedOpenCLOpts();
497 Opts.OpenCLGenericAddressSpace = hasFeatureEnabled(
498 Features: OpenCLFeaturesMap, Name: "__opencl_c_generic_address_space");
499 Opts.OpenCLPipes =
500 hasFeatureEnabled(Features: OpenCLFeaturesMap, Name: "__opencl_c_pipes");
501 Opts.Blocks =
502 hasFeatureEnabled(Features: OpenCLFeaturesMap, Name: "__opencl_c_device_enqueue");
503 }
504 }
505
506 if (Opts.DoubleSize) {
507 if (Opts.DoubleSize == 32) {
508 DoubleWidth = 32;
509 LongDoubleWidth = 32;
510 DoubleFormat = &llvm::APFloat::IEEEsingle();
511 LongDoubleFormat = &llvm::APFloat::IEEEsingle();
512 } else if (Opts.DoubleSize == 64) {
513 DoubleWidth = 64;
514 LongDoubleWidth = 64;
515 DoubleFormat = &llvm::APFloat::IEEEdouble();
516 LongDoubleFormat = &llvm::APFloat::IEEEdouble();
517 }
518 }
519
520 if (Opts.LongDoubleSize) {
521 if (Opts.LongDoubleSize == DoubleWidth) {
522 LongDoubleWidth = DoubleWidth;
523 LongDoubleAlign = DoubleAlign;
524 LongDoubleFormat = DoubleFormat;
525 } else if (Opts.LongDoubleSize == 128) {
526 LongDoubleWidth = LongDoubleAlign = 128;
527 LongDoubleFormat = &llvm::APFloat::IEEEquad();
528 } else if (Opts.LongDoubleSize == 80) {
529 LongDoubleFormat = &llvm::APFloat::x87DoubleExtended();
530 if (getTriple().isWindowsMSVCEnvironment()) {
531 LongDoubleWidth = 128;
532 LongDoubleAlign = 128;
533 } else { // Linux
534 if (getTriple().getArch() == llvm::Triple::x86) {
535 LongDoubleWidth = 96;
536 LongDoubleAlign = 32;
537 } else {
538 LongDoubleWidth = 128;
539 LongDoubleAlign = 128;
540 }
541 }
542 }
543 }
544
545 if (Opts.NewAlignOverride)
546 NewAlign = Opts.NewAlignOverride * getCharWidth();
547
548 // Each unsigned fixed point type has the same number of fractional bits as
549 // its corresponding signed type.
550 PaddingOnUnsignedFixedPoint |= Opts.PaddingOnUnsignedFixedPoint;
551 CheckFixedPointBits();
552
553 if (Opts.ProtectParens && !checkArithmeticFenceSupported()) {
554 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "-fprotect-parens";
555 Opts.ProtectParens = false;
556 }
557
558 if (Opts.MaxBitIntWidth)
559 MaxBitIntWidth = static_cast<unsigned>(Opts.MaxBitIntWidth);
560
561 if (Opts.FakeAddressSpaceMap)
562 AddrSpaceMap = &FakeAddrSpaceMap;
563
564 // Check if it's CUDA device compilation; ensure layout consistency with host.
565 if (Opts.CUDA && Opts.CUDAIsDevice && Aux && !HasMicrosoftRecordLayout)
566 HasMicrosoftRecordLayout = Aux->getCXXABI().isMicrosoft();
567}
568
569bool TargetInfo::initFeatureMap(
570 llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
571 const std::vector<std::string> &FeatureVec) const {
572 for (StringRef Name : FeatureVec) {
573 if (Name.empty())
574 continue;
575 // Apply the feature via the target.
576 if (Name[0] != '+' && Name[0] != '-')
577 Diags.Report(DiagID: diag::warn_fe_backend_invalid_feature_flag) << Name;
578 else
579 setFeatureEnabled(Features, Name: Name.substr(Start: 1), Enabled: Name[0] == '+');
580 }
581 return true;
582}
583
584ParsedTargetAttr TargetInfo::parseTargetAttr(StringRef Features) const {
585 ParsedTargetAttr Ret;
586 if (Features == "default")
587 return Ret;
588 SmallVector<StringRef, 1> AttrFeatures;
589 Features.split(A&: AttrFeatures, Separator: ",");
590
591 // Grab the various features and prepend a "+" to turn on the feature to
592 // the backend and add them to our existing set of features.
593 for (auto &Feature : AttrFeatures) {
594 // Go ahead and trim whitespace rather than either erroring or
595 // accepting it weirdly.
596 Feature = Feature.trim();
597
598 // TODO: Support the fpmath option. It will require checking
599 // overall feature validity for the function with the rest of the
600 // attributes on the function.
601 if (Feature.starts_with(Prefix: "fpmath="))
602 continue;
603
604 if (Feature.starts_with(Prefix: "branch-protection=")) {
605 Ret.BranchProtection = Feature.split(Separator: '=').second.trim();
606 continue;
607 }
608
609 // While we're here iterating check for a different target cpu.
610 if (Feature.starts_with(Prefix: "arch=")) {
611 if (!Ret.CPU.empty())
612 Ret.Duplicate = "arch=";
613 else
614 Ret.CPU = Feature.split(Separator: "=").second.trim();
615 } else if (Feature.starts_with(Prefix: "tune=")) {
616 if (!Ret.Tune.empty())
617 Ret.Duplicate = "tune=";
618 else
619 Ret.Tune = Feature.split(Separator: "=").second.trim();
620 } else if (Feature.starts_with(Prefix: "no-"))
621 Ret.Features.push_back(x: "-" + Feature.split(Separator: "-").second.str());
622 else
623 Ret.Features.push_back(x: "+" + Feature.str());
624 }
625 return Ret;
626}
627
628TargetInfo::CallingConvKind
629TargetInfo::getCallingConvKind(bool ClangABICompat4) const {
630 if (getCXXABI() != TargetCXXABI::Microsoft &&
631 (ClangABICompat4 || getTriple().isPS4()))
632 return CCK_ClangABI4OrPS4;
633 return CCK_Default;
634}
635
636VTableUniquenessKind TargetInfo::getVTableUniqueness() const {
637 return VTableUniquenessKind::AlwaysUnique;
638}
639
640bool TargetInfo::callGlobalDeleteInDeletingDtor(
641 const LangOptions &LangOpts) const {
642 if (getCXXABI() == TargetCXXABI::Microsoft &&
643 !LangOpts.isCompatibleWith(Version: LangOptions::ClangABI::Ver21))
644 return true;
645 return false;
646}
647
648bool TargetInfo::emitVectorDeletingDtors(const LangOptions &LangOpts) const {
649 if (getCXXABI() == TargetCXXABI::Microsoft &&
650 !LangOpts.isCompatibleWith(Version: LangOptions::ClangABI::Ver21))
651 return true;
652 return false;
653}
654
655bool TargetInfo::areDefaultedSMFStillPOD(const LangOptions &LangOpts) const {
656 return !LangOpts.isCompatibleWith(Version: LangOptions::ClangABI::Ver15);
657}
658
659void TargetInfo::setDependentOpenCLOpts() {
660 auto &Opts = getSupportedOpenCLOpts();
661 if (!hasFeatureEnabled(Features: Opts, Name: "cl_khr_fp64") ||
662 !hasFeatureEnabled(Features: Opts, Name: "__opencl_c_fp64")) {
663 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_global_atomic_add", Enabled: false);
664 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_local_atomic_add", Enabled: false);
665 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_global_atomic_min_max", Enabled: false);
666 setFeatureEnabled(Features&: Opts, Name: "__opencl_c_ext_fp64_local_atomic_min_max", Enabled: false);
667 }
668}
669
670LangAS TargetInfo::getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const {
671 switch (TK) {
672 case OCLTK_Image:
673 case OCLTK_Pipe:
674 return LangAS::opencl_global;
675
676 case OCLTK_Sampler:
677 return LangAS::opencl_constant;
678
679 default:
680 return LangAS::Default;
681 }
682}
683
684//===----------------------------------------------------------------------===//
685
686
687static StringRef removeGCCRegisterPrefix(StringRef Name) {
688 if (Name[0] == '%' || Name[0] == '#')
689 Name = Name.substr(Start: 1);
690
691 return Name;
692}
693
694/// isValidClobber - Returns whether the passed in string is
695/// a valid clobber in an inline asm statement. This is used by
696/// Sema.
697bool TargetInfo::isValidClobber(StringRef Name) const {
698 return (isValidGCCRegisterName(Name) || Name == "memory" || Name == "cc" ||
699 Name == "unwind");
700}
701
702/// isValidGCCRegisterName - Returns whether the passed in string
703/// is a valid register name according to GCC. This is used by Sema for
704/// inline asm statements.
705bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
706 if (Name.empty())
707 return false;
708
709 // Get rid of any register prefix.
710 Name = removeGCCRegisterPrefix(Name);
711 if (Name.empty())
712 return false;
713
714 ArrayRef<const char *> Names = getGCCRegNames();
715
716 // If we have a number it maps to an entry in the register name array.
717 if (isDigit(c: Name[0])) {
718 unsigned n;
719 if (!Name.getAsInteger(Radix: 0, Result&: n))
720 return n < Names.size();
721 }
722
723 // Check register names.
724 if (llvm::is_contained(Range&: Names, Element: Name))
725 return true;
726
727 // Check any additional names that we have.
728 for (const AddlRegName &ARN : getGCCAddlRegNames())
729 for (const char *AN : ARN.Names) {
730 if (!AN)
731 break;
732 // Make sure the register that the additional name is for is within
733 // the bounds of the register names from above.
734 if (AN == Name && ARN.RegNum < Names.size())
735 return true;
736 }
737
738 // Now check aliases.
739 for (const GCCRegAlias &GRA : getGCCRegAliases())
740 for (const char *A : GRA.Aliases) {
741 if (!A)
742 break;
743 if (A == Name)
744 return true;
745 }
746
747 return false;
748}
749
750StringRef TargetInfo::getNormalizedGCCRegisterName(StringRef Name,
751 bool ReturnCanonical) const {
752 assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
753
754 // Get rid of any register prefix.
755 Name = removeGCCRegisterPrefix(Name);
756
757 ArrayRef<const char *> Names = getGCCRegNames();
758
759 // First, check if we have a number.
760 if (isDigit(c: Name[0])) {
761 unsigned n;
762 if (!Name.getAsInteger(Radix: 0, Result&: n)) {
763 assert(n < Names.size() && "Out of bounds register number!");
764 return Names[n];
765 }
766 }
767
768 // Check any additional names that we have.
769 for (const AddlRegName &ARN : getGCCAddlRegNames())
770 for (const char *AN : ARN.Names) {
771 if (!AN)
772 break;
773 // Make sure the register that the additional name is for is within
774 // the bounds of the register names from above.
775 if (AN == Name && ARN.RegNum < Names.size())
776 return ReturnCanonical ? Names[ARN.RegNum] : Name;
777 }
778
779 // Now check aliases.
780 for (const GCCRegAlias &RA : getGCCRegAliases())
781 for (const char *A : RA.Aliases) {
782 if (!A)
783 break;
784 if (A == Name)
785 return RA.Register;
786 }
787
788 return Name;
789}
790
791bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
792 const char *Name = Info.getConstraintStr().c_str();
793 // An output constraint must start with '=' or '+'
794 if (*Name != '=' && *Name != '+')
795 return false;
796
797 if (*Name == '+')
798 Info.setIsReadWrite();
799
800 Name++;
801 while (*Name) {
802 switch (*Name) {
803 default:
804 if (!validateAsmConstraint(Name, info&: Info)) {
805 // FIXME: We temporarily return false
806 // so we can add more constraints as we hit it.
807 // Eventually, an unknown constraint should just be treated as 'g'.
808 return false;
809 }
810 break;
811 case '&': // early clobber.
812 Info.setEarlyClobber();
813 break;
814 case '%': // commutative.
815 // FIXME: Check that there is a another register after this one.
816 break;
817 case 'r': // general register.
818 Info.setAllowsRegister();
819 break;
820 case 'm': // memory operand.
821 case 'o': // offsetable memory operand.
822 case 'V': // non-offsetable memory operand.
823 case '<': // autodecrement memory operand.
824 case '>': // autoincrement memory operand.
825 Info.setAllowsMemory();
826 break;
827 case 'g': // general register, memory operand or immediate integer.
828 case 'X': // any operand.
829 Info.setAllowsRegister();
830 Info.setAllowsMemory();
831 break;
832 case ',': // multiple alternative constraint. Pass it.
833 // Handle additional optional '=' or '+' modifiers.
834 if (Name[1] == '=' || Name[1] == '+')
835 Name++;
836 break;
837 case '#': // Ignore as constraint.
838 while (Name[1] && Name[1] != ',')
839 Name++;
840 break;
841 case '?': // Disparage slightly code.
842 case '!': // Disparage severely.
843 case '*': // Ignore for choosing register preferences.
844 case 'i': // Ignore i,n,E,F as output constraints (match from the other
845 // chars)
846 case 'n':
847 case 'E':
848 case 'F':
849 break; // Pass them.
850 }
851
852 Name++;
853 }
854
855 // Early clobber with a read-write constraint which doesn't permit registers
856 // is invalid.
857 if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister())
858 return false;
859
860 // If a constraint allows neither memory nor register operands it contains
861 // only modifiers. Reject it.
862 return Info.allowsMemory() || Info.allowsRegister();
863}
864
865bool TargetInfo::resolveSymbolicName(const char *&Name,
866 ArrayRef<ConstraintInfo> OutputConstraints,
867 unsigned &Index) const {
868 assert(*Name == '[' && "Symbolic name did not start with '['");
869 Name++;
870 const char *Start = Name;
871 while (*Name && *Name != ']')
872 Name++;
873
874 if (!*Name) {
875 // Missing ']'
876 return false;
877 }
878
879 std::string SymbolicName(Start, Name - Start);
880
881 for (Index = 0; Index != OutputConstraints.size(); ++Index)
882 if (SymbolicName == OutputConstraints[Index].getName())
883 return true;
884
885 return false;
886}
887
888bool TargetInfo::validateInputConstraint(
889 MutableArrayRef<ConstraintInfo> OutputConstraints,
890 ConstraintInfo &Info) const {
891 const char *Name = Info.ConstraintStr.c_str();
892
893 if (!*Name)
894 return false;
895
896 while (*Name) {
897 switch (*Name) {
898 default:
899 // Check if we have a matching constraint
900 if (*Name >= '0' && *Name <= '9') {
901 const char *DigitStart = Name;
902 while (Name[1] >= '0' && Name[1] <= '9')
903 Name++;
904 const char *DigitEnd = Name;
905 unsigned i;
906 if (StringRef(DigitStart, DigitEnd - DigitStart + 1)
907 .getAsInteger(Radix: 10, Result&: i))
908 return false;
909
910 // Check if matching constraint is out of bounds.
911 if (i >= OutputConstraints.size()) return false;
912
913 // A number must refer to an output only operand.
914 if (OutputConstraints[i].isReadWrite())
915 return false;
916
917 // If the constraint is already tied, it must be tied to the
918 // same operand referenced to by the number.
919 if (Info.hasTiedOperand() && Info.getTiedOperand() != i)
920 return false;
921
922 // The constraint should have the same info as the respective
923 // output constraint.
924 Info.setTiedOperand(N: i, Output&: OutputConstraints[i]);
925 } else if (!validateAsmConstraint(Name, info&: Info)) {
926 // FIXME: This error return is in place temporarily so we can
927 // add more constraints as we hit it. Eventually, an unknown
928 // constraint should just be treated as 'g'.
929 return false;
930 }
931 break;
932 case '[': {
933 unsigned Index = 0;
934 if (!resolveSymbolicName(Name, OutputConstraints, Index))
935 return false;
936
937 // If the constraint is already tied, it must be tied to the
938 // same operand referenced to by the number.
939 if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
940 return false;
941
942 // A number must refer to an output only operand.
943 if (OutputConstraints[Index].isReadWrite())
944 return false;
945
946 Info.setTiedOperand(N: Index, Output&: OutputConstraints[Index]);
947 break;
948 }
949 case '%': // commutative
950 // FIXME: Fail if % is used with the last operand.
951 break;
952 case 'i': // immediate integer.
953 break;
954 case 'n': // immediate integer with a known value.
955 Info.setRequiresImmediate();
956 break;
957 case 'I': // Various constant constraints with target-specific meanings.
958 case 'J':
959 case 'K':
960 case 'L':
961 case 'M':
962 case 'N':
963 case 'O':
964 case 'P':
965 if (!validateAsmConstraint(Name, info&: Info))
966 return false;
967 break;
968 case 'r': // general register.
969 Info.setAllowsRegister();
970 break;
971 case 'm': // memory operand.
972 case 'o': // offsettable memory operand.
973 case 'V': // non-offsettable memory operand.
974 case '<': // autodecrement memory operand.
975 case '>': // autoincrement memory operand.
976 Info.setAllowsMemory();
977 break;
978 case 'g': // general register, memory operand or immediate integer.
979 case 'X': // any operand.
980 Info.setAllowsRegister();
981 Info.setAllowsMemory();
982 break;
983 case 'E': // immediate floating point.
984 case 'F': // immediate floating point.
985 case 'p': // address operand.
986 break;
987 case ',': // multiple alternative constraint. Ignore comma.
988 break;
989 case '#': // Ignore as constraint.
990 while (Name[1] && Name[1] != ',')
991 Name++;
992 break;
993 case '?': // Disparage slightly code.
994 case '!': // Disparage severely.
995 case '*': // Ignore for choosing register preferences.
996 break; // Pass them.
997 }
998
999 Name++;
1000 }
1001
1002 return true;
1003}
1004
1005bool TargetInfo::validatePointerAuthKey(const llvm::APSInt &value) const {
1006 return false;
1007}
1008
1009void TargetInfo::CheckFixedPointBits() const {
1010 // Check that the number of fractional and integral bits (and maybe sign) can
1011 // fit into the bits given for a fixed point type.
1012 assert(ShortAccumScale + getShortAccumIBits() + 1 <= ShortAccumWidth);
1013 assert(AccumScale + getAccumIBits() + 1 <= AccumWidth);
1014 assert(LongAccumScale + getLongAccumIBits() + 1 <= LongAccumWidth);
1015 assert(getUnsignedShortAccumScale() + getUnsignedShortAccumIBits() <=
1016 ShortAccumWidth);
1017 assert(getUnsignedAccumScale() + getUnsignedAccumIBits() <= AccumWidth);
1018 assert(getUnsignedLongAccumScale() + getUnsignedLongAccumIBits() <=
1019 LongAccumWidth);
1020
1021 assert(getShortFractScale() + 1 <= ShortFractWidth);
1022 assert(getFractScale() + 1 <= FractWidth);
1023 assert(getLongFractScale() + 1 <= LongFractWidth);
1024 assert(getUnsignedShortFractScale() <= ShortFractWidth);
1025 assert(getUnsignedFractScale() <= FractWidth);
1026 assert(getUnsignedLongFractScale() <= LongFractWidth);
1027
1028 // Each unsigned fract type has either the same number of fractional bits
1029 // as, or one more fractional bit than, its corresponding signed fract type.
1030 assert(getShortFractScale() == getUnsignedShortFractScale() ||
1031 getShortFractScale() == getUnsignedShortFractScale() - 1);
1032 assert(getFractScale() == getUnsignedFractScale() ||
1033 getFractScale() == getUnsignedFractScale() - 1);
1034 assert(getLongFractScale() == getUnsignedLongFractScale() ||
1035 getLongFractScale() == getUnsignedLongFractScale() - 1);
1036
1037 // When arranged in order of increasing rank (see 6.3.1.3a), the number of
1038 // fractional bits is nondecreasing for each of the following sets of
1039 // fixed-point types:
1040 // - signed fract types
1041 // - unsigned fract types
1042 // - signed accum types
1043 // - unsigned accum types.
1044 assert(getLongFractScale() >= getFractScale() &&
1045 getFractScale() >= getShortFractScale());
1046 assert(getUnsignedLongFractScale() >= getUnsignedFractScale() &&
1047 getUnsignedFractScale() >= getUnsignedShortFractScale());
1048 assert(LongAccumScale >= AccumScale && AccumScale >= ShortAccumScale);
1049 assert(getUnsignedLongAccumScale() >= getUnsignedAccumScale() &&
1050 getUnsignedAccumScale() >= getUnsignedShortAccumScale());
1051
1052 // When arranged in order of increasing rank (see 6.3.1.3a), the number of
1053 // integral bits is nondecreasing for each of the following sets of
1054 // fixed-point types:
1055 // - signed accum types
1056 // - unsigned accum types
1057 assert(getLongAccumIBits() >= getAccumIBits() &&
1058 getAccumIBits() >= getShortAccumIBits());
1059 assert(getUnsignedLongAccumIBits() >= getUnsignedAccumIBits() &&
1060 getUnsignedAccumIBits() >= getUnsignedShortAccumIBits());
1061
1062 // Each signed accum type has at least as many integral bits as its
1063 // corresponding unsigned accum type.
1064 assert(getShortAccumIBits() >= getUnsignedShortAccumIBits());
1065 assert(getAccumIBits() >= getUnsignedAccumIBits());
1066 assert(getLongAccumIBits() >= getUnsignedLongAccumIBits());
1067}
1068
1069void TargetInfo::copyAuxTarget(const TargetInfo *Aux) {
1070 auto *Target = static_cast<TransferrableTargetInfo*>(this);
1071 auto *Src = static_cast<const TransferrableTargetInfo*>(Aux);
1072 *Target = *Src;
1073}
1074
1075std::string
1076TargetInfo::simplifyConstraint(StringRef Constraint,
1077 SmallVectorImpl<ConstraintInfo> *OutCons) const {
1078 std::string Result;
1079
1080 // Stop at '\0' to match the old behavior.
1081 Constraint = Constraint.split(Separator: '\0').first;
1082
1083 for (const char *I = Constraint.begin(), *E = Constraint.end(); I < E; I++) {
1084 switch (*I) {
1085 default:
1086 Result += convertConstraint(Constraint&: I);
1087 break;
1088 // Ignore these
1089 case '*':
1090 case '?':
1091 case '!':
1092 case '=': // Will see this and the following in mult-alt constraints.
1093 case '+':
1094 break;
1095 case '#': // Ignore the rest of the constraint alternative.
1096 while (I + 1 != E && I[1] != ',')
1097 I++;
1098 break;
1099 case '&':
1100 case '%':
1101 Result += *I;
1102 while (I + 1 != E && I[1] == *I)
1103 I++;
1104 break;
1105 case ',':
1106 Result += "|";
1107 break;
1108 case 'g':
1109 Result += "imr";
1110 break;
1111 case '[': {
1112 assert(OutCons &&
1113 "Must pass output names to constraints with a symbolic name");
1114 unsigned Index;
1115 bool ResolveResult = resolveSymbolicName(Name&: I, OutputConstraints: *OutCons, Index);
1116 assert(ResolveResult && "Could not resolve symbolic name");
1117 (void)ResolveResult;
1118 Result += llvm::utostr(X: Index);
1119 break;
1120 }
1121 }
1122 }
1123 return Result;
1124}
1125
1126unsigned clang::Microsoft64BitMinGlobalAlign(uint64_t TypeSize) {
1127 // MSVC does size based alignment for arm64 based on alignment section in
1128 // below document. Replicate that to keep alignment consistent with object
1129 // files compiled by MSVC.
1130 // https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions
1131 // The same is done for x64, but not documented.
1132
1133 if (TypeSize >= 512) // TypeSize >= 64 bytes
1134 return 128; // align type at least 16 bytes
1135 if (TypeSize >= 64) // TypeSize >= 8 bytes
1136 return 64; // align type at least 8 bytes
1137 if (TypeSize >= 16) // TypeSize >= 2 bytes
1138 return 32; // align type at least 4 bytes
1139
1140 return 0;
1141}
1142