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

source code of clang/lib/Basic/TargetInfo.cpp