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