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