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