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