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