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