SemaType.cpp revision b78d833b12f7c4baab138f305f72efd49455a3f9
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/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Parse/DeclSpec.h"
20using namespace clang;
21
22/// \brief Perform adjustment on the parameter type of a function.
23///
24/// This routine adjusts the given parameter type @p T to the actual
25/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
26/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
27QualType Sema::adjustParameterType(QualType T) {
28  // C99 6.7.5.3p7:
29  if (T->isArrayType()) {
30    // C99 6.7.5.3p7:
31    //   A declaration of a parameter as "array of type" shall be
32    //   adjusted to "qualified pointer to type", where the type
33    //   qualifiers (if any) are those specified within the [ and ] of
34    //   the array type derivation.
35    return Context.getArrayDecayedType(T);
36  } else if (T->isFunctionType())
37    // C99 6.7.5.3p8:
38    //   A declaration of a parameter as "function returning type"
39    //   shall be adjusted to "pointer to function returning type", as
40    //   in 6.3.2.1.
41    return Context.getPointerType(T);
42
43  return T;
44}
45
46/// \brief Convert the specified declspec to the appropriate type
47/// object.
48/// \param DS  the declaration specifiers
49/// \param DeclLoc The location of the declarator identifier or invalid if none.
50/// \returns The type described by the declaration specifiers.  This function
51/// never returns null.
52QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
53                                     SourceLocation DeclLoc,
54                                     bool &isInvalid) {
55  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
56  // checking.
57  QualType Result;
58
59  switch (DS.getTypeSpecType()) {
60  case DeclSpec::TST_void:
61    Result = Context.VoidTy;
62    break;
63  case DeclSpec::TST_char:
64    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
65      Result = Context.CharTy;
66    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
67      Result = Context.SignedCharTy;
68    else {
69      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
70             "Unknown TSS value");
71      Result = Context.UnsignedCharTy;
72    }
73    break;
74  case DeclSpec::TST_wchar:
75    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
76      Result = Context.WCharTy;
77    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
78      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
79        << DS.getSpecifierName(DS.getTypeSpecType());
80      Result = Context.getSignedWCharType();
81    } else {
82      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
83        "Unknown TSS value");
84      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
85        << DS.getSpecifierName(DS.getTypeSpecType());
86      Result = Context.getUnsignedWCharType();
87    }
88    break;
89  case DeclSpec::TST_unspecified:
90    // "<proto1,proto2>" is an objc qualified ID with a missing id.
91    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
92      Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
93                                              DS.getNumProtocolQualifiers());
94      break;
95    }
96
97    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
98    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
99    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
100    // Note that the one exception to this is function definitions, which are
101    // allowed to be completely missing a declspec.  This is handled in the
102    // parser already though by it pretending to have seen an 'int' in this
103    // case.
104    if (getLangOptions().ImplicitInt) {
105      // In C89 mode, we only warn if there is a completely missing declspec
106      // when one is not allowed.
107      if (DS.isEmpty()) {
108        if (DeclLoc.isInvalid())
109          DeclLoc = DS.getSourceRange().getBegin();
110        Diag(DeclLoc, diag::ext_missing_declspec)
111          << DS.getSourceRange()
112        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
113                                                 "int");
114      }
115    } else if (!DS.hasTypeSpecifier()) {
116      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
117      // "At least one type specifier shall be given in the declaration
118      // specifiers in each declaration, and in the specifier-qualifier list in
119      // each struct declaration and type name."
120      // FIXME: Does Microsoft really have the implicit int extension in C++?
121      if (DeclLoc.isInvalid())
122        DeclLoc = DS.getSourceRange().getBegin();
123
124      if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) {
125        Diag(DeclLoc, diag::err_missing_type_specifier)
126          << DS.getSourceRange();
127
128        // When this occurs in C++ code, often something is very broken with the
129        // value being declared, poison it as invalid so we don't get chains of
130        // errors.
131        isInvalid = true;
132      } else {
133        Diag(DeclLoc, diag::ext_missing_type_specifier)
134          << DS.getSourceRange();
135      }
136    }
137
138    // FALL THROUGH.
139  case DeclSpec::TST_int: {
140    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
141      switch (DS.getTypeSpecWidth()) {
142      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
143      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
144      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
145      case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
146      }
147    } else {
148      switch (DS.getTypeSpecWidth()) {
149      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
150      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
151      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
152      case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
153      }
154    }
155    break;
156  }
157  case DeclSpec::TST_float: Result = Context.FloatTy; break;
158  case DeclSpec::TST_double:
159    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
160      Result = Context.LongDoubleTy;
161    else
162      Result = Context.DoubleTy;
163    break;
164  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
165  case DeclSpec::TST_decimal32:    // _Decimal32
166  case DeclSpec::TST_decimal64:    // _Decimal64
167  case DeclSpec::TST_decimal128:   // _Decimal128
168    Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
169    Result = Context.IntTy;
170    isInvalid = true;
171    break;
172  case DeclSpec::TST_class:
173  case DeclSpec::TST_enum:
174  case DeclSpec::TST_union:
175  case DeclSpec::TST_struct: {
176    Decl *D = static_cast<Decl *>(DS.getTypeRep());
177    assert(D && "Didn't get a decl for a class/enum/union/struct?");
178    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
179           DS.getTypeSpecSign() == 0 &&
180           "Can't handle qualifiers on typedef names yet!");
181    // TypeQuals handled by caller.
182    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
183
184    if (D->isInvalidDecl())
185      isInvalid = true;
186    break;
187  }
188  case DeclSpec::TST_typename: {
189    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
190           DS.getTypeSpecSign() == 0 &&
191           "Can't handle qualifiers on typedef names yet!");
192    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
193
194    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
195      // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have
196      // this "hack" for now...
197      if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
198        Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
199                                                       (ObjCProtocolDecl**)PQ,
200                                               DS.getNumProtocolQualifiers());
201      else if (Result == Context.getObjCIdType())
202        // id<protocol-list>
203        Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
204                                                DS.getNumProtocolQualifiers());
205      else if (Result == Context.getObjCClassType()) {
206        if (DeclLoc.isInvalid())
207          DeclLoc = DS.getSourceRange().getBegin();
208        // Class<protocol-list>
209        Diag(DeclLoc, diag::err_qualified_class_unsupported)
210          << DS.getSourceRange();
211      } else {
212        if (DeclLoc.isInvalid())
213          DeclLoc = DS.getSourceRange().getBegin();
214        Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
215          << DS.getSourceRange();
216        isInvalid = true;
217      }
218    }
219
220    // If this is a reference to an invalid typedef, propagate the invalidity.
221    if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
222      if (TDT->getDecl()->isInvalidDecl())
223        isInvalid = true;
224
225    // TypeQuals handled by caller.
226    break;
227  }
228  case DeclSpec::TST_typeofType:
229    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
230    assert(!Result.isNull() && "Didn't get a type for typeof?");
231    // TypeQuals handled by caller.
232    Result = Context.getTypeOfType(Result);
233    break;
234  case DeclSpec::TST_typeofExpr: {
235    Expr *E = static_cast<Expr *>(DS.getTypeRep());
236    assert(E && "Didn't get an expression for typeof?");
237    // TypeQuals handled by caller.
238    Result = Context.getTypeOfExprType(E);
239    break;
240  }
241  case DeclSpec::TST_decltype: {
242    Expr *E = static_cast<Expr *>(DS.getTypeRep());
243    assert(E && "Didn't get an expression for decltype?");
244    // TypeQuals handled by caller.
245    Result = Context.getDecltypeType(E);
246    break;
247  }
248
249  case DeclSpec::TST_error:
250    Result = Context.IntTy;
251    isInvalid = true;
252    break;
253  }
254
255  // Handle complex types.
256  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
257    if (getLangOptions().Freestanding)
258      Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
259    Result = Context.getComplexType(Result);
260  }
261
262  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
263         "FIXME: imaginary types not supported yet!");
264
265  // See if there are any attributes on the declspec that apply to the type (as
266  // opposed to the decl).
267  if (const AttributeList *AL = DS.getAttributes())
268    ProcessTypeAttributeList(Result, AL);
269
270  // Apply const/volatile/restrict qualifiers to T.
271  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
272
273    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
274    // or incomplete types shall not be restrict-qualified."  C++ also allows
275    // restrict-qualified references.
276    if (TypeQuals & QualType::Restrict) {
277      if (Result->isPointerType() || Result->isReferenceType()) {
278        QualType EltTy = Result->isPointerType() ?
279          Result->getAsPointerType()->getPointeeType() :
280          Result->getAsReferenceType()->getPointeeType();
281
282        // If we have a pointer or reference, the pointee must have an object
283        // incomplete type.
284        if (!EltTy->isIncompleteOrObjectType()) {
285          Diag(DS.getRestrictSpecLoc(),
286               diag::err_typecheck_invalid_restrict_invalid_pointee)
287            << EltTy << DS.getSourceRange();
288          TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
289        }
290      } else {
291        Diag(DS.getRestrictSpecLoc(),
292             diag::err_typecheck_invalid_restrict_not_pointer)
293          << Result << DS.getSourceRange();
294        TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
295      }
296    }
297
298    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
299    // of a function type includes any type qualifiers, the behavior is
300    // undefined."
301    if (Result->isFunctionType() && TypeQuals) {
302      // Get some location to point at, either the C or V location.
303      SourceLocation Loc;
304      if (TypeQuals & QualType::Const)
305        Loc = DS.getConstSpecLoc();
306      else {
307        assert((TypeQuals & QualType::Volatile) &&
308               "Has CV quals but not C or V?");
309        Loc = DS.getVolatileSpecLoc();
310      }
311      Diag(Loc, diag::warn_typecheck_function_qualifiers)
312        << Result << DS.getSourceRange();
313    }
314
315    // C++ [dcl.ref]p1:
316    //   Cv-qualified references are ill-formed except when the
317    //   cv-qualifiers are introduced through the use of a typedef
318    //   (7.1.3) or of a template type argument (14.3), in which
319    //   case the cv-qualifiers are ignored.
320    // FIXME: Shouldn't we be checking SCS_typedef here?
321    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
322        TypeQuals && Result->isReferenceType()) {
323      TypeQuals &= ~QualType::Const;
324      TypeQuals &= ~QualType::Volatile;
325    }
326
327    Result = Result.getQualifiedType(TypeQuals);
328  }
329  return Result;
330}
331
332static std::string getPrintableNameForEntity(DeclarationName Entity) {
333  if (Entity)
334    return Entity.getAsString();
335
336  return "type name";
337}
338
339/// \brief Build a pointer type.
340///
341/// \param T The type to which we'll be building a pointer.
342///
343/// \param Quals The cvr-qualifiers to be applied to the pointer type.
344///
345/// \param Loc The location of the entity whose type involves this
346/// pointer type or, if there is no such entity, the location of the
347/// type that will have pointer type.
348///
349/// \param Entity The name of the entity that involves the pointer
350/// type, if known.
351///
352/// \returns A suitable pointer type, if there are no
353/// errors. Otherwise, returns a NULL type.
354QualType Sema::BuildPointerType(QualType T, unsigned Quals,
355                                SourceLocation Loc, DeclarationName Entity) {
356  if (T->isReferenceType()) {
357    // C++ 8.3.2p4: There shall be no ... pointers to references ...
358    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
359      << getPrintableNameForEntity(Entity);
360    return QualType();
361  }
362
363  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
364  // object or incomplete types shall not be restrict-qualified."
365  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
366    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
367      << T;
368    Quals &= ~QualType::Restrict;
369  }
370
371  // Build the pointer type.
372  return Context.getPointerType(T).getQualifiedType(Quals);
373}
374
375/// \brief Build a reference type.
376///
377/// \param T The type to which we'll be building a reference.
378///
379/// \param Quals The cvr-qualifiers to be applied to the reference type.
380///
381/// \param Loc The location of the entity whose type involves this
382/// reference type or, if there is no such entity, the location of the
383/// type that will have reference type.
384///
385/// \param Entity The name of the entity that involves the reference
386/// type, if known.
387///
388/// \returns A suitable reference type, if there are no
389/// errors. Otherwise, returns a NULL type.
390QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
391                                  SourceLocation Loc, DeclarationName Entity) {
392  if (LValueRef) {
393    if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
394      // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
395      //   reference to a type T, and attempt to create the type "lvalue
396      //   reference to cv TD" creates the type "lvalue reference to T".
397      // We use the qualifiers (restrict or none) of the original reference,
398      // not the new ones. This is consistent with GCC.
399      return Context.getLValueReferenceType(R->getPointeeType()).
400               getQualifiedType(T.getCVRQualifiers());
401    }
402  }
403  if (T->isReferenceType()) {
404    // C++ [dcl.ref]p4: There shall be no references to references.
405    //
406    // According to C++ DR 106, references to references are only
407    // diagnosed when they are written directly (e.g., "int & &"),
408    // but not when they happen via a typedef:
409    //
410    //   typedef int& intref;
411    //   typedef intref& intref2;
412    //
413    // Parser::ParserDeclaratorInternal diagnoses the case where
414    // references are written directly; here, we handle the
415    // collapsing of references-to-references as described in C++
416    // DR 106 and amended by C++ DR 540.
417    return T;
418  }
419
420  // C++ [dcl.ref]p1:
421  //   A declarator that specifies the type “reference to cv void”
422  //   is ill-formed.
423  if (T->isVoidType()) {
424    Diag(Loc, diag::err_reference_to_void);
425    return QualType();
426  }
427
428  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
429  // object or incomplete types shall not be restrict-qualified."
430  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
431    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
432      << T;
433    Quals &= ~QualType::Restrict;
434  }
435
436  // C++ [dcl.ref]p1:
437  //   [...] Cv-qualified references are ill-formed except when the
438  //   cv-qualifiers are introduced through the use of a typedef
439  //   (7.1.3) or of a template type argument (14.3), in which case
440  //   the cv-qualifiers are ignored.
441  //
442  // We diagnose extraneous cv-qualifiers for the non-typedef,
443  // non-template type argument case within the parser. Here, we just
444  // ignore any extraneous cv-qualifiers.
445  Quals &= ~QualType::Const;
446  Quals &= ~QualType::Volatile;
447
448  // Handle restrict on references.
449  if (LValueRef)
450    return Context.getLValueReferenceType(T).getQualifiedType(Quals);
451  return Context.getRValueReferenceType(T).getQualifiedType(Quals);
452}
453
454/// \brief Build an array type.
455///
456/// \param T The type of each element in the array.
457///
458/// \param ASM C99 array size modifier (e.g., '*', 'static').
459///
460/// \param ArraySize Expression describing the size of the array.
461///
462/// \param Quals The cvr-qualifiers to be applied to the array's
463/// element type.
464///
465/// \param Loc The location of the entity whose type involves this
466/// array type or, if there is no such entity, the location of the
467/// type that will have array type.
468///
469/// \param Entity The name of the entity that involves the array
470/// type, if known.
471///
472/// \returns A suitable array type, if there are no errors. Otherwise,
473/// returns a NULL type.
474QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
475                              Expr *ArraySize, unsigned Quals,
476                              SourceLocation Loc, DeclarationName Entity) {
477  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
478  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
479  if (RequireCompleteType(Loc, T,
480                             diag::err_illegal_decl_array_incomplete_type))
481    return QualType();
482
483  if (T->isFunctionType()) {
484    Diag(Loc, diag::err_illegal_decl_array_of_functions)
485      << getPrintableNameForEntity(Entity);
486    return QualType();
487  }
488
489  // C++ 8.3.2p4: There shall be no ... arrays of references ...
490  if (T->isReferenceType()) {
491    Diag(Loc, diag::err_illegal_decl_array_of_references)
492      << getPrintableNameForEntity(Entity);
493    return QualType();
494  }
495
496  if (const RecordType *EltTy = T->getAsRecordType()) {
497    // If the element type is a struct or union that contains a variadic
498    // array, accept it as a GNU extension: C99 6.7.2.1p2.
499    if (EltTy->getDecl()->hasFlexibleArrayMember())
500      Diag(Loc, diag::ext_flexible_array_in_array) << T;
501  } else if (T->isObjCInterfaceType()) {
502    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
503    return QualType();
504  }
505
506  // C99 6.7.5.2p1: The size expression shall have integer type.
507  if (ArraySize && !ArraySize->isTypeDependent() &&
508      !ArraySize->getType()->isIntegerType()) {
509    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
510      << ArraySize->getType() << ArraySize->getSourceRange();
511    ArraySize->Destroy(Context);
512    return QualType();
513  }
514  llvm::APSInt ConstVal(32);
515  if (!ArraySize) {
516    if (ASM == ArrayType::Star)
517      T = Context.getVariableArrayType(T, 0, ASM, Quals);
518    else
519      T = Context.getIncompleteArrayType(T, ASM, Quals);
520  } else if (ArraySize->isValueDependent()) {
521    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
522  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
523             (!T->isDependentType() && !T->isConstantSizeType())) {
524    // Per C99, a variable array is an array with either a non-constant
525    // size or an element type that has a non-constant-size
526    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
527  } else {
528    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
529    // have a value greater than zero.
530    if (ConstVal.isSigned()) {
531      if (ConstVal.isNegative()) {
532        Diag(ArraySize->getLocStart(),
533             diag::err_typecheck_negative_array_size)
534          << ArraySize->getSourceRange();
535        return QualType();
536      } else if (ConstVal == 0) {
537        // GCC accepts zero sized static arrays.
538        Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
539          << ArraySize->getSourceRange();
540      }
541    }
542    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
543  }
544  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
545  if (!getLangOptions().C99) {
546    if (ArraySize && !ArraySize->isTypeDependent() &&
547        !ArraySize->isValueDependent() &&
548        !ArraySize->isIntegerConstantExpr(Context))
549      Diag(Loc, diag::ext_vla);
550    else if (ASM != ArrayType::Normal || Quals != 0)
551      Diag(Loc, diag::ext_c99_array_usage);
552  }
553
554  return T;
555}
556
557/// \brief Build an ext-vector type.
558///
559/// Run the required checks for the extended vector type.
560QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
561                                  SourceLocation AttrLoc) {
562
563  Expr *Arg = (Expr *)ArraySize.get();
564
565  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
566  // in conjunction with complex types (pointers, arrays, functions, etc.).
567  if (!T->isDependentType() &&
568      !T->isIntegerType() && !T->isRealFloatingType()) {
569    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
570    return QualType();
571  }
572
573  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
574    llvm::APSInt vecSize(32);
575    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
576      Diag(AttrLoc, diag::err_attribute_argument_not_int)
577      << "ext_vector_type" << Arg->getSourceRange();
578      return QualType();
579    }
580
581    // unlike gcc's vector_size attribute, the size is specified as the
582    // number of elements, not the number of bytes.
583    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
584
585    if (vectorSize == 0) {
586      Diag(AttrLoc, diag::err_attribute_zero_size)
587      << Arg->getSourceRange();
588      return QualType();
589    }
590
591    if (!T->isDependentType())
592      return Context.getExtVectorType(T, vectorSize);
593  }
594
595  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
596                                                AttrLoc);
597}
598
599/// \brief Build a function type.
600///
601/// This routine checks the function type according to C++ rules and
602/// under the assumption that the result type and parameter types have
603/// just been instantiated from a template. It therefore duplicates
604/// some of the behavior of GetTypeForDeclarator, but in a much
605/// simpler form that is only suitable for this narrow use case.
606///
607/// \param T The return type of the function.
608///
609/// \param ParamTypes The parameter types of the function. This array
610/// will be modified to account for adjustments to the types of the
611/// function parameters.
612///
613/// \param NumParamTypes The number of parameter types in ParamTypes.
614///
615/// \param Variadic Whether this is a variadic function type.
616///
617/// \param Quals The cvr-qualifiers to be applied to the function type.
618///
619/// \param Loc The location of the entity whose type involves this
620/// function type or, if there is no such entity, the location of the
621/// type that will have function type.
622///
623/// \param Entity The name of the entity that involves the function
624/// type, if known.
625///
626/// \returns A suitable function type, if there are no
627/// errors. Otherwise, returns a NULL type.
628QualType Sema::BuildFunctionType(QualType T,
629                                 QualType *ParamTypes,
630                                 unsigned NumParamTypes,
631                                 bool Variadic, unsigned Quals,
632                                 SourceLocation Loc, DeclarationName Entity) {
633  if (T->isArrayType() || T->isFunctionType()) {
634    Diag(Loc, diag::err_func_returning_array_function) << T;
635    return QualType();
636  }
637
638  bool Invalid = false;
639  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
640    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
641    if (ParamType->isVoidType()) {
642      Diag(Loc, diag::err_param_with_void_type);
643      Invalid = true;
644    }
645
646    ParamTypes[Idx] = ParamType;
647  }
648
649  if (Invalid)
650    return QualType();
651
652  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
653                                 Quals);
654}
655
656/// \brief Build a member pointer type \c T Class::*.
657///
658/// \param T the type to which the member pointer refers.
659/// \param Class the class type into which the member pointer points.
660/// \param Quals Qualifiers applied to the member pointer type
661/// \param Loc the location where this type begins
662/// \param Entity the name of the entity that will have this member pointer type
663///
664/// \returns a member pointer type, if successful, or a NULL type if there was
665/// an error.
666QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
667                                      unsigned Quals, SourceLocation Loc,
668                                      DeclarationName Entity) {
669  // Verify that we're not building a pointer to pointer to function with
670  // exception specification.
671  if (CheckDistantExceptionSpec(T)) {
672    Diag(Loc, diag::err_distant_exception_spec);
673
674    // FIXME: If we're doing this as part of template instantiation,
675    // we should return immediately.
676
677    // Build the type anyway, but use the canonical type so that the
678    // exception specifiers are stripped off.
679    T = Context.getCanonicalType(T);
680  }
681
682  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
683  //   with reference type, or "cv void."
684  if (T->isReferenceType()) {
685    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
686      << (Entity? Entity.getAsString() : "type name");
687    return QualType();
688  }
689
690  if (T->isVoidType()) {
691    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
692      << (Entity? Entity.getAsString() : "type name");
693    return QualType();
694  }
695
696  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
697  // object or incomplete types shall not be restrict-qualified."
698  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
699    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
700      << T;
701
702    // FIXME: If we're doing this as part of template instantiation,
703    // we should return immediately.
704    Quals &= ~QualType::Restrict;
705  }
706
707  if (!Class->isDependentType() && !Class->isRecordType()) {
708    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
709    return QualType();
710  }
711
712  return Context.getMemberPointerType(T, Class.getTypePtr())
713           .getQualifiedType(Quals);
714}
715
716/// \brief Build a block pointer type.
717///
718/// \param T The type to which we'll be building a block pointer.
719///
720/// \param Quals The cvr-qualifiers to be applied to the block pointer type.
721///
722/// \param Loc The location of the entity whose type involves this
723/// block pointer type or, if there is no such entity, the location of the
724/// type that will have block pointer type.
725///
726/// \param Entity The name of the entity that involves the block pointer
727/// type, if known.
728///
729/// \returns A suitable block pointer type, if there are no
730/// errors. Otherwise, returns a NULL type.
731QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals,
732                                     SourceLocation Loc,
733                                     DeclarationName Entity) {
734  if (!T.getTypePtr()->isFunctionType()) {
735    Diag(Loc, diag::err_nonfunction_block_type);
736    return QualType();
737  }
738
739  return Context.getBlockPointerType(T).getQualifiedType(Quals);
740}
741
742/// GetTypeForDeclarator - Convert the type for the specified
743/// declarator to Type instances. Skip the outermost Skip type
744/// objects.
745///
746/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
747/// owns the declaration of a type (e.g., the definition of a struct
748/// type), then *OwnedDecl will receive the owned declaration.
749QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip,
750                                    TagDecl **OwnedDecl) {
751  bool OmittedReturnType = false;
752
753  if (D.getContext() == Declarator::BlockLiteralContext
754      && Skip == 0
755      && !D.getDeclSpec().hasTypeSpecifier()
756      && (D.getNumTypeObjects() == 0
757          || (D.getNumTypeObjects() == 1
758              && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
759    OmittedReturnType = true;
760
761  // long long is a C99 feature.
762  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
763      D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
764    Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
765
766  // Determine the type of the declarator. Not all forms of declarator
767  // have a type.
768  QualType T;
769  switch (D.getKind()) {
770  case Declarator::DK_Abstract:
771  case Declarator::DK_Normal:
772  case Declarator::DK_Operator: {
773    const DeclSpec &DS = D.getDeclSpec();
774    if (OmittedReturnType) {
775      // We default to a dependent type initially.  Can be modified by
776      // the first return statement.
777      T = Context.DependentTy;
778    } else {
779      bool isInvalid = false;
780      T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
781      if (isInvalid)
782        D.setInvalidType(true);
783      else if (OwnedDecl && DS.isTypeSpecOwned())
784        *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep());
785    }
786    break;
787  }
788
789  case Declarator::DK_Constructor:
790  case Declarator::DK_Destructor:
791  case Declarator::DK_Conversion:
792    // Constructors and destructors don't have return types. Use
793    // "void" instead. Conversion operators will check their return
794    // types separately.
795    T = Context.VoidTy;
796    break;
797  }
798
799  // The name we're declaring, if any.
800  DeclarationName Name;
801  if (D.getIdentifier())
802    Name = D.getIdentifier();
803
804  // Walk the DeclTypeInfo, building the recursive type as we go.
805  // DeclTypeInfos are ordered from the identifier out, which is
806  // opposite of what we want :).
807  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
808    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
809    switch (DeclType.Kind) {
810    default: assert(0 && "Unknown decltype!");
811    case DeclaratorChunk::BlockPointer:
812      // If blocks are disabled, emit an error.
813      if (!LangOpts.Blocks)
814        Diag(DeclType.Loc, diag::err_blocks_disable);
815
816      T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
817                                Name);
818      break;
819    case DeclaratorChunk::Pointer:
820      // Verify that we're not building a pointer to pointer to function with
821      // exception specification.
822      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
823        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
824        D.setInvalidType(true);
825        // Build the type anyway.
826      }
827      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
828      break;
829    case DeclaratorChunk::Reference:
830      // Verify that we're not building a reference to pointer to function with
831      // exception specification.
832      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
833        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
834        D.setInvalidType(true);
835        // Build the type anyway.
836      }
837      T = BuildReferenceType(T, DeclType.Ref.LValueRef,
838                             DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
839                             DeclType.Loc, Name);
840      break;
841    case DeclaratorChunk::Array: {
842      // Verify that we're not building an array of pointers to function with
843      // exception specification.
844      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
845        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
846        D.setInvalidType(true);
847        // Build the type anyway.
848      }
849      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
850      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
851      ArrayType::ArraySizeModifier ASM;
852      if (ATI.isStar)
853        ASM = ArrayType::Star;
854      else if (ATI.hasStatic)
855        ASM = ArrayType::Static;
856      else
857        ASM = ArrayType::Normal;
858      if (ASM == ArrayType::Star &&
859          D.getContext() != Declarator::PrototypeContext) {
860        // FIXME: This check isn't quite right: it allows star in prototypes
861        // for function definitions, and disallows some edge cases detailed
862        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
863        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
864        ASM = ArrayType::Normal;
865        D.setInvalidType(true);
866      }
867      T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
868      break;
869    }
870    case DeclaratorChunk::Function: {
871      // If the function declarator has a prototype (i.e. it is not () and
872      // does not have a K&R-style identifier list), then the arguments are part
873      // of the type, otherwise the argument list is ().
874      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
875
876      // C99 6.7.5.3p1: The return type may not be a function or array type.
877      if (T->isArrayType() || T->isFunctionType()) {
878        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
879        T = Context.IntTy;
880        D.setInvalidType(true);
881      }
882
883      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
884        // C++ [dcl.fct]p6:
885        //   Types shall not be defined in return or parameter types.
886        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
887        if (Tag->isDefinition())
888          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
889            << Context.getTypeDeclType(Tag);
890      }
891
892      // Exception specs are not allowed in typedefs. Complain, but add it
893      // anyway.
894      if (FTI.hasExceptionSpec &&
895          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
896        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
897
898      if (FTI.NumArgs == 0) {
899        if (getLangOptions().CPlusPlus) {
900          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
901          // function takes no arguments.
902          llvm::SmallVector<QualType, 4> Exceptions;
903          Exceptions.reserve(FTI.NumExceptions);
904          for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
905            QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
906            // Check that the type is valid for an exception spec, and drop it
907            // if not.
908            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
909              Exceptions.push_back(ET);
910          }
911          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
912                                      FTI.hasExceptionSpec,
913                                      FTI.hasAnyExceptionSpec,
914                                      Exceptions.size(), Exceptions.data());
915        } else if (FTI.isVariadic) {
916          // We allow a zero-parameter variadic function in C if the
917          // function is marked with the "overloadable"
918          // attribute. Scan for this attribute now.
919          bool Overloadable = false;
920          for (const AttributeList *Attrs = D.getAttributes();
921               Attrs; Attrs = Attrs->getNext()) {
922            if (Attrs->getKind() == AttributeList::AT_overloadable) {
923              Overloadable = true;
924              break;
925            }
926          }
927
928          if (!Overloadable)
929            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
930          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
931        } else {
932          // Simple void foo(), where the incoming T is the result type.
933          T = Context.getFunctionNoProtoType(T);
934        }
935      } else if (FTI.ArgInfo[0].Param == 0) {
936        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
937        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
938      } else {
939        // Otherwise, we have a function with an argument list that is
940        // potentially variadic.
941        llvm::SmallVector<QualType, 16> ArgTys;
942
943        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
944          ParmVarDecl *Param =
945            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
946          QualType ArgTy = Param->getType();
947          assert(!ArgTy.isNull() && "Couldn't parse type?");
948
949          // Adjust the parameter type.
950          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
951
952          // Look for 'void'.  void is allowed only as a single argument to a
953          // function with no other parameters (C99 6.7.5.3p10).  We record
954          // int(void) as a FunctionProtoType with an empty argument list.
955          if (ArgTy->isVoidType()) {
956            // If this is something like 'float(int, void)', reject it.  'void'
957            // is an incomplete type (C99 6.2.5p19) and function decls cannot
958            // have arguments of incomplete type.
959            if (FTI.NumArgs != 1 || FTI.isVariadic) {
960              Diag(DeclType.Loc, diag::err_void_only_param);
961              ArgTy = Context.IntTy;
962              Param->setType(ArgTy);
963            } else if (FTI.ArgInfo[i].Ident) {
964              // Reject, but continue to parse 'int(void abc)'.
965              Diag(FTI.ArgInfo[i].IdentLoc,
966                   diag::err_param_with_void_type);
967              ArgTy = Context.IntTy;
968              Param->setType(ArgTy);
969            } else {
970              // Reject, but continue to parse 'float(const void)'.
971              if (ArgTy.getCVRQualifiers())
972                Diag(DeclType.Loc, diag::err_void_param_qualified);
973
974              // Do not add 'void' to the ArgTys list.
975              break;
976            }
977          } else if (!FTI.hasPrototype) {
978            if (ArgTy->isPromotableIntegerType()) {
979              ArgTy = Context.IntTy;
980            } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
981              if (BTy->getKind() == BuiltinType::Float)
982                ArgTy = Context.DoubleTy;
983            }
984          }
985
986          ArgTys.push_back(ArgTy);
987        }
988
989        llvm::SmallVector<QualType, 4> Exceptions;
990        Exceptions.reserve(FTI.NumExceptions);
991        for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
992          QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
993          // Check that the type is valid for an exception spec, and drop it if
994          // not.
995          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
996            Exceptions.push_back(ET);
997        }
998
999        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1000                                    FTI.isVariadic, FTI.TypeQuals,
1001                                    FTI.hasExceptionSpec,
1002                                    FTI.hasAnyExceptionSpec,
1003                                    Exceptions.size(), Exceptions.data());
1004      }
1005      break;
1006    }
1007    case DeclaratorChunk::MemberPointer:
1008      // The scope spec must refer to a class, or be dependent.
1009      QualType ClsType;
1010      if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
1011        NestedNameSpecifier *NNS
1012          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1013        assert(NNS->getAsType() && "Nested-name-specifier must name a type");
1014        ClsType = QualType(NNS->getAsType(), 0);
1015      } else if (CXXRecordDecl *RD
1016                   = dyn_cast_or_null<CXXRecordDecl>(
1017                                    computeDeclContext(DeclType.Mem.Scope()))) {
1018        ClsType = Context.getTagDeclType(RD);
1019      } else {
1020        Diag(DeclType.Mem.Scope().getBeginLoc(),
1021             diag::err_illegal_decl_mempointer_in_nonclass)
1022          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1023          << DeclType.Mem.Scope().getRange();
1024        D.setInvalidType(true);
1025      }
1026
1027      if (!ClsType.isNull())
1028        T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1029                                   DeclType.Loc, D.getIdentifier());
1030      if (T.isNull()) {
1031        T = Context.IntTy;
1032        D.setInvalidType(true);
1033      }
1034      break;
1035    }
1036
1037    if (T.isNull()) {
1038      D.setInvalidType(true);
1039      T = Context.IntTy;
1040    }
1041
1042    // See if there are any attributes on this declarator chunk.
1043    if (const AttributeList *AL = DeclType.getAttrs())
1044      ProcessTypeAttributeList(T, AL);
1045  }
1046
1047  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1048    const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
1049    assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
1050
1051    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1052    // for a nonstatic member function, the function type to which a pointer
1053    // to member refers, or the top-level function type of a function typedef
1054    // declaration.
1055    if (FnTy->getTypeQuals() != 0 &&
1056        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1057        ((D.getContext() != Declarator::MemberContext &&
1058          (!D.getCXXScopeSpec().isSet() ||
1059           !computeDeclContext(D.getCXXScopeSpec())->isRecord())) ||
1060         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1061      if (D.isFunctionDeclarator())
1062        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1063      else
1064        Diag(D.getIdentifierLoc(),
1065             diag::err_invalid_qualified_typedef_function_type_use);
1066
1067      // Strip the cv-quals from the type.
1068      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1069                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1070    }
1071  }
1072
1073  // If there were any type attributes applied to the decl itself (not the
1074  // type, apply the type attribute to the type!)
1075  if (const AttributeList *Attrs = D.getAttributes())
1076    ProcessTypeAttributeList(T, Attrs);
1077
1078  return T;
1079}
1080
1081/// CheckSpecifiedExceptionType - Check if the given type is valid in an
1082/// exception specification. Incomplete types, or pointers to incomplete types
1083/// other than void are not allowed.
1084bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1085  // FIXME: This may not correctly work with the fix for core issue 437,
1086  // where a class's own type is considered complete within its body.
1087
1088  // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1089  //   an incomplete type.
1090  if (T->isIncompleteType())
1091    return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1092      << Range << T << /*direct*/0;
1093
1094  // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1095  //   an incomplete type a pointer or reference to an incomplete type, other
1096  //   than (cv) void*.
1097  int kind;
1098  if (const PointerType* IT = T->getAsPointerType()) {
1099    T = IT->getPointeeType();
1100    kind = 1;
1101  } else if (const ReferenceType* IT = T->getAsReferenceType()) {
1102    T = IT->getPointeeType();
1103    kind = 2;
1104  } else
1105    return false;
1106
1107  if (T->isIncompleteType() && !T->isVoidType())
1108    return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1109      << Range << T << /*indirect*/kind;
1110
1111  return false;
1112}
1113
1114/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1115/// to member to a function with an exception specification. This means that
1116/// it is invalid to add another level of indirection.
1117bool Sema::CheckDistantExceptionSpec(QualType T) {
1118  if (const PointerType *PT = T->getAsPointerType())
1119    T = PT->getPointeeType();
1120  else if (const MemberPointerType *PT = T->getAsMemberPointerType())
1121    T = PT->getPointeeType();
1122  else
1123    return false;
1124
1125  const FunctionProtoType *FnT = T->getAsFunctionProtoType();
1126  if (!FnT)
1127    return false;
1128
1129  return FnT->hasExceptionSpec();
1130}
1131
1132/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1133/// declarator
1134QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1135  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1136  QualType T = MDecl->getResultType();
1137  llvm::SmallVector<QualType, 16> ArgTys;
1138
1139  // Add the first two invisible argument types for self and _cmd.
1140  if (MDecl->isInstanceMethod()) {
1141    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1142    selfTy = Context.getPointerType(selfTy);
1143    ArgTys.push_back(selfTy);
1144  } else
1145    ArgTys.push_back(Context.getObjCIdType());
1146  ArgTys.push_back(Context.getObjCSelType());
1147
1148  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1149       E = MDecl->param_end(); PI != E; ++PI) {
1150    QualType ArgTy = (*PI)->getType();
1151    assert(!ArgTy.isNull() && "Couldn't parse type?");
1152    ArgTy = adjustParameterType(ArgTy);
1153    ArgTys.push_back(ArgTy);
1154  }
1155  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1156                              MDecl->isVariadic(), 0);
1157  return T;
1158}
1159
1160/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1161/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1162/// they point to and return true. If T1 and T2 aren't pointer types
1163/// or pointer-to-member types, or if they are not similar at this
1164/// level, returns false and leaves T1 and T2 unchanged. Top-level
1165/// qualifiers on T1 and T2 are ignored. This function will typically
1166/// be called in a loop that successively "unwraps" pointer and
1167/// pointer-to-member types to compare them at each level.
1168bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1169  const PointerType *T1PtrType = T1->getAsPointerType(),
1170                    *T2PtrType = T2->getAsPointerType();
1171  if (T1PtrType && T2PtrType) {
1172    T1 = T1PtrType->getPointeeType();
1173    T2 = T2PtrType->getPointeeType();
1174    return true;
1175  }
1176
1177  const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
1178                          *T2MPType = T2->getAsMemberPointerType();
1179  if (T1MPType && T2MPType &&
1180      Context.getCanonicalType(T1MPType->getClass()) ==
1181      Context.getCanonicalType(T2MPType->getClass())) {
1182    T1 = T1MPType->getPointeeType();
1183    T2 = T2MPType->getPointeeType();
1184    return true;
1185  }
1186  return false;
1187}
1188
1189Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1190  // C99 6.7.6: Type names have no identifier.  This is already validated by
1191  // the parser.
1192  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1193
1194  TagDecl *OwnedTag = 0;
1195  QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
1196  if (D.isInvalidType())
1197    return true;
1198
1199  if (getLangOptions().CPlusPlus) {
1200    // Check that there are no default arguments (C++ only).
1201    CheckExtraCXXDefaultArguments(D);
1202
1203    // C++0x [dcl.type]p3:
1204    //   A type-specifier-seq shall not define a class or enumeration
1205    //   unless it appears in the type-id of an alias-declaration
1206    //   (7.1.3).
1207    if (OwnedTag && OwnedTag->isDefinition())
1208      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1209        << Context.getTypeDeclType(OwnedTag);
1210  }
1211
1212  return T.getAsOpaquePtr();
1213}
1214
1215
1216
1217//===----------------------------------------------------------------------===//
1218// Type Attribute Processing
1219//===----------------------------------------------------------------------===//
1220
1221/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1222/// specified type.  The attribute contains 1 argument, the id of the address
1223/// space for the type.
1224static void HandleAddressSpaceTypeAttribute(QualType &Type,
1225                                            const AttributeList &Attr, Sema &S){
1226  // If this type is already address space qualified, reject it.
1227  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1228  // for two or more different address spaces."
1229  if (Type.getAddressSpace()) {
1230    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1231    return;
1232  }
1233
1234  // Check the attribute arguments.
1235  if (Attr.getNumArgs() != 1) {
1236    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1237    return;
1238  }
1239  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1240  llvm::APSInt addrSpace(32);
1241  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1242    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1243      << ASArgExpr->getSourceRange();
1244    return;
1245  }
1246
1247  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1248  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1249}
1250
1251/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1252/// specified type.  The attribute contains 1 argument, weak or strong.
1253static void HandleObjCGCTypeAttribute(QualType &Type,
1254                                      const AttributeList &Attr, Sema &S) {
1255  if (Type.getObjCGCAttr() != QualType::GCNone) {
1256    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1257    return;
1258  }
1259
1260  // Check the attribute arguments.
1261  if (!Attr.getParameterName()) {
1262    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1263      << "objc_gc" << 1;
1264    return;
1265  }
1266  QualType::GCAttrTypes GCAttr;
1267  if (Attr.getNumArgs() != 0) {
1268    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1269    return;
1270  }
1271  if (Attr.getParameterName()->isStr("weak"))
1272    GCAttr = QualType::Weak;
1273  else if (Attr.getParameterName()->isStr("strong"))
1274    GCAttr = QualType::Strong;
1275  else {
1276    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1277      << "objc_gc" << Attr.getParameterName();
1278    return;
1279  }
1280
1281  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1282}
1283
1284void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1285  // Scan through and apply attributes to this type where it makes sense.  Some
1286  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1287  // type, but others can be present in the type specifiers even though they
1288  // apply to the decl.  Here we apply type attributes and ignore the rest.
1289  for (; AL; AL = AL->getNext()) {
1290    // If this is an attribute we can handle, do so now, otherwise, add it to
1291    // the LeftOverAttrs list for rechaining.
1292    switch (AL->getKind()) {
1293    default: break;
1294    case AttributeList::AT_address_space:
1295      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1296      break;
1297    case AttributeList::AT_objc_gc:
1298      HandleObjCGCTypeAttribute(Result, *AL, *this);
1299      break;
1300    }
1301  }
1302}
1303
1304/// @brief Ensure that the type T is a complete type.
1305///
1306/// This routine checks whether the type @p T is complete in any
1307/// context where a complete type is required. If @p T is a complete
1308/// type, returns false. If @p T is a class template specialization,
1309/// this routine then attempts to perform class template
1310/// instantiation. If instantiation fails, or if @p T is incomplete
1311/// and cannot be completed, issues the diagnostic @p diag (giving it
1312/// the type @p T) and returns true.
1313///
1314/// @param Loc  The location in the source that the incomplete type
1315/// diagnostic should refer to.
1316///
1317/// @param T  The type that this routine is examining for completeness.
1318///
1319/// @param diag The diagnostic value (e.g.,
1320/// @c diag::err_typecheck_decl_incomplete_type) that will be used
1321/// for the error message if @p T is incomplete.
1322///
1323/// @param Range1  An optional range in the source code that will be a
1324/// part of the "incomplete type" error message.
1325///
1326/// @param Range2  An optional range in the source code that will be a
1327/// part of the "incomplete type" error message.
1328///
1329/// @param PrintType If non-NULL, the type that should be printed
1330/// instead of @p T. This parameter should be used when the type that
1331/// we're checking for incompleteness isn't the type that should be
1332/// displayed to the user, e.g., when T is a type and PrintType is a
1333/// pointer to T.
1334///
1335/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1336/// @c false otherwise.
1337bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1338                               SourceRange Range1, SourceRange Range2,
1339                               QualType PrintType) {
1340  // FIXME: Add this assertion to help us flush out problems with
1341  // checking for dependent types and type-dependent expressions.
1342  //
1343  //  assert(!T->isDependentType() &&
1344  //         "Can't ask whether a dependent type is complete");
1345
1346  // If we have a complete type, we're done.
1347  if (!T->isIncompleteType())
1348    return false;
1349
1350  // If we have a class template specialization or a class member of a
1351  // class template specialization, try to instantiate it.
1352  if (const RecordType *Record = T->getAsRecordType()) {
1353    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1354          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1355      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1356        // Update the class template specialization's location to
1357        // refer to the point of instantiation.
1358        if (Loc.isValid())
1359          ClassTemplateSpec->setLocation(Loc);
1360        return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1361                                             /*ExplicitInstantiation=*/false);
1362      }
1363    } else if (CXXRecordDecl *Rec
1364                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1365      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1366        // Find the class template specialization that surrounds this
1367        // member class.
1368        ClassTemplateSpecializationDecl *Spec = 0;
1369        for (DeclContext *Parent = Rec->getDeclContext();
1370             Parent && !Spec; Parent = Parent->getParent())
1371          Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1372        assert(Spec && "Not a member of a class template specialization?");
1373        return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(),
1374                                /*ExplicitInstantiation=*/false);
1375      }
1376    }
1377  }
1378
1379  if (PrintType.isNull())
1380    PrintType = T;
1381
1382  // We have an incomplete type. Produce a diagnostic.
1383  Diag(Loc, diag) << PrintType << Range1 << Range2;
1384
1385  // If the type was a forward declaration of a class/struct/union
1386  // type, produce
1387  const TagType *Tag = 0;
1388  if (const RecordType *Record = T->getAsRecordType())
1389    Tag = Record;
1390  else if (const EnumType *Enum = T->getAsEnumType())
1391    Tag = Enum;
1392
1393  if (Tag && !Tag->getDecl()->isInvalidDecl())
1394    Diag(Tag->getDecl()->getLocation(),
1395         Tag->isBeingDefined() ? diag::note_type_being_defined
1396                               : diag::note_forward_declaration)
1397        << QualType(Tag, 0);
1398
1399  return true;
1400}
1401
1402/// \brief Retrieve a version of the type 'T' that is qualified by the
1403/// nested-name-specifier contained in SS.
1404QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1405  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1406    return T;
1407
1408  NestedNameSpecifier *NNS
1409    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1410  return Context.getQualifiedNameType(NNS, T);
1411}
1412