1 //===--- SemaDeclSpec.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/NestedNameSpecifier.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Parse/ParseDiagnostic.h" // FIXME: remove this back-dependency!
23 #include "clang/Sema/LocInfoType.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/Sema.h"
26 #include "clang/Sema/SemaDiagnostic.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include <cstring>
31 using namespace clang;
32 
33 
34 static DiagnosticBuilder Diag(DiagnosticsEngine &D, SourceLocation Loc,
35                               unsigned DiagID) {
36   return D.Report(Loc, DiagID);
37 }
38 
39 
40 void UnqualifiedId::setTemplateId(TemplateIdAnnotation *TemplateId) {
41   assert(TemplateId && "NULL template-id annotation?");
42   Kind = IK_TemplateId;
43   this->TemplateId = TemplateId;
44   StartLocation = TemplateId->TemplateNameLoc;
45   EndLocation = TemplateId->RAngleLoc;
46 }
47 
48 void UnqualifiedId::setConstructorTemplateId(TemplateIdAnnotation *TemplateId) {
49   assert(TemplateId && "NULL template-id annotation?");
50   Kind = IK_ConstructorTemplateId;
51   this->TemplateId = TemplateId;
52   StartLocation = TemplateId->TemplateNameLoc;
53   EndLocation = TemplateId->RAngleLoc;
54 }
55 
56 void CXXScopeSpec::Extend(ASTContext &Context, SourceLocation TemplateKWLoc,
57                           TypeLoc TL, SourceLocation ColonColonLoc) {
58   Builder.Extend(Context, TemplateKWLoc, TL, ColonColonLoc);
59   if (Range.getBegin().isInvalid())
60     Range.setBegin(TL.getBeginLoc());
61   Range.setEnd(ColonColonLoc);
62 
63   assert(Range == Builder.getSourceRange() &&
64          "NestedNameSpecifierLoc range computation incorrect");
65 }
66 
67 void CXXScopeSpec::Extend(ASTContext &Context, IdentifierInfo *Identifier,
68                           SourceLocation IdentifierLoc,
69                           SourceLocation ColonColonLoc) {
70   Builder.Extend(Context, Identifier, IdentifierLoc, ColonColonLoc);
71 
72   if (Range.getBegin().isInvalid())
73     Range.setBegin(IdentifierLoc);
74   Range.setEnd(ColonColonLoc);
75 
76   assert(Range == Builder.getSourceRange() &&
77          "NestedNameSpecifierLoc range computation incorrect");
78 }
79 
80 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceDecl *Namespace,
81                           SourceLocation NamespaceLoc,
82                           SourceLocation ColonColonLoc) {
83   Builder.Extend(Context, Namespace, NamespaceLoc, ColonColonLoc);
84 
85   if (Range.getBegin().isInvalid())
86     Range.setBegin(NamespaceLoc);
87   Range.setEnd(ColonColonLoc);
88 
89   assert(Range == Builder.getSourceRange() &&
90          "NestedNameSpecifierLoc range computation incorrect");
91 }
92 
93 void CXXScopeSpec::Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
94                           SourceLocation AliasLoc,
95                           SourceLocation ColonColonLoc) {
96   Builder.Extend(Context, Alias, AliasLoc, ColonColonLoc);
97 
98   if (Range.getBegin().isInvalid())
99     Range.setBegin(AliasLoc);
100   Range.setEnd(ColonColonLoc);
101 
102   assert(Range == Builder.getSourceRange() &&
103          "NestedNameSpecifierLoc range computation incorrect");
104 }
105 
106 void CXXScopeSpec::MakeGlobal(ASTContext &Context,
107                               SourceLocation ColonColonLoc) {
108   Builder.MakeGlobal(Context, ColonColonLoc);
109 
110   Range = SourceRange(ColonColonLoc);
111 
112   assert(Range == Builder.getSourceRange() &&
113          "NestedNameSpecifierLoc range computation incorrect");
114 }
115 
116 void CXXScopeSpec::MakeTrivial(ASTContext &Context,
117                                NestedNameSpecifier *Qualifier, SourceRange R) {
118   Builder.MakeTrivial(Context, Qualifier, R);
119   Range = R;
120 }
121 
122 void CXXScopeSpec::Adopt(NestedNameSpecifierLoc Other) {
123   if (!Other) {
124     Range = SourceRange();
125     Builder.Clear();
126     return;
127   }
128 
129   Range = Other.getSourceRange();
130   Builder.Adopt(Other);
131 }
132 
133 SourceLocation CXXScopeSpec::getLastQualifierNameLoc() const {
134   if (!Builder.getRepresentation())
135     return SourceLocation();
136   return Builder.getTemporary().getLocalBeginLoc();
137 }
138 
139 NestedNameSpecifierLoc
140 CXXScopeSpec::getWithLocInContext(ASTContext &Context) const {
141   if (!Builder.getRepresentation())
142     return NestedNameSpecifierLoc();
143 
144   return Builder.getWithLocInContext(Context);
145 }
146 
147 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
148 /// "TheDeclarator" is the declarator that this will be added to.
149 DeclaratorChunk DeclaratorChunk::getFunction(bool hasProto,
150                                              bool isAmbiguous,
151                                              SourceLocation LParenLoc,
152                                              ParamInfo *ArgInfo,
153                                              unsigned NumArgs,
154                                              SourceLocation EllipsisLoc,
155                                              SourceLocation RParenLoc,
156                                              unsigned TypeQuals,
157                                              bool RefQualifierIsLvalueRef,
158                                              SourceLocation RefQualifierLoc,
159                                              SourceLocation ConstQualifierLoc,
160                                              SourceLocation
161                                                  VolatileQualifierLoc,
162                                              SourceLocation MutableLoc,
163                                              ExceptionSpecificationType
164                                                  ESpecType,
165                                              SourceLocation ESpecLoc,
166                                              ParsedType *Exceptions,
167                                              SourceRange *ExceptionRanges,
168                                              unsigned NumExceptions,
169                                              Expr *NoexceptExpr,
170                                              SourceLocation LocalRangeBegin,
171                                              SourceLocation LocalRangeEnd,
172                                              Declarator &TheDeclarator,
173                                              TypeResult TrailingReturnType) {
174   assert(!(TypeQuals & DeclSpec::TQ_atomic) &&
175          "function cannot have _Atomic qualifier");
176 
177   DeclaratorChunk I;
178   I.Kind                        = Function;
179   I.Loc                         = LocalRangeBegin;
180   I.EndLoc                      = LocalRangeEnd;
181   I.Fun.AttrList                = 0;
182   I.Fun.hasPrototype            = hasProto;
183   I.Fun.isVariadic              = EllipsisLoc.isValid();
184   I.Fun.isAmbiguous             = isAmbiguous;
185   I.Fun.LParenLoc               = LParenLoc.getRawEncoding();
186   I.Fun.EllipsisLoc             = EllipsisLoc.getRawEncoding();
187   I.Fun.RParenLoc               = RParenLoc.getRawEncoding();
188   I.Fun.DeleteArgInfo           = false;
189   I.Fun.TypeQuals               = TypeQuals;
190   I.Fun.NumArgs                 = NumArgs;
191   I.Fun.ArgInfo                 = 0;
192   I.Fun.RefQualifierIsLValueRef = RefQualifierIsLvalueRef;
193   I.Fun.RefQualifierLoc         = RefQualifierLoc.getRawEncoding();
194   I.Fun.ConstQualifierLoc       = ConstQualifierLoc.getRawEncoding();
195   I.Fun.VolatileQualifierLoc    = VolatileQualifierLoc.getRawEncoding();
196   I.Fun.MutableLoc              = MutableLoc.getRawEncoding();
197   I.Fun.ExceptionSpecType       = ESpecType;
198   I.Fun.ExceptionSpecLoc        = ESpecLoc.getRawEncoding();
199   I.Fun.NumExceptions           = 0;
200   I.Fun.Exceptions              = 0;
201   I.Fun.NoexceptExpr            = 0;
202   I.Fun.HasTrailingReturnType   = TrailingReturnType.isUsable() ||
203                                   TrailingReturnType.isInvalid();
204   I.Fun.TrailingReturnType      = TrailingReturnType.get();
205 
206   // new[] an argument array if needed.
207   if (NumArgs) {
208     // If the 'InlineParams' in Declarator is unused and big enough, put our
209     // parameter list there (in an effort to avoid new/delete traffic).  If it
210     // is already used (consider a function returning a function pointer) or too
211     // small (function taking too many arguments), go to the heap.
212     if (!TheDeclarator.InlineParamsUsed &&
213         NumArgs <= llvm::array_lengthof(TheDeclarator.InlineParams)) {
214       I.Fun.ArgInfo = TheDeclarator.InlineParams;
215       I.Fun.DeleteArgInfo = false;
216       TheDeclarator.InlineParamsUsed = true;
217     } else {
218       I.Fun.ArgInfo = new DeclaratorChunk::ParamInfo[NumArgs];
219       I.Fun.DeleteArgInfo = true;
220     }
221     memcpy(I.Fun.ArgInfo, ArgInfo, sizeof(ArgInfo[0])*NumArgs);
222   }
223 
224   // Check what exception specification information we should actually store.
225   switch (ESpecType) {
226   default: break; // By default, save nothing.
227   case EST_Dynamic:
228     // new[] an exception array if needed
229     if (NumExceptions) {
230       I.Fun.NumExceptions = NumExceptions;
231       I.Fun.Exceptions = new DeclaratorChunk::TypeAndRange[NumExceptions];
232       for (unsigned i = 0; i != NumExceptions; ++i) {
233         I.Fun.Exceptions[i].Ty = Exceptions[i];
234         I.Fun.Exceptions[i].Range = ExceptionRanges[i];
235       }
236     }
237     break;
238 
239   case EST_ComputedNoexcept:
240     I.Fun.NoexceptExpr = NoexceptExpr;
241     break;
242   }
243   return I;
244 }
245 
246 bool Declarator::isDeclarationOfFunction() const {
247   for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
248     switch (DeclTypeInfo[i].Kind) {
249     case DeclaratorChunk::Function:
250       return true;
251     case DeclaratorChunk::Paren:
252       continue;
253     case DeclaratorChunk::Pointer:
254     case DeclaratorChunk::Reference:
255     case DeclaratorChunk::Array:
256     case DeclaratorChunk::BlockPointer:
257     case DeclaratorChunk::MemberPointer:
258       return false;
259     }
260     llvm_unreachable("Invalid type chunk");
261   }
262 
263   switch (DS.getTypeSpecType()) {
264     case TST_atomic:
265     case TST_auto:
266     case TST_bool:
267     case TST_char:
268     case TST_char16:
269     case TST_char32:
270     case TST_class:
271     case TST_decimal128:
272     case TST_decimal32:
273     case TST_decimal64:
274     case TST_double:
275     case TST_enum:
276     case TST_error:
277     case TST_float:
278     case TST_half:
279     case TST_int:
280     case TST_int128:
281     case TST_struct:
282     case TST_interface:
283     case TST_union:
284     case TST_unknown_anytype:
285     case TST_unspecified:
286     case TST_void:
287     case TST_wchar:
288     case TST_image1d_t:
289     case TST_image1d_array_t:
290     case TST_image1d_buffer_t:
291     case TST_image2d_t:
292     case TST_image2d_array_t:
293     case TST_image3d_t:
294     case TST_sampler_t:
295     case TST_event_t:
296       return false;
297 
298     case TST_decltype_auto:
299       // This must have an initializer, so can't be a function declaration,
300       // even if the initializer has function type.
301       return false;
302 
303     case TST_decltype:
304     case TST_typeofExpr:
305       if (Expr *E = DS.getRepAsExpr())
306         return E->getType()->isFunctionType();
307       return false;
308 
309     case TST_underlyingType:
310     case TST_typename:
311     case TST_typeofType: {
312       QualType QT = DS.getRepAsType().get();
313       if (QT.isNull())
314         return false;
315 
316       if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT))
317         QT = LIT->getType();
318 
319       if (QT.isNull())
320         return false;
321 
322       return QT->isFunctionType();
323     }
324   }
325 
326   llvm_unreachable("Invalid TypeSpecType!");
327 }
328 
329 bool Declarator::isStaticMember() {
330   assert(getContext() == MemberContext);
331   return getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
332          CXXMethodDecl::isStaticOverloadedOperator(
333              getName().OperatorFunctionId.Operator);
334 }
335 
336 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers this
337 /// declaration specifier includes.
338 ///
339 unsigned DeclSpec::getParsedSpecifiers() const {
340   unsigned Res = 0;
341   if (StorageClassSpec != SCS_unspecified ||
342       ThreadStorageClassSpec != TSCS_unspecified)
343     Res |= PQ_StorageClassSpecifier;
344 
345   if (TypeQualifiers != TQ_unspecified)
346     Res |= PQ_TypeQualifier;
347 
348   if (hasTypeSpecifier())
349     Res |= PQ_TypeSpecifier;
350 
351   if (FS_inline_specified || FS_virtual_specified || FS_explicit_specified ||
352       FS_noreturn_specified)
353     Res |= PQ_FunctionSpecifier;
354   return Res;
355 }
356 
357 template <class T> static bool BadSpecifier(T TNew, T TPrev,
358                                             const char *&PrevSpec,
359                                             unsigned &DiagID,
360                                             bool IsExtension = true) {
361   PrevSpec = DeclSpec::getSpecifierName(TPrev);
362   if (TNew != TPrev)
363     DiagID = diag::err_invalid_decl_spec_combination;
364   else
365     DiagID = IsExtension ? diag::ext_duplicate_declspec :
366                            diag::warn_duplicate_declspec;
367   return true;
368 }
369 
370 const char *DeclSpec::getSpecifierName(DeclSpec::SCS S) {
371   switch (S) {
372   case DeclSpec::SCS_unspecified: return "unspecified";
373   case DeclSpec::SCS_typedef:     return "typedef";
374   case DeclSpec::SCS_extern:      return "extern";
375   case DeclSpec::SCS_static:      return "static";
376   case DeclSpec::SCS_auto:        return "auto";
377   case DeclSpec::SCS_register:    return "register";
378   case DeclSpec::SCS_private_extern: return "__private_extern__";
379   case DeclSpec::SCS_mutable:     return "mutable";
380   }
381   llvm_unreachable("Unknown typespec!");
382 }
383 
384 const char *DeclSpec::getSpecifierName(DeclSpec::TSCS S) {
385   switch (S) {
386   case DeclSpec::TSCS_unspecified:   return "unspecified";
387   case DeclSpec::TSCS___thread:      return "__thread";
388   case DeclSpec::TSCS_thread_local:  return "thread_local";
389   case DeclSpec::TSCS__Thread_local: return "_Thread_local";
390   }
391   llvm_unreachable("Unknown typespec!");
392 }
393 
394 const char *DeclSpec::getSpecifierName(TSW W) {
395   switch (W) {
396   case TSW_unspecified: return "unspecified";
397   case TSW_short:       return "short";
398   case TSW_long:        return "long";
399   case TSW_longlong:    return "long long";
400   }
401   llvm_unreachable("Unknown typespec!");
402 }
403 
404 const char *DeclSpec::getSpecifierName(TSC C) {
405   switch (C) {
406   case TSC_unspecified: return "unspecified";
407   case TSC_imaginary:   return "imaginary";
408   case TSC_complex:     return "complex";
409   }
410   llvm_unreachable("Unknown typespec!");
411 }
412 
413 
414 const char *DeclSpec::getSpecifierName(TSS S) {
415   switch (S) {
416   case TSS_unspecified: return "unspecified";
417   case TSS_signed:      return "signed";
418   case TSS_unsigned:    return "unsigned";
419   }
420   llvm_unreachable("Unknown typespec!");
421 }
422 
423 const char *DeclSpec::getSpecifierName(DeclSpec::TST T) {
424   switch (T) {
425   case DeclSpec::TST_unspecified: return "unspecified";
426   case DeclSpec::TST_void:        return "void";
427   case DeclSpec::TST_char:        return "char";
428   case DeclSpec::TST_wchar:       return "wchar_t";
429   case DeclSpec::TST_char16:      return "char16_t";
430   case DeclSpec::TST_char32:      return "char32_t";
431   case DeclSpec::TST_int:         return "int";
432   case DeclSpec::TST_int128:      return "__int128";
433   case DeclSpec::TST_half:        return "half";
434   case DeclSpec::TST_float:       return "float";
435   case DeclSpec::TST_double:      return "double";
436   case DeclSpec::TST_bool:        return "_Bool";
437   case DeclSpec::TST_decimal32:   return "_Decimal32";
438   case DeclSpec::TST_decimal64:   return "_Decimal64";
439   case DeclSpec::TST_decimal128:  return "_Decimal128";
440   case DeclSpec::TST_enum:        return "enum";
441   case DeclSpec::TST_class:       return "class";
442   case DeclSpec::TST_union:       return "union";
443   case DeclSpec::TST_struct:      return "struct";
444   case DeclSpec::TST_interface:   return "__interface";
445   case DeclSpec::TST_typename:    return "type-name";
446   case DeclSpec::TST_typeofType:
447   case DeclSpec::TST_typeofExpr:  return "typeof";
448   case DeclSpec::TST_auto:        return "auto";
449   case DeclSpec::TST_decltype:    return "(decltype)";
450   case DeclSpec::TST_decltype_auto: return "decltype(auto)";
451   case DeclSpec::TST_underlyingType: return "__underlying_type";
452   case DeclSpec::TST_unknown_anytype: return "__unknown_anytype";
453   case DeclSpec::TST_atomic: return "_Atomic";
454   case DeclSpec::TST_image1d_t:   return "image1d_t";
455   case DeclSpec::TST_image1d_array_t: return "image1d_array_t";
456   case DeclSpec::TST_image1d_buffer_t: return "image1d_buffer_t";
457   case DeclSpec::TST_image2d_t:   return "image2d_t";
458   case DeclSpec::TST_image2d_array_t: return "image2d_array_t";
459   case DeclSpec::TST_image3d_t:   return "image3d_t";
460   case DeclSpec::TST_sampler_t:   return "sampler_t";
461   case DeclSpec::TST_event_t:     return "event_t";
462   case DeclSpec::TST_error:       return "(error)";
463   }
464   llvm_unreachable("Unknown typespec!");
465 }
466 
467 const char *DeclSpec::getSpecifierName(TQ T) {
468   switch (T) {
469   case DeclSpec::TQ_unspecified: return "unspecified";
470   case DeclSpec::TQ_const:       return "const";
471   case DeclSpec::TQ_restrict:    return "restrict";
472   case DeclSpec::TQ_volatile:    return "volatile";
473   case DeclSpec::TQ_atomic:      return "_Atomic";
474   }
475   llvm_unreachable("Unknown typespec!");
476 }
477 
478 bool DeclSpec::SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
479                                    const char *&PrevSpec,
480                                    unsigned &DiagID) {
481   // OpenCL v1.1 s6.8g: "The extern, static, auto and register storage-class
482   // specifiers are not supported.
483   // It seems sensible to prohibit private_extern too
484   // The cl_clang_storage_class_specifiers extension enables support for
485   // these storage-class specifiers.
486   // OpenCL v1.2 s6.8 changes this to "The auto and register storage-class
487   // specifiers are not supported."
488   if (S.getLangOpts().OpenCL &&
489       !S.getOpenCLOptions().cl_clang_storage_class_specifiers) {
490     switch (SC) {
491     case SCS_extern:
492     case SCS_private_extern:
493     case SCS_static:
494         if (S.getLangOpts().OpenCLVersion < 120) {
495           DiagID   = diag::err_not_opencl_storage_class_specifier;
496           PrevSpec = getSpecifierName(SC);
497           return true;
498         }
499         break;
500     case SCS_auto:
501     case SCS_register:
502       DiagID   = diag::err_not_opencl_storage_class_specifier;
503       PrevSpec = getSpecifierName(SC);
504       return true;
505     default:
506       break;
507     }
508   }
509 
510   if (StorageClassSpec != SCS_unspecified) {
511     // Maybe this is an attempt to use C++11 'auto' outside of C++11 mode.
512     bool isInvalid = true;
513     if (TypeSpecType == TST_unspecified && S.getLangOpts().CPlusPlus) {
514       if (SC == SCS_auto)
515         return SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID);
516       if (StorageClassSpec == SCS_auto) {
517         isInvalid = SetTypeSpecType(TST_auto, StorageClassSpecLoc,
518                                     PrevSpec, DiagID);
519         assert(!isInvalid && "auto SCS -> TST recovery failed");
520       }
521     }
522 
523     // Changing storage class is allowed only if the previous one
524     // was the 'extern' that is part of a linkage specification and
525     // the new storage class is 'typedef'.
526     if (isInvalid &&
527         !(SCS_extern_in_linkage_spec &&
528           StorageClassSpec == SCS_extern &&
529           SC == SCS_typedef))
530       return BadSpecifier(SC, (SCS)StorageClassSpec, PrevSpec, DiagID);
531   }
532   StorageClassSpec = SC;
533   StorageClassSpecLoc = Loc;
534   assert((unsigned)SC == StorageClassSpec && "SCS constants overflow bitfield");
535   return false;
536 }
537 
538 bool DeclSpec::SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
539                                          const char *&PrevSpec,
540                                          unsigned &DiagID) {
541   if (ThreadStorageClassSpec != TSCS_unspecified)
542     return BadSpecifier(TSC, (TSCS)ThreadStorageClassSpec, PrevSpec, DiagID);
543 
544   ThreadStorageClassSpec = TSC;
545   ThreadStorageClassSpecLoc = Loc;
546   return false;
547 }
548 
549 /// These methods set the specified attribute of the DeclSpec, but return true
550 /// and ignore the request if invalid (e.g. "extern" then "auto" is
551 /// specified).
552 bool DeclSpec::SetTypeSpecWidth(TSW W, SourceLocation Loc,
553                                 const char *&PrevSpec,
554                                 unsigned &DiagID) {
555   // Overwrite TSWLoc only if TypeSpecWidth was unspecified, so that
556   // for 'long long' we will keep the source location of the first 'long'.
557   if (TypeSpecWidth == TSW_unspecified)
558     TSWLoc = Loc;
559   // Allow turning long -> long long.
560   else if (W != TSW_longlong || TypeSpecWidth != TSW_long)
561     return BadSpecifier(W, (TSW)TypeSpecWidth, PrevSpec, DiagID);
562   TypeSpecWidth = W;
563   if (TypeAltiVecVector && !TypeAltiVecBool &&
564       ((TypeSpecWidth == TSW_long) || (TypeSpecWidth == TSW_longlong))) {
565     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
566     DiagID = diag::warn_vector_long_decl_spec_combination;
567     return true;
568   }
569   return false;
570 }
571 
572 bool DeclSpec::SetTypeSpecComplex(TSC C, SourceLocation Loc,
573                                   const char *&PrevSpec,
574                                   unsigned &DiagID) {
575   if (TypeSpecComplex != TSC_unspecified)
576     return BadSpecifier(C, (TSC)TypeSpecComplex, PrevSpec, DiagID);
577   TypeSpecComplex = C;
578   TSCLoc = Loc;
579   return false;
580 }
581 
582 bool DeclSpec::SetTypeSpecSign(TSS S, SourceLocation Loc,
583                                const char *&PrevSpec,
584                                unsigned &DiagID) {
585   if (TypeSpecSign != TSS_unspecified)
586     return BadSpecifier(S, (TSS)TypeSpecSign, PrevSpec, DiagID);
587   TypeSpecSign = S;
588   TSSLoc = Loc;
589   return false;
590 }
591 
592 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
593                                const char *&PrevSpec,
594                                unsigned &DiagID,
595                                ParsedType Rep) {
596   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep);
597 }
598 
599 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
600                                SourceLocation TagNameLoc,
601                                const char *&PrevSpec,
602                                unsigned &DiagID,
603                                ParsedType Rep) {
604   assert(isTypeRep(T) && "T does not store a type");
605   assert(Rep && "no type provided!");
606   if (TypeSpecType != TST_unspecified) {
607     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
608     DiagID = diag::err_invalid_decl_spec_combination;
609     return true;
610   }
611   TypeSpecType = T;
612   TypeRep = Rep;
613   TSTLoc = TagKwLoc;
614   TSTNameLoc = TagNameLoc;
615   TypeSpecOwned = false;
616   return false;
617 }
618 
619 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
620                                const char *&PrevSpec,
621                                unsigned &DiagID,
622                                Expr *Rep) {
623   assert(isExprRep(T) && "T does not store an expr");
624   assert(Rep && "no expression provided!");
625   if (TypeSpecType != TST_unspecified) {
626     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
627     DiagID = diag::err_invalid_decl_spec_combination;
628     return true;
629   }
630   TypeSpecType = T;
631   ExprRep = Rep;
632   TSTLoc = Loc;
633   TSTNameLoc = Loc;
634   TypeSpecOwned = false;
635   return false;
636 }
637 
638 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
639                                const char *&PrevSpec,
640                                unsigned &DiagID,
641                                Decl *Rep, bool Owned) {
642   return SetTypeSpecType(T, Loc, Loc, PrevSpec, DiagID, Rep, Owned);
643 }
644 
645 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation TagKwLoc,
646                                SourceLocation TagNameLoc,
647                                const char *&PrevSpec,
648                                unsigned &DiagID,
649                                Decl *Rep, bool Owned) {
650   assert(isDeclRep(T) && "T does not store a decl");
651   // Unlike the other cases, we don't assert that we actually get a decl.
652 
653   if (TypeSpecType != TST_unspecified) {
654     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
655     DiagID = diag::err_invalid_decl_spec_combination;
656     return true;
657   }
658   TypeSpecType = T;
659   DeclRep = Rep;
660   TSTLoc = TagKwLoc;
661   TSTNameLoc = TagNameLoc;
662   TypeSpecOwned = Owned && Rep != 0;
663   return false;
664 }
665 
666 bool DeclSpec::SetTypeSpecType(TST T, SourceLocation Loc,
667                                const char *&PrevSpec,
668                                unsigned &DiagID) {
669   assert(!isDeclRep(T) && !isTypeRep(T) && !isExprRep(T) &&
670          "rep required for these type-spec kinds!");
671   if (TypeSpecType != TST_unspecified) {
672     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
673     DiagID = diag::err_invalid_decl_spec_combination;
674     return true;
675   }
676   TSTLoc = Loc;
677   TSTNameLoc = Loc;
678   if (TypeAltiVecVector && (T == TST_bool) && !TypeAltiVecBool) {
679     TypeAltiVecBool = true;
680     return false;
681   }
682   TypeSpecType = T;
683   TypeSpecOwned = false;
684   if (TypeAltiVecVector && !TypeAltiVecBool && (TypeSpecType == TST_double)) {
685     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
686     DiagID = diag::err_invalid_vector_decl_spec;
687     return true;
688   }
689   return false;
690 }
691 
692 bool DeclSpec::SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
693                           const char *&PrevSpec, unsigned &DiagID) {
694   if (TypeSpecType != TST_unspecified) {
695     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
696     DiagID = diag::err_invalid_vector_decl_spec_combination;
697     return true;
698   }
699   TypeAltiVecVector = isAltiVecVector;
700   AltiVecLoc = Loc;
701   return false;
702 }
703 
704 bool DeclSpec::SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
705                           const char *&PrevSpec, unsigned &DiagID) {
706   if (!TypeAltiVecVector || TypeAltiVecPixel ||
707       (TypeSpecType != TST_unspecified)) {
708     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
709     DiagID = diag::err_invalid_pixel_decl_spec_combination;
710     return true;
711   }
712   TypeAltiVecPixel = isAltiVecPixel;
713   TSTLoc = Loc;
714   TSTNameLoc = Loc;
715   return false;
716 }
717 
718 bool DeclSpec::SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
719                           const char *&PrevSpec, unsigned &DiagID) {
720   if (!TypeAltiVecVector || TypeAltiVecBool ||
721       (TypeSpecType != TST_unspecified)) {
722     PrevSpec = DeclSpec::getSpecifierName((TST) TypeSpecType);
723     DiagID = diag::err_invalid_vector_bool_decl_spec;
724     return true;
725   }
726   TypeAltiVecBool = isAltiVecBool;
727   TSTLoc = Loc;
728   TSTNameLoc = Loc;
729   return false;
730 }
731 
732 bool DeclSpec::SetTypeSpecError() {
733   TypeSpecType = TST_error;
734   TypeSpecOwned = false;
735   TSTLoc = SourceLocation();
736   TSTNameLoc = SourceLocation();
737   return false;
738 }
739 
740 bool DeclSpec::SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
741                            unsigned &DiagID, const LangOptions &Lang) {
742   // Duplicates are permitted in C99, but are not permitted in C++. However,
743   // since this is likely not what the user intended, we will always warn.  We
744   // do not need to set the qualifier's location since we already have it.
745   if (TypeQualifiers & T) {
746     bool IsExtension = true;
747     if (Lang.C99)
748       IsExtension = false;
749     return BadSpecifier(T, T, PrevSpec, DiagID, IsExtension);
750   }
751   TypeQualifiers |= T;
752 
753   switch (T) {
754   case TQ_unspecified: break;
755   case TQ_const:    TQ_constLoc = Loc; return false;
756   case TQ_restrict: TQ_restrictLoc = Loc; return false;
757   case TQ_volatile: TQ_volatileLoc = Loc; return false;
758   case TQ_atomic:   TQ_atomicLoc = Loc; return false;
759   }
760 
761   llvm_unreachable("Unknown type qualifier!");
762 }
763 
764 bool DeclSpec::setFunctionSpecInline(SourceLocation Loc) {
765   // 'inline inline' is ok.
766   FS_inline_specified = true;
767   FS_inlineLoc = Loc;
768   return false;
769 }
770 
771 bool DeclSpec::setFunctionSpecVirtual(SourceLocation Loc) {
772   // 'virtual virtual' is ok.
773   FS_virtual_specified = true;
774   FS_virtualLoc = Loc;
775   return false;
776 }
777 
778 bool DeclSpec::setFunctionSpecExplicit(SourceLocation Loc) {
779   // 'explicit explicit' is ok.
780   FS_explicit_specified = true;
781   FS_explicitLoc = Loc;
782   return false;
783 }
784 
785 bool DeclSpec::setFunctionSpecNoreturn(SourceLocation Loc) {
786   // '_Noreturn _Noreturn' is ok.
787   FS_noreturn_specified = true;
788   FS_noreturnLoc = Loc;
789   return false;
790 }
791 
792 bool DeclSpec::SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
793                              unsigned &DiagID) {
794   if (Friend_specified) {
795     PrevSpec = "friend";
796     DiagID = diag::ext_duplicate_declspec;
797     return true;
798   }
799 
800   Friend_specified = true;
801   FriendLoc = Loc;
802   return false;
803 }
804 
805 bool DeclSpec::setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
806                                     unsigned &DiagID) {
807   if (isModulePrivateSpecified()) {
808     PrevSpec = "__module_private__";
809     DiagID = diag::ext_duplicate_declspec;
810     return true;
811   }
812 
813   ModulePrivateLoc = Loc;
814   return false;
815 }
816 
817 bool DeclSpec::SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
818                                 unsigned &DiagID) {
819   // 'constexpr constexpr' is ok.
820   Constexpr_specified = true;
821   ConstexprLoc = Loc;
822   return false;
823 }
824 
825 void DeclSpec::setProtocolQualifiers(Decl * const *Protos,
826                                      unsigned NP,
827                                      SourceLocation *ProtoLocs,
828                                      SourceLocation LAngleLoc) {
829   if (NP == 0) return;
830   Decl **ProtoQuals = new Decl*[NP];
831   memcpy(ProtoQuals, Protos, sizeof(Decl*)*NP);
832   ProtocolQualifiers = ProtoQuals;
833   ProtocolLocs = new SourceLocation[NP];
834   memcpy(ProtocolLocs, ProtoLocs, sizeof(SourceLocation)*NP);
835   NumProtocolQualifiers = NP;
836   ProtocolLAngleLoc = LAngleLoc;
837 }
838 
839 void DeclSpec::SaveWrittenBuiltinSpecs() {
840   writtenBS.Sign = getTypeSpecSign();
841   writtenBS.Width = getTypeSpecWidth();
842   writtenBS.Type = getTypeSpecType();
843   // Search the list of attributes for the presence of a mode attribute.
844   writtenBS.ModeAttr = false;
845   AttributeList* attrs = getAttributes().getList();
846   while (attrs) {
847     if (attrs->getKind() == AttributeList::AT_Mode) {
848       writtenBS.ModeAttr = true;
849       break;
850     }
851     attrs = attrs->getNext();
852   }
853 }
854 
855 /// Finish - This does final analysis of the declspec, rejecting things like
856 /// "_Imaginary" (lacking an FP type).  This returns a diagnostic to issue or
857 /// diag::NUM_DIAGNOSTICS if there is no error.  After calling this method,
858 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
859 void DeclSpec::Finish(DiagnosticsEngine &D, Preprocessor &PP) {
860   // Before possibly changing their values, save specs as written.
861   SaveWrittenBuiltinSpecs();
862 
863   // Check the type specifier components first.
864 
865   // If decltype(auto) is used, no other type specifiers are permitted.
866   if (TypeSpecType == TST_decltype_auto &&
867       (TypeSpecWidth != TSW_unspecified ||
868        TypeSpecComplex != TSC_unspecified ||
869        TypeSpecSign != TSS_unspecified ||
870        TypeAltiVecVector || TypeAltiVecPixel || TypeAltiVecBool ||
871        TypeQualifiers)) {
872     const unsigned NumLocs = 8;
873     SourceLocation ExtraLocs[NumLocs] = {
874       TSWLoc, TSCLoc, TSSLoc, AltiVecLoc,
875       TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc
876     };
877     FixItHint Hints[NumLocs];
878     SourceLocation FirstLoc;
879     for (unsigned I = 0; I != NumLocs; ++I) {
880       if (!ExtraLocs[I].isInvalid()) {
881         if (FirstLoc.isInvalid() ||
882             PP.getSourceManager().isBeforeInTranslationUnit(ExtraLocs[I],
883                                                             FirstLoc))
884           FirstLoc = ExtraLocs[I];
885         Hints[I] = FixItHint::CreateRemoval(ExtraLocs[I]);
886       }
887     }
888     TypeSpecWidth = TSW_unspecified;
889     TypeSpecComplex = TSC_unspecified;
890     TypeSpecSign = TSS_unspecified;
891     TypeAltiVecVector = TypeAltiVecPixel = TypeAltiVecBool = false;
892     TypeQualifiers = 0;
893     Diag(D, TSTLoc, diag::err_decltype_auto_cannot_be_combined)
894       << Hints[0] << Hints[1] << Hints[2] << Hints[3]
895       << Hints[4] << Hints[5] << Hints[6] << Hints[7];
896   }
897 
898   // Validate and finalize AltiVec vector declspec.
899   if (TypeAltiVecVector) {
900     if (TypeAltiVecBool) {
901       // Sign specifiers are not allowed with vector bool. (PIM 2.1)
902       if (TypeSpecSign != TSS_unspecified) {
903         Diag(D, TSSLoc, diag::err_invalid_vector_bool_decl_spec)
904           << getSpecifierName((TSS)TypeSpecSign);
905       }
906 
907       // Only char/int are valid with vector bool. (PIM 2.1)
908       if (((TypeSpecType != TST_unspecified) && (TypeSpecType != TST_char) &&
909            (TypeSpecType != TST_int)) || TypeAltiVecPixel) {
910         Diag(D, TSTLoc, diag::err_invalid_vector_bool_decl_spec)
911           << (TypeAltiVecPixel ? "__pixel" :
912                                  getSpecifierName((TST)TypeSpecType));
913       }
914 
915       // Only 'short' is valid with vector bool. (PIM 2.1)
916       if ((TypeSpecWidth != TSW_unspecified) && (TypeSpecWidth != TSW_short))
917         Diag(D, TSWLoc, diag::err_invalid_vector_bool_decl_spec)
918           << getSpecifierName((TSW)TypeSpecWidth);
919 
920       // Elements of vector bool are interpreted as unsigned. (PIM 2.1)
921       if ((TypeSpecType == TST_char) || (TypeSpecType == TST_int) ||
922           (TypeSpecWidth != TSW_unspecified))
923         TypeSpecSign = TSS_unsigned;
924     }
925 
926     if (TypeAltiVecPixel) {
927       //TODO: perform validation
928       TypeSpecType = TST_int;
929       TypeSpecSign = TSS_unsigned;
930       TypeSpecWidth = TSW_short;
931       TypeSpecOwned = false;
932     }
933   }
934 
935   // signed/unsigned are only valid with int/char/wchar_t.
936   if (TypeSpecSign != TSS_unspecified) {
937     if (TypeSpecType == TST_unspecified)
938       TypeSpecType = TST_int; // unsigned -> unsigned int, signed -> signed int.
939     else if (TypeSpecType != TST_int  && TypeSpecType != TST_int128 &&
940              TypeSpecType != TST_char && TypeSpecType != TST_wchar) {
941       Diag(D, TSSLoc, diag::err_invalid_sign_spec)
942         << getSpecifierName((TST)TypeSpecType);
943       // signed double -> double.
944       TypeSpecSign = TSS_unspecified;
945     }
946   }
947 
948   // Validate the width of the type.
949   switch (TypeSpecWidth) {
950   case TSW_unspecified: break;
951   case TSW_short:    // short int
952   case TSW_longlong: // long long int
953     if (TypeSpecType == TST_unspecified)
954       TypeSpecType = TST_int; // short -> short int, long long -> long long int.
955     else if (TypeSpecType != TST_int) {
956       Diag(D, TSWLoc,
957            TypeSpecWidth == TSW_short ? diag::err_invalid_short_spec
958                                       : diag::err_invalid_longlong_spec)
959         <<  getSpecifierName((TST)TypeSpecType);
960       TypeSpecType = TST_int;
961       TypeSpecOwned = false;
962     }
963     break;
964   case TSW_long:  // long double, long int
965     if (TypeSpecType == TST_unspecified)
966       TypeSpecType = TST_int;  // long -> long int.
967     else if (TypeSpecType != TST_int && TypeSpecType != TST_double) {
968       Diag(D, TSWLoc, diag::err_invalid_long_spec)
969         << getSpecifierName((TST)TypeSpecType);
970       TypeSpecType = TST_int;
971       TypeSpecOwned = false;
972     }
973     break;
974   }
975 
976   // TODO: if the implementation does not implement _Complex or _Imaginary,
977   // disallow their use.  Need information about the backend.
978   if (TypeSpecComplex != TSC_unspecified) {
979     if (TypeSpecType == TST_unspecified) {
980       Diag(D, TSCLoc, diag::ext_plain_complex)
981         << FixItHint::CreateInsertion(
982                               PP.getLocForEndOfToken(getTypeSpecComplexLoc()),
983                                                  " double");
984       TypeSpecType = TST_double;   // _Complex -> _Complex double.
985     } else if (TypeSpecType == TST_int || TypeSpecType == TST_char) {
986       // Note that this intentionally doesn't include _Complex _Bool.
987       if (!PP.getLangOpts().CPlusPlus)
988         Diag(D, TSTLoc, diag::ext_integer_complex);
989     } else if (TypeSpecType != TST_float && TypeSpecType != TST_double) {
990       Diag(D, TSCLoc, diag::err_invalid_complex_spec)
991         << getSpecifierName((TST)TypeSpecType);
992       TypeSpecComplex = TSC_unspecified;
993     }
994   }
995 
996   // C11 6.7.1/3, C++11 [dcl.stc]p1, GNU TLS: __thread, thread_local and
997   // _Thread_local can only appear with the 'static' and 'extern' storage class
998   // specifiers. We also allow __private_extern__ as an extension.
999   if (ThreadStorageClassSpec != TSCS_unspecified) {
1000     switch (StorageClassSpec) {
1001     case SCS_unspecified:
1002     case SCS_extern:
1003     case SCS_private_extern:
1004     case SCS_static:
1005       break;
1006     default:
1007       if (PP.getSourceManager().isBeforeInTranslationUnit(
1008             getThreadStorageClassSpecLoc(), getStorageClassSpecLoc()))
1009         Diag(D, getStorageClassSpecLoc(),
1010              diag::err_invalid_decl_spec_combination)
1011           << DeclSpec::getSpecifierName(getThreadStorageClassSpec())
1012           << SourceRange(getThreadStorageClassSpecLoc());
1013       else
1014         Diag(D, getThreadStorageClassSpecLoc(),
1015              diag::err_invalid_decl_spec_combination)
1016           << DeclSpec::getSpecifierName(getStorageClassSpec())
1017           << SourceRange(getStorageClassSpecLoc());
1018       // Discard the thread storage class specifier to recover.
1019       ThreadStorageClassSpec = TSCS_unspecified;
1020       ThreadStorageClassSpecLoc = SourceLocation();
1021     }
1022   }
1023 
1024   // If no type specifier was provided and we're parsing a language where
1025   // the type specifier is not optional, but we got 'auto' as a storage
1026   // class specifier, then assume this is an attempt to use C++0x's 'auto'
1027   // type specifier.
1028   if (PP.getLangOpts().CPlusPlus &&
1029       TypeSpecType == TST_unspecified && StorageClassSpec == SCS_auto) {
1030     TypeSpecType = TST_auto;
1031     StorageClassSpec = SCS_unspecified;
1032     TSTLoc = TSTNameLoc = StorageClassSpecLoc;
1033     StorageClassSpecLoc = SourceLocation();
1034   }
1035   // Diagnose if we've recovered from an ill-formed 'auto' storage class
1036   // specifier in a pre-C++11 dialect of C++.
1037   if (!PP.getLangOpts().CPlusPlus11 && TypeSpecType == TST_auto)
1038     Diag(D, TSTLoc, diag::ext_auto_type_specifier);
1039   if (PP.getLangOpts().CPlusPlus && !PP.getLangOpts().CPlusPlus11 &&
1040       StorageClassSpec == SCS_auto)
1041     Diag(D, StorageClassSpecLoc, diag::warn_auto_storage_class)
1042       << FixItHint::CreateRemoval(StorageClassSpecLoc);
1043   if (TypeSpecType == TST_char16 || TypeSpecType == TST_char32)
1044     Diag(D, TSTLoc, diag::warn_cxx98_compat_unicode_type)
1045       << (TypeSpecType == TST_char16 ? "char16_t" : "char32_t");
1046   if (Constexpr_specified)
1047     Diag(D, ConstexprLoc, diag::warn_cxx98_compat_constexpr);
1048 
1049   // C++ [class.friend]p6:
1050   //   No storage-class-specifier shall appear in the decl-specifier-seq
1051   //   of a friend declaration.
1052   if (isFriendSpecified() &&
1053       (getStorageClassSpec() || getThreadStorageClassSpec())) {
1054     SmallString<32> SpecName;
1055     SourceLocation SCLoc;
1056     FixItHint StorageHint, ThreadHint;
1057 
1058     if (DeclSpec::SCS SC = getStorageClassSpec()) {
1059       SpecName = getSpecifierName(SC);
1060       SCLoc = getStorageClassSpecLoc();
1061       StorageHint = FixItHint::CreateRemoval(SCLoc);
1062     }
1063 
1064     if (DeclSpec::TSCS TSC = getThreadStorageClassSpec()) {
1065       if (!SpecName.empty()) SpecName += " ";
1066       SpecName += getSpecifierName(TSC);
1067       SCLoc = getThreadStorageClassSpecLoc();
1068       ThreadHint = FixItHint::CreateRemoval(SCLoc);
1069     }
1070 
1071     Diag(D, SCLoc, diag::err_friend_storage_spec)
1072       << SpecName << StorageHint << ThreadHint;
1073 
1074     ClearStorageClassSpecs();
1075   }
1076 
1077   assert(!TypeSpecOwned || isDeclRep((TST) TypeSpecType));
1078 
1079   // Okay, now we can infer the real type.
1080 
1081   // TODO: return "auto function" and other bad things based on the real type.
1082 
1083   // 'data definition has no type or storage class'?
1084 }
1085 
1086 bool DeclSpec::isMissingDeclaratorOk() {
1087   TST tst = getTypeSpecType();
1088   return isDeclRep(tst) && getRepAsDecl() != 0 &&
1089     StorageClassSpec != DeclSpec::SCS_typedef;
1090 }
1091 
1092 void UnqualifiedId::setOperatorFunctionId(SourceLocation OperatorLoc,
1093                                           OverloadedOperatorKind Op,
1094                                           SourceLocation SymbolLocations[3]) {
1095   Kind = IK_OperatorFunctionId;
1096   StartLocation = OperatorLoc;
1097   EndLocation = OperatorLoc;
1098   OperatorFunctionId.Operator = Op;
1099   for (unsigned I = 0; I != 3; ++I) {
1100     OperatorFunctionId.SymbolLocations[I] = SymbolLocations[I].getRawEncoding();
1101 
1102     if (SymbolLocations[I].isValid())
1103       EndLocation = SymbolLocations[I];
1104   }
1105 }
1106 
1107 bool VirtSpecifiers::SetSpecifier(Specifier VS, SourceLocation Loc,
1108                                   const char *&PrevSpec) {
1109   LastLocation = Loc;
1110 
1111   if (Specifiers & VS) {
1112     PrevSpec = getSpecifierName(VS);
1113     return true;
1114   }
1115 
1116   Specifiers |= VS;
1117 
1118   switch (VS) {
1119   default: llvm_unreachable("Unknown specifier!");
1120   case VS_Override: VS_overrideLoc = Loc; break;
1121   case VS_Sealed:
1122   case VS_Final:    VS_finalLoc = Loc; break;
1123   }
1124 
1125   return false;
1126 }
1127 
1128 const char *VirtSpecifiers::getSpecifierName(Specifier VS) {
1129   switch (VS) {
1130   default: llvm_unreachable("Unknown specifier");
1131   case VS_Override: return "override";
1132   case VS_Final: return "final";
1133   case VS_Sealed: return "sealed";
1134   }
1135 }
1136