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