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