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