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