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