SemaType.cpp revision 6e132aab867c189b1c3ee7463ef9d2b1f03a294d
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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 type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/TypeLocVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Parse/DeclSpec.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/Support/ErrorHandling.h"
26using namespace clang;
27
28/// \brief Perform adjustment on the parameter type of a function.
29///
30/// This routine adjusts the given parameter type @p T to the actual
31/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
32/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
33QualType Sema::adjustParameterType(QualType T) {
34  // C99 6.7.5.3p7:
35  //   A declaration of a parameter as "array of type" shall be
36  //   adjusted to "qualified pointer to type", where the type
37  //   qualifiers (if any) are those specified within the [ and ] of
38  //   the array type derivation.
39  if (T->isArrayType())
40    return Context.getArrayDecayedType(T);
41
42  // C99 6.7.5.3p8:
43  //   A declaration of a parameter as "function returning type"
44  //   shall be adjusted to "pointer to function returning type", as
45  //   in 6.3.2.1.
46  if (T->isFunctionType())
47    return Context.getPointerType(T);
48
49  return T;
50}
51
52
53
54/// isOmittedBlockReturnType - Return true if this declarator is missing a
55/// return type because this is a omitted return type on a block literal.
56static bool isOmittedBlockReturnType(const Declarator &D) {
57  if (D.getContext() != Declarator::BlockLiteralContext ||
58      D.getDeclSpec().hasTypeSpecifier())
59    return false;
60
61  if (D.getNumTypeObjects() == 0)
62    return true;   // ^{ ... }
63
64  if (D.getNumTypeObjects() == 1 &&
65      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
66    return true;   // ^(int X, float Y) { ... }
67
68  return false;
69}
70
71/// \brief Convert the specified declspec to the appropriate type
72/// object.
73/// \param D  the declarator containing the declaration specifier.
74/// \returns The type described by the declaration specifiers.  This function
75/// never returns null.
76static QualType ConvertDeclSpecToType(Declarator &TheDeclarator, Sema &TheSema){
77  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
78  // checking.
79  const DeclSpec &DS = TheDeclarator.getDeclSpec();
80  SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
81  if (DeclLoc.isInvalid())
82    DeclLoc = DS.getSourceRange().getBegin();
83
84  ASTContext &Context = TheSema.Context;
85
86  QualType Result;
87  switch (DS.getTypeSpecType()) {
88  case DeclSpec::TST_void:
89    Result = Context.VoidTy;
90    break;
91  case DeclSpec::TST_char:
92    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
93      Result = Context.CharTy;
94    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
95      Result = Context.SignedCharTy;
96    else {
97      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
98             "Unknown TSS value");
99      Result = Context.UnsignedCharTy;
100    }
101    break;
102  case DeclSpec::TST_wchar:
103    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
104      Result = Context.WCharTy;
105    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
106      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
107        << DS.getSpecifierName(DS.getTypeSpecType());
108      Result = Context.getSignedWCharType();
109    } else {
110      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
111        "Unknown TSS value");
112      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
113        << DS.getSpecifierName(DS.getTypeSpecType());
114      Result = Context.getUnsignedWCharType();
115    }
116    break;
117  case DeclSpec::TST_char16:
118      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
119        "Unknown TSS value");
120      Result = Context.Char16Ty;
121    break;
122  case DeclSpec::TST_char32:
123      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
124        "Unknown TSS value");
125      Result = Context.Char32Ty;
126    break;
127  case DeclSpec::TST_unspecified:
128    // "<proto1,proto2>" is an objc qualified ID with a missing id.
129    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
130      Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
131                                                (ObjCProtocolDecl**)PQ,
132                                                DS.getNumProtocolQualifiers());
133      break;
134    }
135
136    // If this is a missing declspec in a block literal return context, then it
137    // is inferred from the return statements inside the block.
138    if (isOmittedBlockReturnType(TheDeclarator)) {
139      Result = Context.DependentTy;
140      break;
141    }
142
143    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
144    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
145    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
146    // Note that the one exception to this is function definitions, which are
147    // allowed to be completely missing a declspec.  This is handled in the
148    // parser already though by it pretending to have seen an 'int' in this
149    // case.
150    if (TheSema.getLangOptions().ImplicitInt) {
151      // In C89 mode, we only warn if there is a completely missing declspec
152      // when one is not allowed.
153      if (DS.isEmpty()) {
154        TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
155          << DS.getSourceRange()
156        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
157                                                 "int");
158      }
159    } else if (!DS.hasTypeSpecifier()) {
160      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
161      // "At least one type specifier shall be given in the declaration
162      // specifiers in each declaration, and in the specifier-qualifier list in
163      // each struct declaration and type name."
164      // FIXME: Does Microsoft really have the implicit int extension in C++?
165      if (TheSema.getLangOptions().CPlusPlus &&
166          !TheSema.getLangOptions().Microsoft) {
167        TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
168          << DS.getSourceRange();
169
170        // When this occurs in C++ code, often something is very broken with the
171        // value being declared, poison it as invalid so we don't get chains of
172        // errors.
173        TheDeclarator.setInvalidType(true);
174      } else {
175        TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
176          << DS.getSourceRange();
177      }
178    }
179
180    // FALL THROUGH.
181  case DeclSpec::TST_int: {
182    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
183      switch (DS.getTypeSpecWidth()) {
184      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
185      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
186      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
187      case DeclSpec::TSW_longlong:
188        Result = Context.LongLongTy;
189
190        // long long is a C99 feature.
191        if (!TheSema.getLangOptions().C99 &&
192            !TheSema.getLangOptions().CPlusPlus0x)
193          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
194        break;
195      }
196    } else {
197      switch (DS.getTypeSpecWidth()) {
198      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
199      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
200      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
201      case DeclSpec::TSW_longlong:
202        Result = Context.UnsignedLongLongTy;
203
204        // long long is a C99 feature.
205        if (!TheSema.getLangOptions().C99 &&
206            !TheSema.getLangOptions().CPlusPlus0x)
207          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
208        break;
209      }
210    }
211    break;
212  }
213  case DeclSpec::TST_float: Result = Context.FloatTy; break;
214  case DeclSpec::TST_double:
215    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
216      Result = Context.LongDoubleTy;
217    else
218      Result = Context.DoubleTy;
219    break;
220  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
221  case DeclSpec::TST_decimal32:    // _Decimal32
222  case DeclSpec::TST_decimal64:    // _Decimal64
223  case DeclSpec::TST_decimal128:   // _Decimal128
224    TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
225    Result = Context.IntTy;
226    TheDeclarator.setInvalidType(true);
227    break;
228  case DeclSpec::TST_class:
229  case DeclSpec::TST_enum:
230  case DeclSpec::TST_union:
231  case DeclSpec::TST_struct: {
232    TypeDecl *D
233      = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
234    if (!D) {
235      // This can happen in C++ with ambiguous lookups.
236      Result = Context.IntTy;
237      TheDeclarator.setInvalidType(true);
238      break;
239    }
240
241    // If the type is deprecated or unavailable, diagnose it.
242    TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
243
244    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
245           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
246
247    // TypeQuals handled by caller.
248    Result = Context.getTypeDeclType(D);
249
250    // In C++, make an ElaboratedType.
251    if (TheSema.getLangOptions().CPlusPlus) {
252      TagDecl::TagKind Tag
253        = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType());
254      Result = Context.getElaboratedType(Result, Tag);
255    }
256
257    if (D->isInvalidDecl())
258      TheDeclarator.setInvalidType(true);
259    break;
260  }
261  case DeclSpec::TST_typename: {
262    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
263           DS.getTypeSpecSign() == 0 &&
264           "Can't handle qualifiers on typedef names yet!");
265    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
266
267    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
268      if (const ObjCInterfaceType *
269            Interface = Result->getAs<ObjCInterfaceType>()) {
270        // It would be nice if protocol qualifiers were only stored with the
271        // ObjCObjectPointerType. Unfortunately, this isn't possible due
272        // to the following typedef idiom (which is uncommon, but allowed):
273        //
274        // typedef Foo<P> T;
275        // static void func() {
276        //   Foo<P> *yy;
277        //   T *zz;
278        // }
279        Result = Context.getObjCInterfaceType(Interface->getDecl(),
280                                              (ObjCProtocolDecl**)PQ,
281                                              DS.getNumProtocolQualifiers());
282      } else if (Result->isObjCIdType())
283        // id<protocol-list>
284        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
285                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
286      else if (Result->isObjCClassType()) {
287        // Class<protocol-list>
288        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
289                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
290      } else {
291        TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
292          << DS.getSourceRange();
293        TheDeclarator.setInvalidType(true);
294      }
295    }
296
297    // TypeQuals handled by caller.
298    break;
299  }
300  case DeclSpec::TST_typeofType:
301    // FIXME: Preserve type source info.
302    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
303    assert(!Result.isNull() && "Didn't get a type for typeof?");
304    // TypeQuals handled by caller.
305    Result = Context.getTypeOfType(Result);
306    break;
307  case DeclSpec::TST_typeofExpr: {
308    Expr *E = static_cast<Expr *>(DS.getTypeRep());
309    assert(E && "Didn't get an expression for typeof?");
310    // TypeQuals handled by caller.
311    Result = Context.getTypeOfExprType(E);
312    break;
313  }
314  case DeclSpec::TST_decltype: {
315    Expr *E = static_cast<Expr *>(DS.getTypeRep());
316    assert(E && "Didn't get an expression for decltype?");
317    // TypeQuals handled by caller.
318    Result = TheSema.BuildDecltypeType(E);
319    if (Result.isNull()) {
320      Result = Context.IntTy;
321      TheDeclarator.setInvalidType(true);
322    }
323    break;
324  }
325  case DeclSpec::TST_auto: {
326    // TypeQuals handled by caller.
327    Result = Context.UndeducedAutoTy;
328    break;
329  }
330
331  case DeclSpec::TST_error:
332    Result = Context.IntTy;
333    TheDeclarator.setInvalidType(true);
334    break;
335  }
336
337  // Handle complex types.
338  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
339    if (TheSema.getLangOptions().Freestanding)
340      TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
341    Result = Context.getComplexType(Result);
342  }
343
344  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
345         "FIXME: imaginary types not supported yet!");
346
347  // See if there are any attributes on the declspec that apply to the type (as
348  // opposed to the decl).
349  if (const AttributeList *AL = DS.getAttributes())
350    TheSema.ProcessTypeAttributeList(Result, AL);
351
352  // Apply const/volatile/restrict qualifiers to T.
353  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
354
355    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
356    // or incomplete types shall not be restrict-qualified."  C++ also allows
357    // restrict-qualified references.
358    if (TypeQuals & DeclSpec::TQ_restrict) {
359      if (Result->isPointerType() || Result->isReferenceType()) {
360        QualType EltTy = Result->isPointerType() ?
361          Result->getAs<PointerType>()->getPointeeType() :
362          Result->getAs<ReferenceType>()->getPointeeType();
363
364        // If we have a pointer or reference, the pointee must have an object
365        // incomplete type.
366        if (!EltTy->isIncompleteOrObjectType()) {
367          TheSema.Diag(DS.getRestrictSpecLoc(),
368               diag::err_typecheck_invalid_restrict_invalid_pointee)
369            << EltTy << DS.getSourceRange();
370          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
371        }
372      } else {
373        TheSema.Diag(DS.getRestrictSpecLoc(),
374             diag::err_typecheck_invalid_restrict_not_pointer)
375          << Result << DS.getSourceRange();
376        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
377      }
378    }
379
380    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
381    // of a function type includes any type qualifiers, the behavior is
382    // undefined."
383    if (Result->isFunctionType() && TypeQuals) {
384      // Get some location to point at, either the C or V location.
385      SourceLocation Loc;
386      if (TypeQuals & DeclSpec::TQ_const)
387        Loc = DS.getConstSpecLoc();
388      else if (TypeQuals & DeclSpec::TQ_volatile)
389        Loc = DS.getVolatileSpecLoc();
390      else {
391        assert((TypeQuals & DeclSpec::TQ_restrict) &&
392               "Has CVR quals but not C, V, or R?");
393        Loc = DS.getRestrictSpecLoc();
394      }
395      TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
396        << Result << DS.getSourceRange();
397    }
398
399    // C++ [dcl.ref]p1:
400    //   Cv-qualified references are ill-formed except when the
401    //   cv-qualifiers are introduced through the use of a typedef
402    //   (7.1.3) or of a template type argument (14.3), in which
403    //   case the cv-qualifiers are ignored.
404    // FIXME: Shouldn't we be checking SCS_typedef here?
405    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
406        TypeQuals && Result->isReferenceType()) {
407      TypeQuals &= ~DeclSpec::TQ_const;
408      TypeQuals &= ~DeclSpec::TQ_volatile;
409    }
410
411    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
412    Result = Context.getQualifiedType(Result, Quals);
413  }
414
415  return Result;
416}
417
418static std::string getPrintableNameForEntity(DeclarationName Entity) {
419  if (Entity)
420    return Entity.getAsString();
421
422  return "type name";
423}
424
425/// \brief Build a pointer type.
426///
427/// \param T The type to which we'll be building a pointer.
428///
429/// \param Quals The cvr-qualifiers to be applied to the pointer type.
430///
431/// \param Loc The location of the entity whose type involves this
432/// pointer type or, if there is no such entity, the location of the
433/// type that will have pointer type.
434///
435/// \param Entity The name of the entity that involves the pointer
436/// type, if known.
437///
438/// \returns A suitable pointer type, if there are no
439/// errors. Otherwise, returns a NULL type.
440QualType Sema::BuildPointerType(QualType T, unsigned Quals,
441                                SourceLocation Loc, DeclarationName Entity) {
442  if (T->isReferenceType()) {
443    // C++ 8.3.2p4: There shall be no ... pointers to references ...
444    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
445      << getPrintableNameForEntity(Entity) << T;
446    return QualType();
447  }
448
449  Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
450
451  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
452  // object or incomplete types shall not be restrict-qualified."
453  if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
454    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
455      << T;
456    Qs.removeRestrict();
457  }
458
459  // Build the pointer type.
460  return Context.getQualifiedType(Context.getPointerType(T), Qs);
461}
462
463/// \brief Build a reference type.
464///
465/// \param T The type to which we'll be building a reference.
466///
467/// \param CVR The cvr-qualifiers to be applied to the reference type.
468///
469/// \param Loc The location of the entity whose type involves this
470/// reference type or, if there is no such entity, the location of the
471/// type that will have reference type.
472///
473/// \param Entity The name of the entity that involves the reference
474/// type, if known.
475///
476/// \returns A suitable reference type, if there are no
477/// errors. Otherwise, returns a NULL type.
478QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
479                                  unsigned CVR, SourceLocation Loc,
480                                  DeclarationName Entity) {
481  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
482
483  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
484
485  // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
486  //   reference to a type T, and attempt to create the type "lvalue
487  //   reference to cv TD" creates the type "lvalue reference to T".
488  // We use the qualifiers (restrict or none) of the original reference,
489  // not the new ones. This is consistent with GCC.
490
491  // C++ [dcl.ref]p4: There shall be no references to references.
492  //
493  // According to C++ DR 106, references to references are only
494  // diagnosed when they are written directly (e.g., "int & &"),
495  // but not when they happen via a typedef:
496  //
497  //   typedef int& intref;
498  //   typedef intref& intref2;
499  //
500  // Parser::ParseDeclaratorInternal diagnoses the case where
501  // references are written directly; here, we handle the
502  // collapsing of references-to-references as described in C++
503  // DR 106 and amended by C++ DR 540.
504
505  // C++ [dcl.ref]p1:
506  //   A declarator that specifies the type "reference to cv void"
507  //   is ill-formed.
508  if (T->isVoidType()) {
509    Diag(Loc, diag::err_reference_to_void);
510    return QualType();
511  }
512
513  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
514  // object or incomplete types shall not be restrict-qualified."
515  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
516    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
517      << T;
518    Quals.removeRestrict();
519  }
520
521  // C++ [dcl.ref]p1:
522  //   [...] Cv-qualified references are ill-formed except when the
523  //   cv-qualifiers are introduced through the use of a typedef
524  //   (7.1.3) or of a template type argument (14.3), in which case
525  //   the cv-qualifiers are ignored.
526  //
527  // We diagnose extraneous cv-qualifiers for the non-typedef,
528  // non-template type argument case within the parser. Here, we just
529  // ignore any extraneous cv-qualifiers.
530  Quals.removeConst();
531  Quals.removeVolatile();
532
533  // Handle restrict on references.
534  if (LValueRef)
535    return Context.getQualifiedType(
536               Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
537  return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
538}
539
540/// \brief Build an array type.
541///
542/// \param T The type of each element in the array.
543///
544/// \param ASM C99 array size modifier (e.g., '*', 'static').
545///
546/// \param ArraySize Expression describing the size of the array.
547///
548/// \param Quals The cvr-qualifiers to be applied to the array's
549/// element type.
550///
551/// \param Loc The location of the entity whose type involves this
552/// array type or, if there is no such entity, the location of the
553/// type that will have array type.
554///
555/// \param Entity The name of the entity that involves the array
556/// type, if known.
557///
558/// \returns A suitable array type, if there are no errors. Otherwise,
559/// returns a NULL type.
560QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
561                              Expr *ArraySize, unsigned Quals,
562                              SourceRange Brackets, DeclarationName Entity) {
563
564  SourceLocation Loc = Brackets.getBegin();
565  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
566  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
567  // Not in C++, though. There we only dislike void.
568  if (getLangOptions().CPlusPlus) {
569    if (T->isVoidType()) {
570      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
571      return QualType();
572    }
573  } else {
574    if (RequireCompleteType(Loc, T,
575                            diag::err_illegal_decl_array_incomplete_type))
576      return QualType();
577  }
578
579  if (T->isFunctionType()) {
580    Diag(Loc, diag::err_illegal_decl_array_of_functions)
581      << getPrintableNameForEntity(Entity) << T;
582    return QualType();
583  }
584
585  // C++ 8.3.2p4: There shall be no ... arrays of references ...
586  if (T->isReferenceType()) {
587    Diag(Loc, diag::err_illegal_decl_array_of_references)
588      << getPrintableNameForEntity(Entity) << T;
589    return QualType();
590  }
591
592  if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
593    Diag(Loc,  diag::err_illegal_decl_array_of_auto)
594      << getPrintableNameForEntity(Entity);
595    return QualType();
596  }
597
598  if (const RecordType *EltTy = T->getAs<RecordType>()) {
599    // If the element type is a struct or union that contains a variadic
600    // array, accept it as a GNU extension: C99 6.7.2.1p2.
601    if (EltTy->getDecl()->hasFlexibleArrayMember())
602      Diag(Loc, diag::ext_flexible_array_in_array) << T;
603  } else if (T->isObjCInterfaceType()) {
604    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
605    return QualType();
606  }
607
608  // C99 6.7.5.2p1: The size expression shall have integer type.
609  if (ArraySize && !ArraySize->isTypeDependent() &&
610      !ArraySize->getType()->isIntegerType()) {
611    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
612      << ArraySize->getType() << ArraySize->getSourceRange();
613    ArraySize->Destroy(Context);
614    return QualType();
615  }
616  llvm::APSInt ConstVal(32);
617  if (!ArraySize) {
618    if (ASM == ArrayType::Star)
619      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
620    else
621      T = Context.getIncompleteArrayType(T, ASM, Quals);
622  } else if (ArraySize->isValueDependent()) {
623    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
624  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
625             (!T->isDependentType() && !T->isIncompleteType() &&
626              !T->isConstantSizeType())) {
627    // Per C99, a variable array is an array with either a non-constant
628    // size or an element type that has a non-constant-size
629    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
630  } else {
631    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
632    // have a value greater than zero.
633    if (ConstVal.isSigned() && ConstVal.isNegative()) {
634      Diag(ArraySize->getLocStart(),
635           diag::err_typecheck_negative_array_size)
636        << ArraySize->getSourceRange();
637      return QualType();
638    }
639    if (ConstVal == 0) {
640      // GCC accepts zero sized static arrays.
641      Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
642        << ArraySize->getSourceRange();
643    }
644    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
645  }
646  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
647  if (!getLangOptions().C99) {
648    if (ArraySize && !ArraySize->isTypeDependent() &&
649        !ArraySize->isValueDependent() &&
650        !ArraySize->isIntegerConstantExpr(Context))
651      Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla);
652    else if (ASM != ArrayType::Normal || Quals != 0)
653      Diag(Loc,
654           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
655                                     : diag::ext_c99_array_usage);
656  }
657
658  return T;
659}
660
661/// \brief Build an ext-vector type.
662///
663/// Run the required checks for the extended vector type.
664QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
665                                  SourceLocation AttrLoc) {
666
667  Expr *Arg = (Expr *)ArraySize.get();
668
669  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
670  // in conjunction with complex types (pointers, arrays, functions, etc.).
671  if (!T->isDependentType() &&
672      !T->isIntegerType() && !T->isRealFloatingType()) {
673    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
674    return QualType();
675  }
676
677  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
678    llvm::APSInt vecSize(32);
679    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
680      Diag(AttrLoc, diag::err_attribute_argument_not_int)
681      << "ext_vector_type" << Arg->getSourceRange();
682      return QualType();
683    }
684
685    // unlike gcc's vector_size attribute, the size is specified as the
686    // number of elements, not the number of bytes.
687    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
688
689    if (vectorSize == 0) {
690      Diag(AttrLoc, diag::err_attribute_zero_size)
691      << Arg->getSourceRange();
692      return QualType();
693    }
694
695    if (!T->isDependentType())
696      return Context.getExtVectorType(T, vectorSize);
697  }
698
699  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
700                                                AttrLoc);
701}
702
703/// \brief Build a function type.
704///
705/// This routine checks the function type according to C++ rules and
706/// under the assumption that the result type and parameter types have
707/// just been instantiated from a template. It therefore duplicates
708/// some of the behavior of GetTypeForDeclarator, but in a much
709/// simpler form that is only suitable for this narrow use case.
710///
711/// \param T The return type of the function.
712///
713/// \param ParamTypes The parameter types of the function. This array
714/// will be modified to account for adjustments to the types of the
715/// function parameters.
716///
717/// \param NumParamTypes The number of parameter types in ParamTypes.
718///
719/// \param Variadic Whether this is a variadic function type.
720///
721/// \param Quals The cvr-qualifiers to be applied to the function type.
722///
723/// \param Loc The location of the entity whose type involves this
724/// function type or, if there is no such entity, the location of the
725/// type that will have function type.
726///
727/// \param Entity The name of the entity that involves the function
728/// type, if known.
729///
730/// \returns A suitable function type, if there are no
731/// errors. Otherwise, returns a NULL type.
732QualType Sema::BuildFunctionType(QualType T,
733                                 QualType *ParamTypes,
734                                 unsigned NumParamTypes,
735                                 bool Variadic, unsigned Quals,
736                                 SourceLocation Loc, DeclarationName Entity) {
737  if (T->isArrayType() || T->isFunctionType()) {
738    Diag(Loc, diag::err_func_returning_array_function) << T;
739    return QualType();
740  }
741
742  bool Invalid = false;
743  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
744    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
745    if (ParamType->isVoidType()) {
746      Diag(Loc, diag::err_param_with_void_type);
747      Invalid = true;
748    }
749
750    ParamTypes[Idx] = ParamType;
751  }
752
753  if (Invalid)
754    return QualType();
755
756  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
757                                 Quals);
758}
759
760/// \brief Build a member pointer type \c T Class::*.
761///
762/// \param T the type to which the member pointer refers.
763/// \param Class the class type into which the member pointer points.
764/// \param CVR Qualifiers applied to the member pointer type
765/// \param Loc the location where this type begins
766/// \param Entity the name of the entity that will have this member pointer type
767///
768/// \returns a member pointer type, if successful, or a NULL type if there was
769/// an error.
770QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
771                                      unsigned CVR, SourceLocation Loc,
772                                      DeclarationName Entity) {
773  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
774
775  // Verify that we're not building a pointer to pointer to function with
776  // exception specification.
777  if (CheckDistantExceptionSpec(T)) {
778    Diag(Loc, diag::err_distant_exception_spec);
779
780    // FIXME: If we're doing this as part of template instantiation,
781    // we should return immediately.
782
783    // Build the type anyway, but use the canonical type so that the
784    // exception specifiers are stripped off.
785    T = Context.getCanonicalType(T);
786  }
787
788  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
789  //   with reference type, or "cv void."
790  if (T->isReferenceType()) {
791    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
792      << (Entity? Entity.getAsString() : "type name") << T;
793    return QualType();
794  }
795
796  if (T->isVoidType()) {
797    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
798      << (Entity? Entity.getAsString() : "type name");
799    return QualType();
800  }
801
802  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
803  // object or incomplete types shall not be restrict-qualified."
804  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
805    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
806      << T;
807
808    // FIXME: If we're doing this as part of template instantiation,
809    // we should return immediately.
810    Quals.removeRestrict();
811  }
812
813  if (!Class->isDependentType() && !Class->isRecordType()) {
814    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
815    return QualType();
816  }
817
818  return Context.getQualifiedType(
819           Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
820}
821
822/// \brief Build a block pointer type.
823///
824/// \param T The type to which we'll be building a block pointer.
825///
826/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
827///
828/// \param Loc The location of the entity whose type involves this
829/// block pointer type or, if there is no such entity, the location of the
830/// type that will have block pointer type.
831///
832/// \param Entity The name of the entity that involves the block pointer
833/// type, if known.
834///
835/// \returns A suitable block pointer type, if there are no
836/// errors. Otherwise, returns a NULL type.
837QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
838                                     SourceLocation Loc,
839                                     DeclarationName Entity) {
840  if (!T->isFunctionType()) {
841    Diag(Loc, diag::err_nonfunction_block_type);
842    return QualType();
843  }
844
845  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
846  return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
847}
848
849QualType Sema::GetTypeFromParser(TypeTy *Ty, DeclaratorInfo **DInfo) {
850  QualType QT = QualType::getFromOpaquePtr(Ty);
851  if (QT.isNull()) {
852    if (DInfo) *DInfo = 0;
853    return QualType();
854  }
855
856  DeclaratorInfo *DI = 0;
857  if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
858    QT = LIT->getType();
859    DI = LIT->getDeclaratorInfo();
860  }
861
862  if (DInfo) *DInfo = DI;
863  return QT;
864}
865
866/// GetTypeForDeclarator - Convert the type for the specified
867/// declarator to Type instances.
868///
869/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
870/// owns the declaration of a type (e.g., the definition of a struct
871/// type), then *OwnedDecl will receive the owned declaration.
872QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
873                                    DeclaratorInfo **DInfo,
874                                    TagDecl **OwnedDecl) {
875  // Determine the type of the declarator. Not all forms of declarator
876  // have a type.
877  QualType T;
878
879  switch (D.getName().getKind()) {
880  case UnqualifiedId::IK_Identifier:
881  case UnqualifiedId::IK_OperatorFunctionId:
882  case UnqualifiedId::IK_LiteralOperatorId:
883  case UnqualifiedId::IK_TemplateId:
884    T = ConvertDeclSpecToType(D, *this);
885
886    if (!D.isInvalidType() && OwnedDecl && D.getDeclSpec().isTypeSpecOwned())
887      *OwnedDecl = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
888    break;
889
890  case UnqualifiedId::IK_ConstructorName:
891  case UnqualifiedId::IK_DestructorName:
892  case UnqualifiedId::IK_ConversionFunctionId:
893    // Constructors and destructors don't have return types. Use
894    // "void" instead. Conversion operators will check their return
895    // types separately.
896    T = Context.VoidTy;
897    break;
898  }
899
900  if (T.isNull())
901    return T;
902
903  if (T == Context.UndeducedAutoTy) {
904    int Error = -1;
905
906    switch (D.getContext()) {
907    case Declarator::KNRTypeListContext:
908      assert(0 && "K&R type lists aren't allowed in C++");
909      break;
910    case Declarator::PrototypeContext:
911      Error = 0; // Function prototype
912      break;
913    case Declarator::MemberContext:
914      switch (cast<TagDecl>(CurContext)->getTagKind()) {
915      case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
916      case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
917      case TagDecl::TK_union:  Error = 2; /* Union member */ break;
918      case TagDecl::TK_class:  Error = 3; /* Class member */ break;
919      }
920      break;
921    case Declarator::CXXCatchContext:
922      Error = 4; // Exception declaration
923      break;
924    case Declarator::TemplateParamContext:
925      Error = 5; // Template parameter
926      break;
927    case Declarator::BlockLiteralContext:
928      Error = 6;  // Block literal
929      break;
930    case Declarator::FileContext:
931    case Declarator::BlockContext:
932    case Declarator::ForContext:
933    case Declarator::ConditionContext:
934    case Declarator::TypeNameContext:
935      break;
936    }
937
938    if (Error != -1) {
939      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
940        << Error;
941      T = Context.IntTy;
942      D.setInvalidType(true);
943    }
944  }
945
946  // The name we're declaring, if any.
947  DeclarationName Name;
948  if (D.getIdentifier())
949    Name = D.getIdentifier();
950
951  // Walk the DeclTypeInfo, building the recursive type as we go.
952  // DeclTypeInfos are ordered from the identifier out, which is
953  // opposite of what we want :).
954  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
955    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
956    switch (DeclType.Kind) {
957    default: assert(0 && "Unknown decltype!");
958    case DeclaratorChunk::BlockPointer:
959      // If blocks are disabled, emit an error.
960      if (!LangOpts.Blocks)
961        Diag(DeclType.Loc, diag::err_blocks_disable);
962
963      T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
964                                Name);
965      break;
966    case DeclaratorChunk::Pointer:
967      // Verify that we're not building a pointer to pointer to function with
968      // exception specification.
969      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
970        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
971        D.setInvalidType(true);
972        // Build the type anyway.
973      }
974      if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
975        const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>();
976        T = Context.getObjCObjectPointerType(T,
977                                         (ObjCProtocolDecl **)OIT->qual_begin(),
978                                         OIT->getNumProtocols());
979        break;
980      }
981      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
982      break;
983    case DeclaratorChunk::Reference: {
984      Qualifiers Quals;
985      if (DeclType.Ref.HasRestrict) Quals.addRestrict();
986
987      // Verify that we're not building a reference to pointer to function with
988      // exception specification.
989      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
990        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
991        D.setInvalidType(true);
992        // Build the type anyway.
993      }
994      T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
995                             DeclType.Loc, Name);
996      break;
997    }
998    case DeclaratorChunk::Array: {
999      // Verify that we're not building an array of pointers to function with
1000      // exception specification.
1001      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1002        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1003        D.setInvalidType(true);
1004        // Build the type anyway.
1005      }
1006      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1007      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1008      ArrayType::ArraySizeModifier ASM;
1009      if (ATI.isStar)
1010        ASM = ArrayType::Star;
1011      else if (ATI.hasStatic)
1012        ASM = ArrayType::Static;
1013      else
1014        ASM = ArrayType::Normal;
1015      if (ASM == ArrayType::Star &&
1016          D.getContext() != Declarator::PrototypeContext) {
1017        // FIXME: This check isn't quite right: it allows star in prototypes
1018        // for function definitions, and disallows some edge cases detailed
1019        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1020        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1021        ASM = ArrayType::Normal;
1022        D.setInvalidType(true);
1023      }
1024      T = BuildArrayType(T, ASM, ArraySize,
1025                         Qualifiers::fromCVRMask(ATI.TypeQuals),
1026                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1027      break;
1028    }
1029    case DeclaratorChunk::Function: {
1030      // If the function declarator has a prototype (i.e. it is not () and
1031      // does not have a K&R-style identifier list), then the arguments are part
1032      // of the type, otherwise the argument list is ().
1033      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1034
1035      // C99 6.7.5.3p1: The return type may not be a function or array type.
1036      if (T->isArrayType() || T->isFunctionType()) {
1037        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
1038        T = Context.IntTy;
1039        D.setInvalidType(true);
1040      }
1041
1042      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1043        // C++ [dcl.fct]p6:
1044        //   Types shall not be defined in return or parameter types.
1045        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1046        if (Tag->isDefinition())
1047          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1048            << Context.getTypeDeclType(Tag);
1049      }
1050
1051      // Exception specs are not allowed in typedefs. Complain, but add it
1052      // anyway.
1053      if (FTI.hasExceptionSpec &&
1054          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1055        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1056
1057      if (FTI.NumArgs == 0) {
1058        if (getLangOptions().CPlusPlus) {
1059          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1060          // function takes no arguments.
1061          llvm::SmallVector<QualType, 4> Exceptions;
1062          Exceptions.reserve(FTI.NumExceptions);
1063          for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1064            // FIXME: Preserve type source info.
1065            QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1066            // Check that the type is valid for an exception spec, and drop it
1067            // if not.
1068            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1069              Exceptions.push_back(ET);
1070          }
1071          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1072                                      FTI.hasExceptionSpec,
1073                                      FTI.hasAnyExceptionSpec,
1074                                      Exceptions.size(), Exceptions.data());
1075        } else if (FTI.isVariadic) {
1076          // We allow a zero-parameter variadic function in C if the
1077          // function is marked with the "overloadable"
1078          // attribute. Scan for this attribute now.
1079          bool Overloadable = false;
1080          for (const AttributeList *Attrs = D.getAttributes();
1081               Attrs; Attrs = Attrs->getNext()) {
1082            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1083              Overloadable = true;
1084              break;
1085            }
1086          }
1087
1088          if (!Overloadable)
1089            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1090          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
1091        } else {
1092          // Simple void foo(), where the incoming T is the result type.
1093          T = Context.getFunctionNoProtoType(T);
1094        }
1095      } else if (FTI.ArgInfo[0].Param == 0) {
1096        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1097        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1098        D.setInvalidType(true);
1099      } else {
1100        // Otherwise, we have a function with an argument list that is
1101        // potentially variadic.
1102        llvm::SmallVector<QualType, 16> ArgTys;
1103
1104        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1105          ParmVarDecl *Param =
1106            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1107          QualType ArgTy = Param->getType();
1108          assert(!ArgTy.isNull() && "Couldn't parse type?");
1109
1110          // Adjust the parameter type.
1111          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1112
1113          // Look for 'void'.  void is allowed only as a single argument to a
1114          // function with no other parameters (C99 6.7.5.3p10).  We record
1115          // int(void) as a FunctionProtoType with an empty argument list.
1116          if (ArgTy->isVoidType()) {
1117            // If this is something like 'float(int, void)', reject it.  'void'
1118            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1119            // have arguments of incomplete type.
1120            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1121              Diag(DeclType.Loc, diag::err_void_only_param);
1122              ArgTy = Context.IntTy;
1123              Param->setType(ArgTy);
1124            } else if (FTI.ArgInfo[i].Ident) {
1125              // Reject, but continue to parse 'int(void abc)'.
1126              Diag(FTI.ArgInfo[i].IdentLoc,
1127                   diag::err_param_with_void_type);
1128              ArgTy = Context.IntTy;
1129              Param->setType(ArgTy);
1130            } else {
1131              // Reject, but continue to parse 'float(const void)'.
1132              if (ArgTy.hasQualifiers())
1133                Diag(DeclType.Loc, diag::err_void_param_qualified);
1134
1135              // Do not add 'void' to the ArgTys list.
1136              break;
1137            }
1138          } else if (!FTI.hasPrototype) {
1139            if (ArgTy->isPromotableIntegerType()) {
1140              ArgTy = Context.getPromotedIntegerType(ArgTy);
1141            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1142              if (BTy->getKind() == BuiltinType::Float)
1143                ArgTy = Context.DoubleTy;
1144            }
1145          }
1146
1147          ArgTys.push_back(ArgTy);
1148        }
1149
1150        llvm::SmallVector<QualType, 4> Exceptions;
1151        Exceptions.reserve(FTI.NumExceptions);
1152        for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1153          // FIXME: Preserve type source info.
1154          QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1155          // Check that the type is valid for an exception spec, and drop it if
1156          // not.
1157          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1158            Exceptions.push_back(ET);
1159        }
1160
1161        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1162                                    FTI.isVariadic, FTI.TypeQuals,
1163                                    FTI.hasExceptionSpec,
1164                                    FTI.hasAnyExceptionSpec,
1165                                    Exceptions.size(), Exceptions.data());
1166      }
1167      break;
1168    }
1169    case DeclaratorChunk::MemberPointer:
1170      // Verify that we're not building a pointer to pointer to function with
1171      // exception specification.
1172      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1173        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1174        D.setInvalidType(true);
1175        // Build the type anyway.
1176      }
1177      // The scope spec must refer to a class, or be dependent.
1178      QualType ClsType;
1179      if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1180            || dyn_cast_or_null<CXXRecordDecl>(
1181                                   computeDeclContext(DeclType.Mem.Scope()))) {
1182        NestedNameSpecifier *NNS
1183          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1184        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1185        switch (NNS->getKind()) {
1186        case NestedNameSpecifier::Identifier:
1187          ClsType = Context.getTypenameType(NNSPrefix, NNS->getAsIdentifier());
1188          break;
1189
1190        case NestedNameSpecifier::Namespace:
1191        case NestedNameSpecifier::Global:
1192          llvm::llvm_unreachable("Nested-name-specifier must name a type");
1193          break;
1194
1195        case NestedNameSpecifier::TypeSpec:
1196        case NestedNameSpecifier::TypeSpecWithTemplate:
1197          ClsType = QualType(NNS->getAsType(), 0);
1198          if (NNSPrefix)
1199            ClsType = Context.getQualifiedNameType(NNSPrefix, ClsType);
1200          break;
1201        }
1202      } else {
1203        Diag(DeclType.Mem.Scope().getBeginLoc(),
1204             diag::err_illegal_decl_mempointer_in_nonclass)
1205          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1206          << DeclType.Mem.Scope().getRange();
1207        D.setInvalidType(true);
1208      }
1209
1210      if (!ClsType.isNull())
1211        T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1212                                   DeclType.Loc, D.getIdentifier());
1213      if (T.isNull()) {
1214        T = Context.IntTy;
1215        D.setInvalidType(true);
1216      }
1217      break;
1218    }
1219
1220    if (T.isNull()) {
1221      D.setInvalidType(true);
1222      T = Context.IntTy;
1223    }
1224
1225    // See if there are any attributes on this declarator chunk.
1226    if (const AttributeList *AL = DeclType.getAttrs())
1227      ProcessTypeAttributeList(T, AL);
1228  }
1229
1230  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1231    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1232    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1233
1234    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1235    // for a nonstatic member function, the function type to which a pointer
1236    // to member refers, or the top-level function type of a function typedef
1237    // declaration.
1238    if (FnTy->getTypeQuals() != 0 &&
1239        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1240        ((D.getContext() != Declarator::MemberContext &&
1241          (!D.getCXXScopeSpec().isSet() ||
1242           !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1243              ->isRecord())) ||
1244         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1245      if (D.isFunctionDeclarator())
1246        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1247      else
1248        Diag(D.getIdentifierLoc(),
1249             diag::err_invalid_qualified_typedef_function_type_use);
1250
1251      // Strip the cv-quals from the type.
1252      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1253                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1254    }
1255  }
1256
1257  // If there were any type attributes applied to the decl itself (not the
1258  // type, apply the type attribute to the type!)
1259  if (const AttributeList *Attrs = D.getAttributes())
1260    ProcessTypeAttributeList(T, Attrs);
1261
1262  if (DInfo) {
1263    if (D.isInvalidType())
1264      *DInfo = 0;
1265    else
1266      *DInfo = GetDeclaratorInfoForDeclarator(D, T);
1267  }
1268
1269  return T;
1270}
1271
1272namespace {
1273  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1274    const DeclSpec &DS;
1275
1276  public:
1277    TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1278
1279    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1280      Visit(TL.getUnqualifiedLoc());
1281    }
1282    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1283      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1284    }
1285    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1286      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1287
1288      if (DS.getProtocolQualifiers()) {
1289        assert(TL.getNumProtocols() > 0);
1290        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1291        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1292        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1293        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1294          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1295      } else {
1296        assert(TL.getNumProtocols() == 0);
1297        TL.setLAngleLoc(SourceLocation());
1298        TL.setRAngleLoc(SourceLocation());
1299      }
1300    }
1301    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1302      assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1303
1304      TL.setStarLoc(SourceLocation());
1305
1306      if (DS.getProtocolQualifiers()) {
1307        assert(TL.getNumProtocols() > 0);
1308        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1309        TL.setHasProtocolsAsWritten(true);
1310        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1311        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1312        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1313          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1314
1315      } else {
1316        assert(TL.getNumProtocols() == 0);
1317        TL.setHasProtocolsAsWritten(false);
1318        TL.setLAngleLoc(SourceLocation());
1319        TL.setRAngleLoc(SourceLocation());
1320      }
1321
1322      // This might not have been written with an inner type.
1323      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1324        TL.setHasBaseTypeAsWritten(false);
1325        TL.getBaseTypeLoc().initialize(SourceLocation());
1326      } else {
1327        TL.setHasBaseTypeAsWritten(true);
1328        Visit(TL.getBaseTypeLoc());
1329      }
1330    }
1331    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1332      DeclaratorInfo *DInfo = 0;
1333      Sema::GetTypeFromParser(DS.getTypeRep(), &DInfo);
1334
1335      // If we got no declarator info from previous Sema routines,
1336      // just fill with the typespec loc.
1337      if (!DInfo) {
1338        TL.initialize(DS.getTypeSpecTypeLoc());
1339        return;
1340      }
1341
1342      TemplateSpecializationTypeLoc OldTL =
1343        cast<TemplateSpecializationTypeLoc>(DInfo->getTypeLoc());
1344      TL.copy(OldTL);
1345    }
1346    void VisitTypeLoc(TypeLoc TL) {
1347      // FIXME: add other typespec types and change this to an assert.
1348      TL.initialize(DS.getTypeSpecTypeLoc());
1349    }
1350  };
1351
1352  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1353    const DeclaratorChunk &Chunk;
1354
1355  public:
1356    DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1357
1358    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1359      llvm::llvm_unreachable("qualified type locs not expected here!");
1360    }
1361
1362    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1363      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1364      TL.setCaretLoc(Chunk.Loc);
1365    }
1366    void VisitPointerTypeLoc(PointerTypeLoc TL) {
1367      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1368      TL.setStarLoc(Chunk.Loc);
1369    }
1370    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1371      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1372      TL.setStarLoc(Chunk.Loc);
1373      TL.setHasBaseTypeAsWritten(true);
1374      TL.setHasProtocolsAsWritten(false);
1375      TL.setLAngleLoc(SourceLocation());
1376      TL.setRAngleLoc(SourceLocation());
1377    }
1378    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1379      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1380      TL.setStarLoc(Chunk.Loc);
1381      // FIXME: nested name specifier
1382    }
1383    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1384      assert(Chunk.Kind == DeclaratorChunk::Reference);
1385      // 'Amp' is misleading: this might have been originally
1386      /// spelled with AmpAmp.
1387      TL.setAmpLoc(Chunk.Loc);
1388    }
1389    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1390      assert(Chunk.Kind == DeclaratorChunk::Reference);
1391      assert(!Chunk.Ref.LValueRef);
1392      TL.setAmpAmpLoc(Chunk.Loc);
1393    }
1394    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1395      assert(Chunk.Kind == DeclaratorChunk::Array);
1396      TL.setLBracketLoc(Chunk.Loc);
1397      TL.setRBracketLoc(Chunk.EndLoc);
1398      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1399    }
1400    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1401      assert(Chunk.Kind == DeclaratorChunk::Function);
1402      TL.setLParenLoc(Chunk.Loc);
1403      TL.setRParenLoc(Chunk.EndLoc);
1404
1405      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1406      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1407        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1408        TL.setArg(tpi++, Param);
1409      }
1410      // FIXME: exception specs
1411    }
1412
1413    void VisitTypeLoc(TypeLoc TL) {
1414      llvm::llvm_unreachable("unsupported TypeLoc kind in declarator!");
1415    }
1416  };
1417}
1418
1419/// \brief Create and instantiate a DeclaratorInfo with type source information.
1420///
1421/// \param T QualType referring to the type as written in source code.
1422DeclaratorInfo *
1423Sema::GetDeclaratorInfoForDeclarator(Declarator &D, QualType T) {
1424  DeclaratorInfo *DInfo = Context.CreateDeclaratorInfo(T);
1425  UnqualTypeLoc CurrTL = DInfo->getTypeLoc().getUnqualifiedLoc();
1426
1427  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1428    DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1429    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1430  }
1431
1432  TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1433
1434  return DInfo;
1435}
1436
1437/// \brief Create a LocInfoType to hold the given QualType and DeclaratorInfo.
1438QualType Sema::CreateLocInfoType(QualType T, DeclaratorInfo *DInfo) {
1439  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1440  // and Sema during declaration parsing. Try deallocating/caching them when
1441  // it's appropriate, instead of allocating them and keeping them around.
1442  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1443  new (LocT) LocInfoType(T, DInfo);
1444  assert(LocT->getTypeClass() != T->getTypeClass() &&
1445         "LocInfoType's TypeClass conflicts with an existing Type class");
1446  return QualType(LocT, 0);
1447}
1448
1449void LocInfoType::getAsStringInternal(std::string &Str,
1450                                      const PrintingPolicy &Policy) const {
1451  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1452         " was used directly instead of getting the QualType through"
1453         " GetTypeFromParser");
1454}
1455
1456/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1457/// declarator
1458QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1459  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1460  QualType T = MDecl->getResultType();
1461  llvm::SmallVector<QualType, 16> ArgTys;
1462
1463  // Add the first two invisible argument types for self and _cmd.
1464  if (MDecl->isInstanceMethod()) {
1465    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1466    selfTy = Context.getPointerType(selfTy);
1467    ArgTys.push_back(selfTy);
1468  } else
1469    ArgTys.push_back(Context.getObjCIdType());
1470  ArgTys.push_back(Context.getObjCSelType());
1471
1472  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1473       E = MDecl->param_end(); PI != E; ++PI) {
1474    QualType ArgTy = (*PI)->getType();
1475    assert(!ArgTy.isNull() && "Couldn't parse type?");
1476    ArgTy = adjustParameterType(ArgTy);
1477    ArgTys.push_back(ArgTy);
1478  }
1479  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1480                              MDecl->isVariadic(), 0);
1481  return T;
1482}
1483
1484/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1485/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1486/// they point to and return true. If T1 and T2 aren't pointer types
1487/// or pointer-to-member types, or if they are not similar at this
1488/// level, returns false and leaves T1 and T2 unchanged. Top-level
1489/// qualifiers on T1 and T2 are ignored. This function will typically
1490/// be called in a loop that successively "unwraps" pointer and
1491/// pointer-to-member types to compare them at each level.
1492bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1493  const PointerType *T1PtrType = T1->getAs<PointerType>(),
1494                    *T2PtrType = T2->getAs<PointerType>();
1495  if (T1PtrType && T2PtrType) {
1496    T1 = T1PtrType->getPointeeType();
1497    T2 = T2PtrType->getPointeeType();
1498    return true;
1499  }
1500
1501  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1502                          *T2MPType = T2->getAs<MemberPointerType>();
1503  if (T1MPType && T2MPType &&
1504      Context.getCanonicalType(T1MPType->getClass()) ==
1505      Context.getCanonicalType(T2MPType->getClass())) {
1506    T1 = T1MPType->getPointeeType();
1507    T2 = T2MPType->getPointeeType();
1508    return true;
1509  }
1510  return false;
1511}
1512
1513Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1514  // C99 6.7.6: Type names have no identifier.  This is already validated by
1515  // the parser.
1516  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1517
1518  DeclaratorInfo *DInfo = 0;
1519  TagDecl *OwnedTag = 0;
1520  QualType T = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
1521  if (D.isInvalidType())
1522    return true;
1523
1524  if (getLangOptions().CPlusPlus) {
1525    // Check that there are no default arguments (C++ only).
1526    CheckExtraCXXDefaultArguments(D);
1527
1528    // C++0x [dcl.type]p3:
1529    //   A type-specifier-seq shall not define a class or enumeration
1530    //   unless it appears in the type-id of an alias-declaration
1531    //   (7.1.3).
1532    if (OwnedTag && OwnedTag->isDefinition())
1533      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1534        << Context.getTypeDeclType(OwnedTag);
1535  }
1536
1537  if (DInfo)
1538    T = CreateLocInfoType(T, DInfo);
1539
1540  return T.getAsOpaquePtr();
1541}
1542
1543
1544
1545//===----------------------------------------------------------------------===//
1546// Type Attribute Processing
1547//===----------------------------------------------------------------------===//
1548
1549/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1550/// specified type.  The attribute contains 1 argument, the id of the address
1551/// space for the type.
1552static void HandleAddressSpaceTypeAttribute(QualType &Type,
1553                                            const AttributeList &Attr, Sema &S){
1554
1555  // If this type is already address space qualified, reject it.
1556  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1557  // for two or more different address spaces."
1558  if (Type.getAddressSpace()) {
1559    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1560    return;
1561  }
1562
1563  // Check the attribute arguments.
1564  if (Attr.getNumArgs() != 1) {
1565    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1566    return;
1567  }
1568  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1569  llvm::APSInt addrSpace(32);
1570  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1571    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1572      << ASArgExpr->getSourceRange();
1573    return;
1574  }
1575
1576  // Bounds checking.
1577  if (addrSpace.isSigned()) {
1578    if (addrSpace.isNegative()) {
1579      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1580        << ASArgExpr->getSourceRange();
1581      return;
1582    }
1583    addrSpace.setIsSigned(false);
1584  }
1585  llvm::APSInt max(addrSpace.getBitWidth());
1586  max = Qualifiers::MaxAddressSpace;
1587  if (addrSpace > max) {
1588    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1589      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1590    return;
1591  }
1592
1593  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1594  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1595}
1596
1597/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1598/// specified type.  The attribute contains 1 argument, weak or strong.
1599static void HandleObjCGCTypeAttribute(QualType &Type,
1600                                      const AttributeList &Attr, Sema &S) {
1601  if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1602    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1603    return;
1604  }
1605
1606  // Check the attribute arguments.
1607  if (!Attr.getParameterName()) {
1608    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1609      << "objc_gc" << 1;
1610    return;
1611  }
1612  Qualifiers::GC GCAttr;
1613  if (Attr.getNumArgs() != 0) {
1614    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1615    return;
1616  }
1617  if (Attr.getParameterName()->isStr("weak"))
1618    GCAttr = Qualifiers::Weak;
1619  else if (Attr.getParameterName()->isStr("strong"))
1620    GCAttr = Qualifiers::Strong;
1621  else {
1622    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1623      << "objc_gc" << Attr.getParameterName();
1624    return;
1625  }
1626
1627  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1628}
1629
1630/// HandleNoReturnTypeAttribute - Process the noreturn attribute on the
1631/// specified type.  The attribute contains 0 arguments.
1632static void HandleNoReturnTypeAttribute(QualType &Type,
1633                                        const AttributeList &Attr, Sema &S) {
1634  if (Attr.getNumArgs() != 0)
1635    return;
1636
1637  // We only apply this to a pointer to function or a pointer to block.
1638  if (!Type->isFunctionPointerType()
1639      && !Type->isBlockPointerType()
1640      && !Type->isFunctionType())
1641    return;
1642
1643  Type = S.Context.getNoReturnType(Type);
1644}
1645
1646/// HandleVectorSizeAttribute - this attribute is only applicable to integral
1647/// and float scalars, although arrays, pointers, and function return values are
1648/// allowed in conjunction with this construct. Aggregates with this attribute
1649/// are invalid, even if they are of the same size as a corresponding scalar.
1650/// The raw attribute should contain precisely 1 argument, the vector size for
1651/// the variable, measured in bytes. If curType and rawAttr are well formed,
1652/// this routine will return a new vector type.
1653static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) {
1654  // Check the attribute arugments.
1655  if (Attr.getNumArgs() != 1) {
1656    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1657    return;
1658  }
1659  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
1660  llvm::APSInt vecSize(32);
1661  if (!sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
1662    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1663      << "vector_size" << sizeExpr->getSourceRange();
1664    return;
1665  }
1666  // the base type must be integer or float, and can't already be a vector.
1667  if (CurType->isVectorType() ||
1668      (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
1669    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
1670    return;
1671  }
1672  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
1673  // vecSize is specified in bytes - convert to bits.
1674  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1675
1676  // the vector size needs to be an integral multiple of the type size.
1677  if (vectorSize % typeSize) {
1678    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
1679      << sizeExpr->getSourceRange();
1680    return;
1681  }
1682  if (vectorSize == 0) {
1683    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
1684      << sizeExpr->getSourceRange();
1685    return;
1686  }
1687
1688  // Success! Instantiate the vector type, the number of elements is > 0, and
1689  // not required to be a power of 2, unlike GCC.
1690  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize);
1691}
1692
1693void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1694  // Scan through and apply attributes to this type where it makes sense.  Some
1695  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1696  // type, but others can be present in the type specifiers even though they
1697  // apply to the decl.  Here we apply type attributes and ignore the rest.
1698  for (; AL; AL = AL->getNext()) {
1699    // If this is an attribute we can handle, do so now, otherwise, add it to
1700    // the LeftOverAttrs list for rechaining.
1701    switch (AL->getKind()) {
1702    default: break;
1703    case AttributeList::AT_address_space:
1704      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1705      break;
1706    case AttributeList::AT_objc_gc:
1707      HandleObjCGCTypeAttribute(Result, *AL, *this);
1708      break;
1709    case AttributeList::AT_noreturn:
1710      HandleNoReturnTypeAttribute(Result, *AL, *this);
1711      break;
1712    case AttributeList::AT_vector_size:
1713      HandleVectorSizeAttr(Result, *AL, *this);
1714      break;
1715    }
1716  }
1717}
1718
1719/// @brief Ensure that the type T is a complete type.
1720///
1721/// This routine checks whether the type @p T is complete in any
1722/// context where a complete type is required. If @p T is a complete
1723/// type, returns false. If @p T is a class template specialization,
1724/// this routine then attempts to perform class template
1725/// instantiation. If instantiation fails, or if @p T is incomplete
1726/// and cannot be completed, issues the diagnostic @p diag (giving it
1727/// the type @p T) and returns true.
1728///
1729/// @param Loc  The location in the source that the incomplete type
1730/// diagnostic should refer to.
1731///
1732/// @param T  The type that this routine is examining for completeness.
1733///
1734/// @param PD The partial diagnostic that will be printed out if T is not a
1735/// complete type.
1736///
1737/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1738/// @c false otherwise.
1739bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1740                               const PartialDiagnostic &PD,
1741                               std::pair<SourceLocation,
1742                                         PartialDiagnostic> Note) {
1743  unsigned diag = PD.getDiagID();
1744
1745  // FIXME: Add this assertion to make sure we always get instantiation points.
1746  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
1747  // FIXME: Add this assertion to help us flush out problems with
1748  // checking for dependent types and type-dependent expressions.
1749  //
1750  //  assert(!T->isDependentType() &&
1751  //         "Can't ask whether a dependent type is complete");
1752
1753  // If we have a complete type, we're done.
1754  if (!T->isIncompleteType())
1755    return false;
1756
1757  // If we have a class template specialization or a class member of a
1758  // class template specialization, or an array with known size of such,
1759  // try to instantiate it.
1760  QualType MaybeTemplate = T;
1761  if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
1762    MaybeTemplate = Array->getElementType();
1763  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
1764    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1765          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1766      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
1767        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
1768                                                      TSK_ImplicitInstantiation,
1769                                                      /*Complain=*/diag != 0);
1770    } else if (CXXRecordDecl *Rec
1771                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1772      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1773        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
1774        assert(MSInfo && "Missing member specialization information?");
1775        // This record was instantiated from a class within a template.
1776        if (MSInfo->getTemplateSpecializationKind()
1777                                               != TSK_ExplicitSpecialization)
1778          return InstantiateClass(Loc, Rec, Pattern,
1779                                  getTemplateInstantiationArgs(Rec),
1780                                  TSK_ImplicitInstantiation,
1781                                  /*Complain=*/diag != 0);
1782      }
1783    }
1784  }
1785
1786  if (diag == 0)
1787    return true;
1788
1789  // We have an incomplete type. Produce a diagnostic.
1790  Diag(Loc, PD) << T;
1791
1792  // If we have a note, produce it.
1793  if (!Note.first.isInvalid())
1794    Diag(Note.first, Note.second);
1795
1796  // If the type was a forward declaration of a class/struct/union
1797  // type, produce
1798  const TagType *Tag = 0;
1799  if (const RecordType *Record = T->getAs<RecordType>())
1800    Tag = Record;
1801  else if (const EnumType *Enum = T->getAs<EnumType>())
1802    Tag = Enum;
1803
1804  if (Tag && !Tag->getDecl()->isInvalidDecl())
1805    Diag(Tag->getDecl()->getLocation(),
1806         Tag->isBeingDefined() ? diag::note_type_being_defined
1807                               : diag::note_forward_declaration)
1808        << QualType(Tag, 0);
1809
1810  return true;
1811}
1812
1813/// \brief Retrieve a version of the type 'T' that is qualified by the
1814/// nested-name-specifier contained in SS.
1815QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1816  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1817    return T;
1818
1819  NestedNameSpecifier *NNS
1820    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1821  return Context.getQualifiedNameType(NNS, T);
1822}
1823
1824QualType Sema::BuildTypeofExprType(Expr *E) {
1825  return Context.getTypeOfExprType(E);
1826}
1827
1828QualType Sema::BuildDecltypeType(Expr *E) {
1829  if (E->getType() == Context.OverloadTy) {
1830    Diag(E->getLocStart(),
1831         diag::err_cannot_determine_declared_type_of_overloaded_function);
1832    return QualType();
1833  }
1834  return Context.getDecltypeType(E);
1835}
1836