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