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