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