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