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