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