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