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