xref: /freebsd/contrib/llvm-project/clang/lib/Sema/DeclSpec.cpp (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 //===--- DeclSpec.cpp - Declaration Specifier Semantic Analysis -----------===//
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 semantic analysis for declaration specifiers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/DeclSpec.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/LocInfoType.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Sema/ParsedTemplate.h"
23 #include "clang/Sema/Sema.h"
24 #include "clang/Sema/SemaDiagnostic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include <cstring>
28 using namespace clang;
29 
30 
31 void UnqualifiedId::setTemplateId(TemplateIdAnnotation *TemplateId) {
32   assert(TemplateId && "NULL template-id annotation?");
33   assert(!TemplateId->isInvalid() &&
34          "should not convert invalid template-ids to unqualified-ids");
35 
36   Kind = UnqualifiedIdKind::IK_TemplateId;
37   this->TemplateId = TemplateId;
38   StartLocation = TemplateId->TemplateNameLoc;
39   EndLocation = TemplateId->RAngleLoc;
40 }
41 
42 void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) {
43   assert(TemplateId && "NULL template-id annotation?");
44   assert(!TemplateId->isInvalid() &&
45          "should not convert invalid template-ids to unqualified-ids");
46 
47   Kind = UnqualifiedIdKind::IK_ConstructorTemplateId;
48   this->TemplateId = TemplateId;
49   StartLocation = TemplateId->TemplateNameLoc;
50   EndLocation = TemplateId->RAngleLoc;
51 }
52 
53 void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc,
54                           TypeLoc TL, SourceLocation ColonColonLoc) {
55   Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc);
56   if (Range.getBegin().isInvalid())
57     Range.setBegin(TL.getBeginLoc());
58   Range.setEnd(ColonColonLoc);
59 
60   assert(Range == Builder.getSourceRange() &&
61          "NestedNameSpecifierLoc range computation incorrect");
62 }
63 
64 void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier,
65                           SourceLocation IdentifierLoc,
66                           SourceLocation ColonColonLoc) {
67   Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc);
68 
69   if (Range.getBegin().isInvalid())
70     Range.setBegin(IdentifierLoc);
71   Range.setEnd(ColonColonLoc);
72 
73   assert(Range == Builder.getSourceRange() &&
74          "NestedNameSpecifierLoc range computation incorrect");
75 }
76 
77 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace,
78                           SourceLocation NamespaceLoc,
79                           SourceLocation ColonColonLoc) {
80   Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc);
81 
82   if (Range.getBegin().isInvalid())
83     Range.setBegin(NamespaceLoc);
84   Range.setEnd(ColonColonLoc);
85 
86   assert(Range == Builder.getSourceRange() &&
87          "NestedNameSpecifierLoc range computation incorrect");
88 }
89 
90 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
91                           SourceLocation AliasLoc,
92                           SourceLocation ColonColonLoc) {
93   Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc);
94 
95   if (Range.getBegin().isInvalid())
96     Range.setBegin(AliasLoc);
97   Range.setEnd(ColonColonLoc);
98 
99   assert(Range == Builder.getSourceRange() &&
100          "NestedNameSpecifierLoc range computation incorrect");
101 }
102 
103 void CXXScopeSpec::MakeGlobal(ASTContext &Context,
104                               SourceLocation ColonColonLoc) {
105   Builder.MakeGlobal(Context, ColonColonLoc);
106 
107   Range = SourceRange(ColonColonLoc);
108 
109   assert(Range == Builder.getSourceRange() &&
110          "NestedNameSpecifierLoc range computation incorrect");
111 }
112 
113 void CXXScopeSpec::MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
114                              SourceLocation SuperLoc,
115                              SourceLocation ColonColonLoc) {
116   Builder.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
117 
118   Range.setBegin(SuperLoc);
119   Range.setEnd(ColonColonLoc);
120 
121   assert(Range == Builder.getSourceRange() &&
122   "NestedNameSpecifierLoc range computation incorrect");
123 }
124 
125 void CXXScopeSpec::MakeTrivial(ASTContext &Context,
126                                NestedNameSpecifier *Qualifier, SourceRange R) {
127   Builder.MakeTrivial(Context, Qualifier, R);
128   Range = R;
129 }
130 
131 void CXXScopeSpec::Adopt(NestedNameSpecifierLoc Other) {
132   if (!Other) {
133     Range = SourceRange();
134     Builder.Clear();
135     return;
136   }
137 
138   Range = Other.getSourceRange();
139   Builder.Adopt(Other);
140   assert(Range == Builder.getSourceRange() &&
141          "NestedNameSpecifierLoc range computation incorrect");
142 }
143 
144 SourceLocation CXXScopeSpec::getLastQualifierNameLoc() const {
145   if (!Builder.getRepresentation())
146     return SourceLocation();
147   return Builder.getTemporary().getLocalBeginLoc();
148 }
149 
150 NestedNameSpecifierLoc
151 CXXScopeSpec::getWithLocInContext(ASTContext &Context) const {
152   if (!Builder.getRepresentation())
153     return NestedNameSpecifierLoc();
154 
155   return Builder.getWithLocInContext(Context);
156 }
157 
158 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
159 /// "TheDeclarator" is the declarator that this will be added to.
160 DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto,
161                                              bool isAmbiguous,
162                                              SourceLocation LParenLoc,
163                                              ParamInfo *Params,
164                                              unsigned NumParams,
165                                              SourceLocation EllipsisLoc,
166                                              SourceLocation RParenLoc,
167                                              bool RefQualifierIsLvalueRef,
168                                              SourceLocation RefQualifierLoc,
169                                              SourceLocation MutableLoc,
170                                              ExceptionSpecificationType
171                                                  ESpecType,
172                                              SourceRange ESpecRange,
173                                              ParsedType *Exceptions,
174                                              SourceRange *ExceptionRanges,
175                                              unsigned NumExceptions,
176                                              Expr *NoexceptExpr,
177                                              CachedTokens *ExceptionSpecTokens,
178                                              ArrayRef<NamedDecl*>
179                                                  DeclsInPrototype,
180                                              SourceLocation LocalRangeBegin,
181                                              SourceLocation LocalRangeEnd,
182                                              Declarator &TheDeclarator,
183                                              TypeResult TrailingReturnType,
184                                              DeclSpec *MethodQualifiers) {
185   assert(!(MethodQualifiers && MethodQualifiers->getTypeQualifiers() & DeclSpec::TQ_atomic) &&
186          "function cannot have _Atomic qualifier");
187 
188   DeclaratorChunk I;
189   I.Kind                        = Function;
190   I.Loc                         = LocalRangeBegin;
191   I.EndLoc                      = LocalRangeEnd;
192   I.Fun.hasPrototype            = hasProto;
193   I.Fun.isVariadic              = EllipsisLoc.isValid();
194   I.Fun.isAmbiguous             = isAmbiguous;
195   I.Fun.LParenLoc               = LParenLoc.getRawEncoding();
196   I.Fun.EllipsisLoc             = EllipsisLoc.getRawEncoding();
197   I.Fun.RParenLoc               = RParenLoc.getRawEncoding();
198   I.Fun.DeleteParams            = false;
199   I.Fun.NumParams               = NumParams;
200   I.Fun.Params                  = nullptr;
201   I.Fun.RefQualifierIsLValueRef = RefQualifierIsLvalueRef;
202   I.Fun.RefQualifierLoc         = RefQualifierLoc.getRawEncoding();
203   I.Fun.MutableLoc              = MutableLoc.getRawEncoding();
204   I.Fun.ExceptionSpecType       = ESpecType;
205   I.Fun.ExceptionSpecLocBeg     = ESpecRange.getBegin().getRawEncoding();
206   I.Fun.ExceptionSpecLocEnd     = ESpecRange.getEnd().getRawEncoding();
207   I.Fun.NumExceptionsOrDecls    = 0;
208   I.Fun.Exceptions              = nullptr;
209   I.Fun.NoexceptExpr            = nullptr;
210   I.Fun.HasTrailingReturnType   = TrailingReturnType.isUsable() ||
211                                   TrailingReturnType.isInvalid();
212   I.Fun.TrailingReturnType      = TrailingReturnType.get();
213   I.Fun.MethodQualifiers        = nullptr;
214   I.Fun.QualAttrFactory         = nullptr;
215 
216   if (MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
217                            MethodQualifiers->getAttributes().size())) {
218     auto &attrs = MethodQualifiers->getAttributes();
219     I.Fun.MethodQualifiers = new DeclSpec(attrs.getPool().getFactory());
220     MethodQualifiers->forEachCVRUQualifier(
221         [&](DeclSpec::TQ TypeQual, StringRef PrintName, SourceLocation SL) {
222           I.Fun.MethodQualifiers->SetTypeQual(TypeQual, SL);
223         });
224     I.Fun.MethodQualifiers->getAttributes().takeAllFrom(attrs);
225     I.Fun.MethodQualifiers->getAttributePool().takeAllFrom(attrs.getPool());
226   }
227 
228   assert(I.Fun.ExceptionSpecType == ESpecType && "bitfield overflow");
229 
230   // new[] a parameter array if needed.
231   if (NumParams) {
232     // If the 'InlineParams' in Declarator is unused and big enough, put our
233     // parameter list there (in an effort to avoid new/delete traffic).  If it
234     // is already used (consider a function returning a function pointer) or too
235     // small (function with too many parameters), go to the heap.
236     if (!TheDeclarator.InlineStorageUsed &&
237         NumParams <= llvm::array_lengthof(TheDeclarator.InlineParams)) {
238       I.Fun.Params = TheDeclarator.InlineParams;
239       new (I.Fun.Params) ParamInfo[NumParams];
240       I.Fun.DeleteParams = false;
241       TheDeclarator.InlineStorageUsed = true;
242     } else {
243       I.Fun.Params = new DeclaratorChunk::ParamInfo[NumParams];
244       I.Fun.DeleteParams = true;
245     }
246     for (unsigned i = 0; i < NumParams; i++)
247       I.Fun.Params[i] = std::move(Params[i]);
248   }
249 
250   // Check what exception specification information we should actually store.
251   switch (ESpecType) {
252   default: break; // By default, save nothing.
253   case EST_Dynamic:
254     // new[] an exception array if needed
255     if (NumExceptions) {
256       I.Fun.NumExceptionsOrDecls = NumExceptions;
257       I.Fun.Exceptions = new DeclaratorChunk::TypeAndRange[NumExceptions];
258       for (unsigned i = 0; i != NumExceptions; ++i) {
259         I.Fun.Exceptions[i].Ty = Exceptions[i];
260         I.Fun.Exceptions[i].Range = ExceptionRanges[i];
261       }
262     }
263     break;
264 
265   case EST_DependentNoexcept:
266   case EST_NoexceptFalse:
267   case EST_NoexceptTrue:
268     I.Fun.NoexceptExpr = NoexceptExpr;
269     break;
270 
271   case EST_Unparsed:
272     I.Fun.ExceptionSpecTokens = ExceptionSpecTokens;
273     break;
274   }
275 
276   if (!DeclsInPrototype.empty()) {
277     assert(ESpecType == EST_None && NumExceptions == 0 &&
278            "cannot have exception specifiers and decls in prototype");
279     I.Fun.NumExceptionsOrDecls = DeclsInPrototype.size();
280     // Copy the array of decls into stable heap storage.
281     I.Fun.DeclsInPrototype = new NamedDecl *[DeclsInPrototype.size()];
282     for (size_t J = 0; J < DeclsInPrototype.size(); ++J)
283       I.Fun.DeclsInPrototype[J] = DeclsInPrototype[J];
284   }
285 
286   return I;
287 }
288 
289 void Declarator::setDecompositionBindings(
290     SourceLocation LSquareLoc,
291     ArrayRef<DecompositionDeclarator::Binding> Bindings,
292     SourceLocation RSquareLoc) {
293   assert(!hasName() && "declarator given multiple names!");
294 
295   BindingGroup.LSquareLoc = LSquareLoc;
296   BindingGroup.RSquareLoc = RSquareLoc;
297   BindingGroup.NumBindings = Bindings.size();
298   Range.setEnd(RSquareLoc);
299 
300   // We're now past the identifier.
301   SetIdentifier(nullptr, LSquareLoc);
302   Name.EndLocation = RSquareLoc;
303 
304   // Allocate storage for bindings and stash them away.
305   if (Bindings.size()) {
306     if (!InlineStorageUsed &&
307         Bindings.size() <= llvm::array_lengthof(InlineBindings)) {
308       BindingGroup.Bindings = InlineBindings;
309       BindingGroup.DeleteBindings = false;
310       InlineStorageUsed = true;
311     } else {
312       BindingGroup.Bindings =
313           new DecompositionDeclarator::Binding[Bindings.size()];
314       BindingGroup.DeleteBindings = true;
315     }
316     std::uninitialized_copy(Bindings.begin(), Bindings.end(),
317                             BindingGroup.Bindings);
318   }
319 }
320 
321 bool Declarator::isDeclarationOfFunction() const {
322   for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
323     switch (DeclTypeInfo[i].Kind) {
324     case DeclaratorChunk::Function:
325       return true;
326     case DeclaratorChunk::Paren:
327       continue;
328     case DeclaratorChunk::Pointer:
329     case DeclaratorChunk::Reference:
330     case DeclaratorChunk::Array:
331     case DeclaratorChunk::BlockPointer:
332     case DeclaratorChunk::MemberPointer:
333     case DeclaratorChunk::Pipe:
334       return false;
335     }
336     llvm_unreachable("Invalid type chunk");
337   }
338 
339   switch (DS.getTypeSpecType()) {
340     case TST_atomic:
341     case TST_auto:
342     case TST_auto_type:
343     case TST_bool:
344     case TST_char:
345     case TST_char8:
346     case TST_char16:
347     case TST_char32:
348     case TST_class:
349     case TST_decimal128:
350     case TST_decimal32:
351     case TST_decimal64:
352     case TST_double:
353     case TST_Accum:
354     case TST_Fract:
355     case TST_Float16:
356     case TST_float128:
357     case TST_enum:
358     case TST_error:
359     case TST_float:
360     case TST_half:
361     case TST_int:
362     case TST_int128:
363     case TST_extint:
364     case TST_struct:
365     case TST_interface:
366     case TST_union:
367     case TST_unknown_anytype:
368     case TST_unspecified:
369     case TST_void:
370     case TST_wchar:
371     case TST_BFloat16:
372 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
373 #include "clang/Basic/OpenCLImageTypes.def"
374       return false;
375 
376     case TST_decltype_auto:
377       // This must have an initializer, so can't be a function declaration,
378       // even if the initializer has function type.
379       return false;
380 
381     case TST_decltype:
382     case TST_typeofExpr:
383       if (Expr *E = DS.getRepAsExpr())
384         return E->getType()->isFunctionType();
385       return false;
386 
387     case TST_underlyingType:
388     case TST_typename:
389     case TST_typeofType: {
390       QualType QT = DS.getRepAsType().get();
391       if (QT.isNull())
392         return false;
393 
394       if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT))
395         QT = LIT->getType();
396 
397       if (QT.isNull())
398         return false;
399 
400       return QT->isFunctionType();
401     }
402   }
403 
404   llvm_unreachable("Invalid TypeSpecType!");
405 }
406 
407 bool Declarator::isStaticMember() {
408   assert(getContext() == DeclaratorContext::MemberContext);
409   return getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
410          (getName().Kind == UnqualifiedIdKind::IK_OperatorFunctionId &&
411           CXXMethodDecl::isStaticOverloadedOperator(
412               getName().OperatorFunctionId.Operator));
413 }
414 
415 bool Declarator::isCtorOrDtor() {
416   return (getName().getKind() == UnqualifiedIdKind::IK_ConstructorName) ||
417          (getName().getKind() == UnqualifiedIdKind::IK_DestructorName);
418 }
419 
420 void DeclSpec::forEachCVRUQualifier(
421     llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle) {
422   if (TypeQualifiers & TQ_const)
423     Handle(TQ_const, "const", TQ_constLoc);
424   if (TypeQualifiers & TQ_volatile)
425     Handle(TQ_volatile, "volatile", TQ_volatileLoc);
426   if (TypeQualifiers & TQ_restrict)
427     Handle(TQ_restrict, "restrict", TQ_restrictLoc);
428   if (TypeQualifiers & TQ_unaligned)
429     Handle(TQ_unaligned, "unaligned", TQ_unalignedLoc);
430 }
431 
432 void DeclSpec::forEachQualifier(
433     llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle) {
434   forEachCVRUQualifier(Handle);
435   // FIXME: Add code below to iterate through the attributes and call Handle.
436 }
437 
438 bool DeclSpec::hasTagDefinition() const {
439   if (!TypeSpecOwned)
440     return false;
441   return cast<TagDecl>(getRepAsDecl())->isCompleteDefinition();
442 }
443 
444 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
445 /// declaration specifier includes.
446 ///
447 unsigned DeclSpec::getParsedSpecifiers() const {
448   unsigned Res = 0;
449   if (StorageClassSpec != SCS_unspecified ||
450       ThreadStorageClassSpec != TSCS_unspecified)
451     Res |= PQ_StorageClassSpecifier;
452 
453   if (TypeQualifiers != TQ_unspecified)
454     Res |= PQ_TypeQualifier;
455 
456   if (hasTypeSpecifier())
457     Res |= PQ_TypeSpecifier;
458 
459   if (FS_inline_specified || FS_virtual_specified || hasExplicitSpecifier() ||
460       FS_noreturn_specified || FS_forceinline_specified)
461     Res |= PQ_FunctionSpecifier;
462   return Res;
463 }
464 
465 template <class T> static bool BadSpecifier(T TNew, T TPrev,
466                                             const char *&PrevSpec,
467                                             unsigned &DiagID,
468                                             bool IsExtension = true) {
469   PrevSpec = DeclSpec::getSpecifierName(TPrev);
470   if (TNew != TPrev)
471     DiagID = diag::err_invalid_decl_spec_combination;
472   else
473     DiagID = IsExtension ? diag::ext_warn_duplicate_declspec :
474                            diag::warn_duplicate_declspec;
475   return true;
476 }
477 
478 const char *DeclSpec::getSpecifierName(DeclSpec::SCS S) {
479   switch (S) {
480   case DeclSpec::SCS_unspecified: return "unspecified";
481   case DeclSpec::SCS_typedef:     return "typedef";
482   case DeclSpec::SCS_extern:      return "extern";
483   case DeclSpec::SCS_static:      return "static";
484   case DeclSpec::SCS_auto:        return "auto";
485   case DeclSpec::SCS_register:    return "register";
486   case DeclSpec::SCS_private_extern: return "__private_extern__";
487   case DeclSpec::SCS_mutable:     return "mutable";
488   }
489   llvm_unreachable("Unknown typespec!");
490 }
491 
492 const char *DeclSpec::getSpecifierName(DeclSpec::TSCS S) {
493   switch (S) {
494   case DeclSpec::TSCS_unspecified:   return "unspecified";
495   case DeclSpec::TSCS___thread:      return "__thread";
496   case DeclSpec::TSCS_thread_local:  return "thread_local";
497   case DeclSpec::TSCS__Thread_local: return "_Thread_local";
498   }
499   llvm_unreachable("Unknown typespec!");
500 }
501 
502 const char *DeclSpec::getSpecifierName(TSW W) {
503   switch (W) {
504   case TSW_unspecified: return "unspecified";
505   case TSW_short:       return "short";
506   case TSW_long:        return "long";
507   case TSW_longlong:    return "long long";
508   }
509   llvm_unreachable("Unknown typespec!");
510 }
511 
512 const char *DeclSpec::getSpecifierName(TSC C) {
513   switch (C) {
514   case TSC_unspecified: return "unspecified";
515   case TSC_imaginary:   return "imaginary";
516   case TSC_complex:     return "complex";
517   }
518   llvm_unreachable("Unknown typespec!");
519 }
520 
521 
522 const char *DeclSpec::getSpecifierName(TSS S) {
523   switch (S) {
524   case TSS_unspecified: return "unspecified";
525   case TSS_signed:      return "signed";
526   case TSS_unsigned:    return "unsigned";
527   }
528   llvm_unreachable("Unknown typespec!");
529 }
530 
531 const char *DeclSpec::getSpecifierName(DeclSpec::TST T,
532                                        const PrintingPolicy &Policy) {
533   switch (T) {
534   case DeclSpec::TST_unspecified: return "unspecified";
535   case DeclSpec::TST_void:        return "void";
536   case DeclSpec::TST_char:        return "char";
537   case DeclSpec::TST_wchar:       return Policy.MSWChar ? "__wchar_t" : "wchar_t";
538   case DeclSpec::TST_char8:       return "char8_t";
539   case DeclSpec::TST_char16:      return "char16_t";
540   case DeclSpec::TST_char32:      return "char32_t";
541   case DeclSpec::TST_int:         return "int";
542   case DeclSpec::TST_int128:      return "__int128";
543   case DeclSpec::TST_extint:      return "_ExtInt";
544   case DeclSpec::TST_half:        return "half";
545   case DeclSpec::TST_float:       return "float";
546   case DeclSpec::TST_double:      return "double";
547   case DeclSpec::TST_accum:       return "_Accum";
548   case DeclSpec::TST_fract:       return "_Fract";
549   case DeclSpec::TST_float16:     return "_Float16";
550   case DeclSpec::TST_float128:    return "__float128";
551   case DeclSpec::TST_bool:        return Policy.Bool ? "bool" : "_Bool";
552   case DeclSpec::TST_decimal32:   return "_Decimal32";
553   case DeclSpec::TST_decimal64:   return "_Decimal64";
554   case DeclSpec::TST_decimal128:  return "_Decimal128";
555   case DeclSpec::TST_enum:        return "enum";
556   case DeclSpec::TST_class:       return "class";
557   case DeclSpec::TST_union:       return "union";
558   case DeclSpec::TST_struct:      return "struct";
559   case DeclSpec::TST_interface:   return "__interface";
560   case DeclSpec::TST_typename:    return "type-name";
561   case DeclSpec::TST_typeofType:
562   case DeclSpec::TST_typeofExpr:  return "typeof";
563   case DeclSpec::TST_auto:        return "auto";
564   case DeclSpec::TST_auto_type:   return "__auto_type";
565   case DeclSpec::TST_decltype:    return "(decltype)";
566   case DeclSpec::TST_decltype_auto: return "decltype(auto)";
567   case DeclSpec::TST_underlyingType: return "__underlying_type";
568   case DeclSpec::TST_unknown_anytype: return "__unknown_anytype";
569   case DeclSpec::TST_atomic: return "_Atomic";
570   case DeclSpec::TST_BFloat16: return "__bf16";
571 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
572   case DeclSpec::TST_##ImgType##_t: \
573     return #ImgType "_t";
574 #include "clang/Basic/OpenCLImageTypes.def"
575   case DeclSpec::TST_error:       return "(error)";
576   }
577   llvm_unreachable("Unknown typespec!");
578 }
579 
580 const char *DeclSpec::getSpecifierName(ConstexprSpecKind C) {
581   switch (C) {
582   case CSK_unspecified: return "unspecified";
583   case CSK_constexpr:   return "constexpr";
584   case CSK_consteval:   return "consteval";
585   case CSK_constinit:   return "constinit";
586   }
587   llvm_unreachable("Unknown ConstexprSpecKind");
588 }
589 
590 const char *DeclSpec::getSpecifierName(TQ T) {
591   switch (T) {
592   case DeclSpec::TQ_unspecified: return "unspecified";
593   case DeclSpec::TQ_const:       return "const";
594   case DeclSpec::TQ_restrict:    return "restrict";
595   case DeclSpec::TQ_volatile:    return "volatile";
596   case DeclSpec::TQ_atomic:      return "_Atomic";
597   case DeclSpec::TQ_unaligned:   return "__unaligned";
598   }
599   llvm_unreachable("Unknown typespec!");
600 }
601 
602 bool DeclSpec::SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
603                                    const char *&PrevSpec,
604                                    unsigned &DiagID,
605                                    const PrintingPolicy &Policy) {
606   // OpenCL v1.1 s6.8g: "The extern, static, auto and register storage-class
607   // specifiers are not supported.
608   // It seems sensible to prohibit private_extern too
609   // The cl_clang_storage_class_specifiers extension enables support for
610   // these storage-class specifiers.
611   // OpenCL v1.2 s6.8 changes this to "The auto and register storage-class
612   // specifiers are not supported."
613   if (S.getLangOpts().OpenCL &&
614       !S.getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers")) {
615     switch (SC) {
616     case SCS_extern:
617     case SCS_private_extern:
618     case SCS_static:
619       if (S.getLangOpts().OpenCLVersion < 120 &&
620           !S.getLangOpts().OpenCLCPlusPlus) {
621         DiagID = diag::err_opencl_unknown_type_specifier;
622         PrevSpec = getSpecifierName(SC);
623         return true;
624       }
625       break;
626     case SCS_auto:
627     case SCS_register:
628       DiagID   = diag::err_opencl_unknown_type_specifier;
629       PrevSpec = getSpecifierName(SC);
630       return true;
631     default:
632       break;
633     }
634   }
635 
636   if (StorageClassSpec != SCS_unspecified) {
637     // Maybe this is an attempt to use C++11 'auto' outside of C++11 mode.
638     bool isInvalid = true;
639     if (TypeSpecType == TST_unspecified && S.getLangOpts().CPlusPlus) {
640       if (SC == SCS_auto)
641         return SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID, Policy);
642       if (StorageClassSpec == SCS_auto) {
643         isInvalid = SetTypeSpecType(TST_auto, StorageClassSpecLoc,
644                                     PrevSpec, DiagID, Policy);
645         assert(!isInvalid && "auto SCS -> TST recovery failed");
646       }
647     }
648 
649     // Changing storage class is allowed only if the previous one
650     // was the 'extern' that is part of a linkage specification and
651     // the new storage class is 'typedef'.
652     if (isInvalid &&
653         !(SCS_extern_in_linkage_spec &&
654           StorageClassSpec == SCS_extern &&
655           SC == SCS_typedef))
656       return BadSpecifier(SC, (SCS)StorageClassSpec, PrevSpec, DiagID);
657   }
658   StorageClassSpec = SC;
659   StorageClassSpecLoc = Loc;
660   assert((unsigned)SC == StorageClassSpec && "SCS constants overflow bitfield");
661   return false;
662 }
663 
664 bool DeclSpec::SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
665                                          const char *&PrevSpec,
666                                          unsigned &DiagID) {
667   if (ThreadStorageClassSpec != TSCS_unspecified)
668     return BadSpecifier(TSC, (TSCS)ThreadStorageClassSpec, PrevSpec, DiagID);
669 
670   ThreadStorageClassSpec = TSC;
671   ThreadStorageClassSpecLoc = Loc;
672   return false;
673 }
674 
675 /// These methods set the specified attribute of the DeclSpec, but return true
676 /// and ignore the request if invalid (e.g. "extern" then "auto" is
677 /// specified).
678 bool DeclSpec::SetTypeSpecWidth(TSW W, SourceLocation Loc,
679                                 const char *&PrevSpec,
680                                 unsigned &DiagID,
681                                 const PrintingPolicy &Policy) {
682   // Overwrite TSWRange.Begin only if TypeSpecWidth was unspecified, so that
683   // for 'long long' we will keep the source location of the first 'long'.
684   if (TypeSpecWidth == TSW_unspecified)
685     TSWRange.setBegin(Loc);
686   // Allow turning long -> long long.
687   else if (W != TSW_longlong || TypeSpecWidth != TSW_long)
688     return BadSpecifier(W, (TSW)TypeSpecWidth, PrevSpec, DiagID);
689   TypeSpecWidth = W;
690   // Remember location of the last 'long'
691   TSWRange.setEnd(Loc);
692   return false;
693 }
694 
695 bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc,
696                                   const char *&PrevSpec,
697                                   unsigned &DiagID) {
698   if (TypeSpecComplex != TSC_unspecified)
699     return BadSpecifier(C, (TSC)TypeSpecComplex, PrevSpec, DiagID);
700   TypeSpecComplex = C;
701   TSCLoc = Loc;
702   return false;
703 }
704 
705 bool DeclSpec::SetTypeSpecSign(TSS S, SourceLocation Loc,
706                                const char *&PrevSpec,
707                                unsigned &DiagID) {
708   if (TypeSpecSign != TSS_unspecified)
709     return BadSpecifier(S, (TSS)TypeSpecSign, PrevSpec, DiagID);
710   TypeSpecSign = S;
711   TSSLoc = Loc;
712   return false;
713 }
714 
715 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
716                                const char *&PrevSpec,
717                                unsigned &DiagID,
718                                ParsedType Rep,
719                                const PrintingPolicy &Policy) {
720   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Policy);
721 }
722 
723 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
724                                SourceLocation TagNameLoc,
725                                const char *&PrevSpec,
726                                unsigned &DiagID,
727                                ParsedType Rep,
728                                const PrintingPolicy &Policy) {
729   assert(isTypeRep(T) && "T does not store a type");
730   assert(Rep && "no type provided!");
731   if (TypeSpecType == TST_error)
732     return false;
733   if (TypeSpecType != TST_unspecified) {
734     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
735     DiagID = diag::err_invalid_decl_spec_combination;
736     return true;
737   }
738   TypeSpecType = T;
739   TypeRep = Rep;
740   TSTLoc = TagKwLoc;
741   TSTNameLoc = TagNameLoc;
742   TypeSpecOwned = false;
743   return false;
744 }
745 
746 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
747                                const char *&PrevSpec,
748                                unsigned &DiagID,
749                                Expr *Rep,
750                                const PrintingPolicy &Policy) {
751   assert(isExprRep(T) && "T does not store an expr");
752   assert(Rep && "no expression provided!");
753   if (TypeSpecType == TST_error)
754     return false;
755   if (TypeSpecType != TST_unspecified) {
756     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
757     DiagID = diag::err_invalid_decl_spec_combination;
758     return true;
759   }
760   TypeSpecType = T;
761   ExprRep = Rep;
762   TSTLoc = Loc;
763   TSTNameLoc = Loc;
764   TypeSpecOwned = false;
765   return false;
766 }
767 
768 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
769                                const char *&PrevSpec,
770                                unsigned &DiagID,
771                                Decl *Rep, bool Owned,
772                                const PrintingPolicy &Policy) {
773   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Owned, Policy);
774 }
775 
776 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
777                                SourceLocation TagNameLoc,
778                                const char *&PrevSpec,
779                                unsigned &DiagID,
780                                Decl *Rep, bool Owned,
781                                const PrintingPolicy &Policy) {
782   assert(isDeclRep(T) && "T does not store a decl");
783   // Unlike the other cases, we don't assert that we actually get a decl.
784 
785   if (TypeSpecType == TST_error)
786     return false;
787   if (TypeSpecType != TST_unspecified) {
788     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
789     DiagID = diag::err_invalid_decl_spec_combination;
790     return true;
791   }
792   TypeSpecType = T;
793   DeclRep = Rep;
794   TSTLoc = TagKwLoc;
795   TSTNameLoc = TagNameLoc;
796   TypeSpecOwned = Owned && Rep != nullptr;
797   return false;
798 }
799 
800 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
801                                unsigned &DiagID, TemplateIdAnnotation *Rep,
802                                const PrintingPolicy &Policy) {
803   assert(T == TST_auto || T == TST_decltype_auto);
804   ConstrainedAuto = true;
805   TemplateIdRep = Rep;
806   return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Policy);
807 }
808 
809 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
810                                const char *&PrevSpec,
811                                unsigned &DiagID,
812                                const PrintingPolicy &Policy) {
813   assert(!isDeclRep(T) && !isTypeRep(T) && !isExprRep(T) &&
814          "rep required for these type-spec kinds!");
815   if (TypeSpecType == TST_error)
816     return false;
817   if (TypeSpecType != TST_unspecified) {
818     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
819     DiagID = diag::err_invalid_decl_spec_combination;
820     return true;
821   }
822   TSTLoc = Loc;
823   TSTNameLoc = Loc;
824   if (TypeAltiVecVector && (T == TST_bool) && !TypeAltiVecBool) {
825     TypeAltiVecBool = true;
826     return false;
827   }
828   TypeSpecType = T;
829   TypeSpecOwned = false;
830   return false;
831 }
832 
833 bool DeclSpec::SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
834                               unsigned &DiagID) {
835   // Cannot set twice
836   if (TypeSpecSat) {
837     DiagID = diag::warn_duplicate_declspec;
838     PrevSpec = "_Sat";
839     return true;
840   }
841   TypeSpecSat = true;
842   TSSatLoc = Loc;
843   return false;
844 }
845 
846 bool DeclSpec::SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
847                           const char *&PrevSpec, unsigned &DiagID,
848                           const PrintingPolicy &Policy) {
849   if (TypeSpecType == TST_error)
850     return false;
851   if (TypeSpecType != TST_unspecified) {
852     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
853     DiagID = diag::err_invalid_vector_decl_spec_combination;
854     return true;
855   }
856   TypeAltiVecVector = isAltiVecVector;
857   AltiVecLoc = Loc;
858   return false;
859 }
860 
861 bool DeclSpec::SetTypePipe(bool isPipe, SourceLocation Loc,
862                            const char *&PrevSpec, unsigned &DiagID,
863                            const PrintingPolicy &Policy) {
864   if (TypeSpecType == TST_error)
865     return false;
866   if (TypeSpecType != TST_unspecified) {
867     PrevSpec = DeclSpec::getSpecifierName((TST)TypeSpecType, Policy);
868     DiagID = diag::err_invalid_decl_spec_combination;
869     return true;
870   }
871 
872   if (isPipe) {
873     TypeSpecPipe = TSP_pipe;
874   }
875   return false;
876 }
877 
878 bool DeclSpec::SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
879                           const char *&PrevSpec, unsigned &DiagID,
880                           const PrintingPolicy &Policy) {
881   if (TypeSpecType == TST_error)
882     return false;
883   if (!TypeAltiVecVector || TypeAltiVecPixel ||
884       (TypeSpecType != TST_unspecified)) {
885     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
886     DiagID = diag::err_invalid_pixel_decl_spec_combination;
887     return true;
888   }
889   TypeAltiVecPixel = isAltiVecPixel;
890   TSTLoc = Loc;
891   TSTNameLoc = Loc;
892   return false;
893 }
894 
895 bool DeclSpec::SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
896                                   const char *&PrevSpec, unsigned &DiagID,
897                                   const PrintingPolicy &Policy) {
898   if (TypeSpecType == TST_error)
899     return false;
900   if (!TypeAltiVecVector || TypeAltiVecBool ||
901       (TypeSpecType != TST_unspecified)) {
902     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
903     DiagID = diag::err_invalid_vector_bool_decl_spec;
904     return true;
905   }
906   TypeAltiVecBool = isAltiVecBool;
907   TSTLoc = Loc;
908   TSTNameLoc = Loc;
909   return false;
910 }
911 
912 bool DeclSpec::SetTypeSpecError() {
913   TypeSpecType = TST_error;
914   TypeSpecOwned = false;
915   TSTLoc = SourceLocation();
916   TSTNameLoc = SourceLocation();
917   return false;
918 }
919 
920 bool DeclSpec::SetExtIntType(SourceLocation KWLoc, Expr *BitsExpr,
921                              const char *&PrevSpec, unsigned &DiagID,
922                              const PrintingPolicy &Policy) {
923   assert(BitsExpr && "no expression provided!");
924   if (TypeSpecType == TST_error)
925     return false;
926 
927   if (TypeSpecType != TST_unspecified) {
928     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType, Policy);
929     DiagID = diag::err_invalid_decl_spec_combination;
930     return true;
931   }
932 
933   TypeSpecType = TST_extint;
934   ExprRep = BitsExpr;
935   TSTLoc = KWLoc;
936   TSTNameLoc = KWLoc;
937   TypeSpecOwned = false;
938   return false;
939 }
940 
941 bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
942                            unsigned &DiagID, const LangOptions &Lang) {
943   // Duplicates are permitted in C99 onwards, but are not permitted in C89 or
944   // C++.  However, since this is likely not what the user intended, we will
945   // always warn.  We do not need to set the qualifier's location since we
946   // already have it.
947   if (TypeQualifiers & T) {
948     bool IsExtension = true;
949     if (Lang.C99)
950       IsExtension = false;
951     return BadSpecifier(T, T, PrevSpec, DiagID, IsExtension);
952   }
953 
954   return SetTypeQual(T, Loc);
955 }
956 
957 bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc) {
958   TypeQualifiers |= T;
959 
960   switch (T) {
961   case TQ_unspecified: break;
962   case TQ_const:    TQ_constLoc = Loc; return false;
963   case TQ_restrict: TQ_restrictLoc = Loc; return false;
964   case TQ_volatile: TQ_volatileLoc = Loc; return false;
965   case TQ_unaligned: TQ_unalignedLoc = Loc; return false;
966   case TQ_atomic:   TQ_atomicLoc = Loc; return false;
967   }
968 
969   llvm_unreachable("Unknown type qualifier!");
970 }
971 
972 bool DeclSpec::setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
973                                      unsigned &DiagID) {
974   // 'inline inline' is ok.  However, since this is likely not what the user
975   // intended, we will always warn, similar to duplicates of type qualifiers.
976   if (FS_inline_specified) {
977     DiagID = diag::warn_duplicate_declspec;
978     PrevSpec = "inline";
979     return true;
980   }
981   FS_inline_specified = true;
982   FS_inlineLoc = Loc;
983   return false;
984 }
985 
986 bool DeclSpec::setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
987                                           unsigned &DiagID) {
988   if (FS_forceinline_specified) {
989     DiagID = diag::warn_duplicate_declspec;
990     PrevSpec = "__forceinline";
991     return true;
992   }
993   FS_forceinline_specified = true;
994   FS_forceinlineLoc = Loc;
995   return false;
996 }
997 
998 bool DeclSpec::setFunctionSpecVirtual(SourceLocation Loc,
999                                       const char *&PrevSpec,
1000                                       unsigned &DiagID) {
1001   // 'virtual virtual' is ok, but warn as this is likely not what the user
1002   // intended.
1003   if (FS_virtual_specified) {
1004     DiagID = diag::warn_duplicate_declspec;
1005     PrevSpec = "virtual";
1006     return true;
1007   }
1008   FS_virtual_specified = true;
1009   FS_virtualLoc = Loc;
1010   return false;
1011 }
1012 
1013 bool DeclSpec::setFunctionSpecExplicit(SourceLocation Loc,
1014                                        const char *&PrevSpec, unsigned &DiagID,
1015                                        ExplicitSpecifier ExplicitSpec,
1016                                        SourceLocation CloseParenLoc) {
1017   assert((ExplicitSpec.getKind() == ExplicitSpecKind::ResolvedTrue ||
1018           ExplicitSpec.getExpr()) &&
1019          "invalid ExplicitSpecifier");
1020   // 'explicit explicit' is ok, but warn as this is likely not what the user
1021   // intended.
1022   if (hasExplicitSpecifier()) {
1023     DiagID = (ExplicitSpec.getExpr() || FS_explicit_specifier.getExpr())
1024                  ? diag::err_duplicate_declspec
1025                  : diag::ext_warn_duplicate_declspec;
1026     PrevSpec = "explicit";
1027     return true;
1028   }
1029   FS_explicit_specifier = ExplicitSpec;
1030   FS_explicitLoc = Loc;
1031   FS_explicitCloseParenLoc = CloseParenLoc;
1032   return false;
1033 }
1034 
1035 bool DeclSpec::setFunctionSpecNoreturn(SourceLocation Loc,
1036                                        const char *&PrevSpec,
1037                                        unsigned &DiagID) {
1038   // '_Noreturn _Noreturn' is ok, but warn as this is likely not what the user
1039   // intended.
1040   if (FS_noreturn_specified) {
1041     DiagID = diag::warn_duplicate_declspec;
1042     PrevSpec = "_Noreturn";
1043     return true;
1044   }
1045   FS_noreturn_specified = true;
1046   FS_noreturnLoc = Loc;
1047   return false;
1048 }
1049 
1050 bool DeclSpec::SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
1051                              unsigned &DiagID) {
1052   if (Friend_specified) {
1053     PrevSpec = "friend";
1054     // Keep the later location, so that we can later diagnose ill-formed
1055     // declarations like 'friend class X friend;'. Per [class.friend]p3,
1056     // 'friend' must be the first token in a friend declaration that is
1057     // not a function declaration.
1058     FriendLoc = Loc;
1059     DiagID = diag::warn_duplicate_declspec;
1060     return true;
1061   }
1062 
1063   Friend_specified = true;
1064   FriendLoc = Loc;
1065   return false;
1066 }
1067 
1068 bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
1069                                     unsigned &DiagID) {
1070   if (isModulePrivateSpecified()) {
1071     PrevSpec = "__module_private__";
1072     DiagID = diag::ext_warn_duplicate_declspec;
1073     return true;
1074   }
1075 
1076   ModulePrivateLoc = Loc;
1077   return false;
1078 }
1079 
1080 bool DeclSpec::SetConstexprSpec(ConstexprSpecKind ConstexprKind,
1081                                 SourceLocation Loc, const char *&PrevSpec,
1082                                 unsigned &DiagID) {
1083   if (getConstexprSpecifier() != CSK_unspecified)
1084     return BadSpecifier(ConstexprKind, getConstexprSpecifier(), PrevSpec,
1085                         DiagID);
1086   ConstexprSpecifier = ConstexprKind;
1087   ConstexprLoc = Loc;
1088   return false;
1089 }
1090 
1091 void DeclSpec::SaveWrittenBuiltinSpecs() {
1092   writtenBS.Sign = getTypeSpecSign();
1093   writtenBS.Width = getTypeSpecWidth();
1094   writtenBS.Type = getTypeSpecType();
1095   // Search the list of attributes for the presence of a mode attribute.
1096   writtenBS.ModeAttr = getAttributes().hasAttribute(ParsedAttr::AT_Mode);
1097 }
1098 
1099 /// Finish - This does final analysis of the declspec, rejecting things like
1100 /// "_Imaginary" (lacking an FP type).  This returns a diagnostic to issue or
1101 /// diag::NUM_DIAGNOSTICS if there is no error.  After calling this method,
1102 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
1103 void DeclSpec::Finish(Sema &S, const PrintingPolicy &Policy) {
1104   // Before possibly changing their values, save specs as written.
1105   SaveWrittenBuiltinSpecs();
1106 
1107   // Check the type specifier components first. No checking for an invalid
1108   // type.
1109   if (TypeSpecType == TST_error)
1110     return;
1111 
1112   // If decltype(auto) is used, no other type specifiers are permitted.
1113   if (TypeSpecType == TST_decltype_auto &&
1114       (TypeSpecWidth != TSW_unspecified ||
1115        TypeSpecComplex != TSC_unspecified ||
1116        TypeSpecSign != TSS_unspecified ||
1117        TypeAltiVecVector || TypeAltiVecPixel || TypeAltiVecBool ||
1118        TypeQualifiers)) {
1119     const unsigned NumLocs = 9;
1120     SourceLocation ExtraLocs[NumLocs] = {
1121         TSWRange.getBegin(), TSCLoc,       TSSLoc,
1122         AltiVecLoc,          TQ_constLoc,  TQ_restrictLoc,
1123         TQ_volatileLoc,      TQ_atomicLoc, TQ_unalignedLoc};
1124     FixItHint Hints[NumLocs];
1125     SourceLocation FirstLoc;
1126     for (unsigned I = 0; I != NumLocs; ++I) {
1127       if (ExtraLocs[I].isValid()) {
1128         if (FirstLoc.isInvalid() ||
1129             S.getSourceManager().isBeforeInTranslationUnit(ExtraLocs[I],
1130                                                            FirstLoc))
1131           FirstLoc = ExtraLocs[I];
1132         Hints[I] = FixItHint::CreateRemoval(ExtraLocs[I]);
1133       }
1134     }
1135     TypeSpecWidth = TSW_unspecified;
1136     TypeSpecComplex = TSC_unspecified;
1137     TypeSpecSign = TSS_unspecified;
1138     TypeAltiVecVector = TypeAltiVecPixel = TypeAltiVecBool = false;
1139     TypeQualifiers = 0;
1140     S.Diag(TSTLoc, diag::err_decltype_auto_cannot_be_combined)
1141       << Hints[0] << Hints[1] << Hints[2] << Hints[3]
1142       << Hints[4] << Hints[5] << Hints[6] << Hints[7];
1143   }
1144 
1145   // Validate and finalize AltiVec vector declspec.
1146   if (TypeAltiVecVector) {
1147     if (TypeAltiVecBool) {
1148       // Sign specifiers are not allowed with vector bool. (PIM 2.1)
1149       if (TypeSpecSign != TSS_unspecified) {
1150         S.Diag(TSSLoc, diag::err_invalid_vector_bool_decl_spec)
1151           << getSpecifierName((TSS)TypeSpecSign);
1152       }
1153       // Only char/int are valid with vector bool prior to Power10.
1154       // Power10 adds instructions that produce vector bool data
1155       // for quadwords as well so allow vector bool __int128.
1156       if (((TypeSpecType != TST_unspecified) && (TypeSpecType != TST_char) &&
1157            (TypeSpecType != TST_int) && (TypeSpecType != TST_int128)) ||
1158           TypeAltiVecPixel) {
1159         S.Diag(TSTLoc, diag::err_invalid_vector_bool_decl_spec)
1160           << (TypeAltiVecPixel ? "__pixel" :
1161                                  getSpecifierName((TST)TypeSpecType, Policy));
1162       }
1163       // vector bool __int128 requires Power10.
1164       if ((TypeSpecType == TST_int128) &&
1165           (!S.Context.getTargetInfo().hasFeature("power10-vector")))
1166         S.Diag(TSTLoc, diag::err_invalid_vector_bool_int128_decl_spec);
1167 
1168       // Only 'short' and 'long long' are valid with vector bool. (PIM 2.1)
1169       if ((TypeSpecWidth != TSW_unspecified) && (TypeSpecWidth != TSW_short) &&
1170           (TypeSpecWidth != TSW_longlong))
1171         S.Diag(TSWRange.getBegin(), diag::err_invalid_vector_bool_decl_spec)
1172             << getSpecifierName((TSW)TypeSpecWidth);
1173 
1174       // vector bool long long requires VSX support or ZVector.
1175       if ((TypeSpecWidth == TSW_longlong) &&
1176           (!S.Context.getTargetInfo().hasFeature("vsx")) &&
1177           (!S.Context.getTargetInfo().hasFeature("power8-vector")) &&
1178           !S.getLangOpts().ZVector)
1179         S.Diag(TSTLoc, diag::err_invalid_vector_long_long_decl_spec);
1180 
1181       // Elements of vector bool are interpreted as unsigned. (PIM 2.1)
1182       if ((TypeSpecType == TST_char) || (TypeSpecType == TST_int) ||
1183           (TypeSpecType == TST_int128) || (TypeSpecWidth != TSW_unspecified))
1184         TypeSpecSign = TSS_unsigned;
1185     } else if (TypeSpecType == TST_double) {
1186       // vector long double and vector long long double are never allowed.
1187       // vector double is OK for Power7 and later, and ZVector.
1188       if (TypeSpecWidth == TSW_long || TypeSpecWidth == TSW_longlong)
1189         S.Diag(TSWRange.getBegin(),
1190                diag::err_invalid_vector_long_double_decl_spec);
1191       else if (!S.Context.getTargetInfo().hasFeature("vsx") &&
1192                !S.getLangOpts().ZVector)
1193         S.Diag(TSTLoc, diag::err_invalid_vector_double_decl_spec);
1194     } else if (TypeSpecType == TST_float) {
1195       // vector float is unsupported for ZVector unless we have the
1196       // vector-enhancements facility 1 (ISA revision 12).
1197       if (S.getLangOpts().ZVector &&
1198           !S.Context.getTargetInfo().hasFeature("arch12"))
1199         S.Diag(TSTLoc, diag::err_invalid_vector_float_decl_spec);
1200     } else if (TypeSpecWidth == TSW_long) {
1201       // vector long is unsupported for ZVector and deprecated for AltiVec.
1202       if (S.getLangOpts().ZVector)
1203         S.Diag(TSWRange.getBegin(), diag::err_invalid_vector_long_decl_spec);
1204       else
1205         S.Diag(TSWRange.getBegin(),
1206                diag::warn_vector_long_decl_spec_combination)
1207             << getSpecifierName((TST)TypeSpecType, Policy);
1208     }
1209 
1210     if (TypeAltiVecPixel) {
1211       //TODO: perform validation
1212       TypeSpecType = TST_int;
1213       TypeSpecSign = TSS_unsigned;
1214       TypeSpecWidth = TSW_short;
1215       TypeSpecOwned = false;
1216     }
1217   }
1218 
1219   bool IsFixedPointType =
1220       TypeSpecType == TST_accum || TypeSpecType == TST_fract;
1221 
1222   // signed/unsigned are only valid with int/char/wchar_t/_Accum.
1223   if (TypeSpecSign != TSS_unspecified) {
1224     if (TypeSpecType == TST_unspecified)
1225       TypeSpecType = TST_int; // unsigned -> unsigned int, signed -> signed int.
1226     else if (TypeSpecType != TST_int && TypeSpecType != TST_int128 &&
1227              TypeSpecType != TST_char && TypeSpecType != TST_wchar &&
1228              !IsFixedPointType && TypeSpecType != TST_extint) {
1229       S.Diag(TSSLoc, diag::err_invalid_sign_spec)
1230         << getSpecifierName((TST)TypeSpecType, Policy);
1231       // signed double -> double.
1232       TypeSpecSign = TSS_unspecified;
1233     }
1234   }
1235 
1236   // Validate the width of the type.
1237   switch (TypeSpecWidth) {
1238   case TSW_unspecified: break;
1239   case TSW_short:    // short int
1240   case TSW_longlong: // long long int
1241     if (TypeSpecType == TST_unspecified)
1242       TypeSpecType = TST_int; // short -> short int, long long -> long long int.
1243     else if (!(TypeSpecType == TST_int ||
1244                (IsFixedPointType && TypeSpecWidth != TSW_longlong))) {
1245       S.Diag(TSWRange.getBegin(), diag::err_invalid_width_spec)
1246           << (int)TypeSpecWidth << getSpecifierName((TST)TypeSpecType, Policy);
1247       TypeSpecType = TST_int;
1248       TypeSpecSat = false;
1249       TypeSpecOwned = false;
1250     }
1251     break;
1252   case TSW_long:  // long double, long int
1253     if (TypeSpecType == TST_unspecified)
1254       TypeSpecType = TST_int;  // long -> long int.
1255     else if (TypeSpecType != TST_int && TypeSpecType != TST_double &&
1256              !IsFixedPointType) {
1257       S.Diag(TSWRange.getBegin(), diag::err_invalid_width_spec)
1258           << (int)TypeSpecWidth << getSpecifierName((TST)TypeSpecType, Policy);
1259       TypeSpecType = TST_int;
1260       TypeSpecSat = false;
1261       TypeSpecOwned = false;
1262     }
1263     break;
1264   }
1265 
1266   // TODO: if the implementation does not implement _Complex or _Imaginary,
1267   // disallow their use.  Need information about the backend.
1268   if (TypeSpecComplex != TSC_unspecified) {
1269     if (TypeSpecType == TST_unspecified) {
1270       S.Diag(TSCLoc, diag::ext_plain_complex)
1271         << FixItHint::CreateInsertion(
1272                               S.getLocForEndOfToken(getTypeSpecComplexLoc()),
1273                                                  " double");
1274       TypeSpecType = TST_double;   // _Complex -> _Complex double.
1275     } else if (TypeSpecType == TST_int || TypeSpecType == TST_char ||
1276                TypeSpecType == TST_extint) {
1277       // Note that this intentionally doesn't include _Complex _Bool.
1278       if (!S.getLangOpts().CPlusPlus)
1279         S.Diag(TSTLoc, diag::ext_integer_complex);
1280     } else if (TypeSpecType != TST_float && TypeSpecType != TST_double &&
1281                TypeSpecType != TST_float128) {
1282       S.Diag(TSCLoc, diag::err_invalid_complex_spec)
1283         << getSpecifierName((TST)TypeSpecType, Policy);
1284       TypeSpecComplex = TSC_unspecified;
1285     }
1286   }
1287 
1288   // C11 6.7.1/3, C++11 [dcl.stc]p1, GNU TLS: __thread, thread_local and
1289   // _Thread_local can only appear with the 'static' and 'extern' storage class
1290   // specifiers. We also allow __private_extern__ as an extension.
1291   if (ThreadStorageClassSpec != TSCS_unspecified) {
1292     switch (StorageClassSpec) {
1293     case SCS_unspecified:
1294     case SCS_extern:
1295     case SCS_private_extern:
1296     case SCS_static:
1297       break;
1298     default:
1299       if (S.getSourceManager().isBeforeInTranslationUnit(
1300             getThreadStorageClassSpecLoc(), getStorageClassSpecLoc()))
1301         S.Diag(getStorageClassSpecLoc(),
1302              diag::err_invalid_decl_spec_combination)
1303           << DeclSpec::getSpecifierName(getThreadStorageClassSpec())
1304           << SourceRange(getThreadStorageClassSpecLoc());
1305       else
1306         S.Diag(getThreadStorageClassSpecLoc(),
1307              diag::err_invalid_decl_spec_combination)
1308           << DeclSpec::getSpecifierName(getStorageClassSpec())
1309           << SourceRange(getStorageClassSpecLoc());
1310       // Discard the thread storage class specifier to recover.
1311       ThreadStorageClassSpec = TSCS_unspecified;
1312       ThreadStorageClassSpecLoc = SourceLocation();
1313     }
1314   }
1315 
1316   // If no type specifier was provided and we're parsing a language where
1317   // the type specifier is not optional, but we got 'auto' as a storage
1318   // class specifier, then assume this is an attempt to use C++0x's 'auto'
1319   // type specifier.
1320   if (S.getLangOpts().CPlusPlus &&
1321       TypeSpecType == TST_unspecified && StorageClassSpec == SCS_auto) {
1322     TypeSpecType = TST_auto;
1323     StorageClassSpec = SCS_unspecified;
1324     TSTLoc = TSTNameLoc = StorageClassSpecLoc;
1325     StorageClassSpecLoc = SourceLocation();
1326   }
1327   // Diagnose if we've recovered from an ill-formed 'auto' storage class
1328   // specifier in a pre-C++11 dialect of C++.
1329   if (!S.getLangOpts().CPlusPlus11 && TypeSpecType == TST_auto)
1330     S.Diag(TSTLoc, diag::ext_auto_type_specifier);
1331   if (S.getLangOpts().CPlusPlus && !S.getLangOpts().CPlusPlus11 &&
1332       StorageClassSpec == SCS_auto)
1333     S.Diag(StorageClassSpecLoc, diag::warn_auto_storage_class)
1334       << FixItHint::CreateRemoval(StorageClassSpecLoc);
1335   if (TypeSpecType == TST_char8)
1336     S.Diag(TSTLoc, diag::warn_cxx17_compat_unicode_type);
1337   else if (TypeSpecType == TST_char16 || TypeSpecType == TST_char32)
1338     S.Diag(TSTLoc, diag::warn_cxx98_compat_unicode_type)
1339       << (TypeSpecType == TST_char16 ? "char16_t" : "char32_t");
1340   if (getConstexprSpecifier() == CSK_constexpr)
1341     S.Diag(ConstexprLoc, diag::warn_cxx98_compat_constexpr);
1342   else if (getConstexprSpecifier() == CSK_consteval)
1343     S.Diag(ConstexprLoc, diag::warn_cxx20_compat_consteval);
1344   else if (getConstexprSpecifier() == CSK_constinit)
1345     S.Diag(ConstexprLoc, diag::warn_cxx20_compat_constinit);
1346   // C++ [class.friend]p6:
1347   //   No storage-class-specifier shall appear in the decl-specifier-seq
1348   //   of a friend declaration.
1349   if (isFriendSpecified() &&
1350       (getStorageClassSpec() || getThreadStorageClassSpec())) {
1351     SmallString<32> SpecName;
1352     SourceLocation SCLoc;
1353     FixItHint StorageHint, ThreadHint;
1354 
1355     if (DeclSpec::SCS SC = getStorageClassSpec()) {
1356       SpecName = getSpecifierName(SC);
1357       SCLoc = getStorageClassSpecLoc();
1358       StorageHint = FixItHint::CreateRemoval(SCLoc);
1359     }
1360 
1361     if (DeclSpec::TSCS TSC = getThreadStorageClassSpec()) {
1362       if (!SpecName.empty()) SpecName += " ";
1363       SpecName += getSpecifierName(TSC);
1364       SCLoc = getThreadStorageClassSpecLoc();
1365       ThreadHint = FixItHint::CreateRemoval(SCLoc);
1366     }
1367 
1368     S.Diag(SCLoc, diag::err_friend_decl_spec)
1369       << SpecName << StorageHint << ThreadHint;
1370 
1371     ClearStorageClassSpecs();
1372   }
1373 
1374   // C++11 [dcl.fct.spec]p5:
1375   //   The virtual specifier shall be used only in the initial
1376   //   declaration of a non-static class member function;
1377   // C++11 [dcl.fct.spec]p6:
1378   //   The explicit specifier shall be used only in the declaration of
1379   //   a constructor or conversion function within its class
1380   //   definition;
1381   if (isFriendSpecified() && (isVirtualSpecified() || hasExplicitSpecifier())) {
1382     StringRef Keyword;
1383     FixItHint Hint;
1384     SourceLocation SCLoc;
1385 
1386     if (isVirtualSpecified()) {
1387       Keyword = "virtual";
1388       SCLoc = getVirtualSpecLoc();
1389       Hint = FixItHint::CreateRemoval(SCLoc);
1390     } else {
1391       Keyword = "explicit";
1392       SCLoc = getExplicitSpecLoc();
1393       Hint = FixItHint::CreateRemoval(getExplicitSpecRange());
1394     }
1395 
1396     S.Diag(SCLoc, diag::err_friend_decl_spec)
1397       << Keyword << Hint;
1398 
1399     FS_virtual_specified = false;
1400     FS_explicit_specifier = ExplicitSpecifier();
1401     FS_virtualLoc = FS_explicitLoc = SourceLocation();
1402   }
1403 
1404   assert(!TypeSpecOwned || isDeclRep((TST) TypeSpecType));
1405 
1406   // Okay, now we can infer the real type.
1407 
1408   // TODO: return "auto function" and other bad things based on the real type.
1409 
1410   // 'data definition has no type or storage class'?
1411 }
1412 
1413 bool DeclSpec::isMissingDeclaratorOk() {
1414   TST tst = getTypeSpecType();
1415   return isDeclRep(tst) && getRepAsDecl() != nullptr &&
1416     StorageClassSpec != DeclSpec::SCS_typedef;
1417 }
1418 
1419 void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc,
1420                                           OverloadedOperatorKind Op,
1421                                           SourceLocation SymbolLocations[3]) {
1422   Kind = UnqualifiedIdKind::IK_OperatorFunctionId;
1423   StartLocation = OperatorLoc;
1424   EndLocation = OperatorLoc;
1425   OperatorFunctionId.Operator = Op;
1426   for (unsigned I = 0; I != 3; ++I) {
1427     OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I].getRawEncoding();
1428 
1429     if (SymbolLocations[I].isValid())
1430       EndLocation = SymbolLocations[I];
1431   }
1432 }
1433 
1434 bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc,
1435                                   const char *&PrevSpec) {
1436   if (!FirstLocation.isValid())
1437     FirstLocation = Loc;
1438   LastLocation = Loc;
1439   LastSpecifier = VS;
1440 
1441   if (Specifiers & VS) {
1442     PrevSpec = getSpecifierName(VS);
1443     return true;
1444   }
1445 
1446   Specifiers |= VS;
1447 
1448   switch (VS) {
1449   default: llvm_unreachable("Unknown specifier!");
1450   case VS_Override: VS_overrideLoc = Loc; break;
1451   case VS_GNU_Final:
1452   case VS_Sealed:
1453   case VS_Final:    VS_finalLoc = Loc; break;
1454   }
1455 
1456   return false;
1457 }
1458 
1459 const char *VirtSpecifiers::getSpecifierName(Specifier VS) {
1460   switch (VS) {
1461   default: llvm_unreachable("Unknown specifier");
1462   case VS_Override: return "override";
1463   case VS_Final: return "final";
1464   case VS_GNU_Final: return "__final";
1465   case VS_Sealed: return "sealed";
1466   }
1467 }
1468