SemaType.cpp revision 253fc4d146d4815c9a4ef15a7196edb2e7831865
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 Convert the specified declspec to the appropriate type
23/// object.
24/// \param DS  the declaration specifiers
25/// \returns The type described by the declaration specifiers, or NULL
26/// if there was an error.
27QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS) {
28  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
29  // checking.
30  QualType Result;
31
32  switch (DS.getTypeSpecType()) {
33  case DeclSpec::TST_void:
34    Result = Context.VoidTy;
35    break;
36  case DeclSpec::TST_char:
37    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
38      Result = Context.CharTy;
39    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
40      Result = Context.SignedCharTy;
41    else {
42      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
43             "Unknown TSS value");
44      Result = Context.UnsignedCharTy;
45    }
46    break;
47  case DeclSpec::TST_wchar:
48    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
49      Result = Context.WCharTy;
50    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
51      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
52        << DS.getSpecifierName(DS.getTypeSpecType());
53      Result = Context.getSignedWCharType();
54    } else {
55      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
56        "Unknown TSS value");
57      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
58        << DS.getSpecifierName(DS.getTypeSpecType());
59      Result = Context.getUnsignedWCharType();
60    }
61    break;
62  case DeclSpec::TST_unspecified:
63    // "<proto1,proto2>" is an objc qualified ID with a missing id.
64    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
65      Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
66                                              DS.getNumProtocolQualifiers());
67      break;
68    }
69
70    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
71    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
72    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
73    // Note that the one exception to this is function definitions, which are
74    // allowed to be completely missing a declspec.  This is handled in the
75    // parser already though by it pretending to have seen an 'int' in this
76    // case.
77    if (getLangOptions().ImplicitInt) {
78      // In C89 mode, we only warn if there is a completely missing declspec
79      // when one is not allowed.
80      if (DS.isEmpty())
81        Diag(DS.getSourceRange().getBegin(), diag::warn_missing_declspec)
82        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
83                                                 "int");
84    } else if (!DS.hasTypeSpecifier()) {
85      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
86      // "At least one type specifier shall be given in the declaration
87      // specifiers in each declaration, and in the specifier-qualifier list in
88      // each struct declaration and type name."
89      // FIXME: Does Microsoft really have the implicit int extension in C++?
90      unsigned DK = getLangOptions().CPlusPlus && !getLangOptions().Microsoft?
91          diag::err_missing_type_specifier
92        : diag::warn_missing_type_specifier;
93      Diag(DS.getSourceRange().getBegin(), DK)
94        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
95                                                 "int");
96    }
97
98    // FALL THROUGH.
99  case DeclSpec::TST_int: {
100    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
101      switch (DS.getTypeSpecWidth()) {
102      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
103      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
104      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
105      case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
106      }
107    } else {
108      switch (DS.getTypeSpecWidth()) {
109      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
110      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
111      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
112      case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
113      }
114    }
115    break;
116  }
117  case DeclSpec::TST_float: Result = Context.FloatTy; break;
118  case DeclSpec::TST_double:
119    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
120      Result = Context.LongDoubleTy;
121    else
122      Result = Context.DoubleTy;
123    break;
124  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
125  case DeclSpec::TST_decimal32:    // _Decimal32
126  case DeclSpec::TST_decimal64:    // _Decimal64
127  case DeclSpec::TST_decimal128:   // _Decimal128
128    assert(0 && "FIXME: GNU decimal extensions not supported yet!");
129  case DeclSpec::TST_class:
130  case DeclSpec::TST_enum:
131  case DeclSpec::TST_union:
132  case DeclSpec::TST_struct: {
133    Decl *D = static_cast<Decl *>(DS.getTypeRep());
134    assert(D && "Didn't get a decl for a class/enum/union/struct?");
135    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
136           DS.getTypeSpecSign() == 0 &&
137           "Can't handle qualifiers on typedef names yet!");
138    // TypeQuals handled by caller.
139    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
140    break;
141  }
142  case DeclSpec::TST_typename: {
143    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
144           DS.getTypeSpecSign() == 0 &&
145           "Can't handle qualifiers on typedef names yet!");
146    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
147
148    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
149      // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so
150      // we have this "hack" for now...
151      if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
152        Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
153                                                       (ObjCProtocolDecl**)PQ,
154                                               DS.getNumProtocolQualifiers());
155      else if (Result == Context.getObjCIdType())
156        // id<protocol-list>
157        Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
158                                                DS.getNumProtocolQualifiers());
159      else if (Result == Context.getObjCClassType())
160        // Class<protocol-list>
161        Diag(DS.getSourceRange().getBegin(),
162             diag::err_qualified_class_unsupported) << DS.getSourceRange();
163      else
164        Diag(DS.getSourceRange().getBegin(),
165             diag::err_invalid_protocol_qualifiers) << DS.getSourceRange();
166    }
167    // TypeQuals handled by caller.
168    break;
169  }
170  case DeclSpec::TST_typeofType:
171    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
172    assert(!Result.isNull() && "Didn't get a type for typeof?");
173    // TypeQuals handled by caller.
174    Result = Context.getTypeOfType(Result);
175    break;
176  case DeclSpec::TST_typeofExpr: {
177    Expr *E = static_cast<Expr *>(DS.getTypeRep());
178    assert(E && "Didn't get an expression for typeof?");
179    // TypeQuals handled by caller.
180    Result = Context.getTypeOfExprType(E);
181    break;
182  }
183  case DeclSpec::TST_error:
184    return QualType();
185  }
186
187  // Handle complex types.
188  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
189    if (getLangOptions().Freestanding)
190      Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
191    Result = Context.getComplexType(Result);
192  }
193
194  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
195         "FIXME: imaginary types not supported yet!");
196
197  // See if there are any attributes on the declspec that apply to the type (as
198  // opposed to the decl).
199  if (const AttributeList *AL = DS.getAttributes())
200    ProcessTypeAttributeList(Result, AL);
201
202  // Apply const/volatile/restrict qualifiers to T.
203  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
204
205    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
206    // or incomplete types shall not be restrict-qualified."  C++ also allows
207    // restrict-qualified references.
208    if (TypeQuals & QualType::Restrict) {
209      if (Result->isPointerType() || Result->isReferenceType()) {
210        QualType EltTy = Result->isPointerType() ?
211          Result->getAsPointerType()->getPointeeType() :
212          Result->getAsReferenceType()->getPointeeType();
213
214        // If we have a pointer or reference, the pointee must have an object or
215        // incomplete type.
216        if (!EltTy->isIncompleteOrObjectType()) {
217          Diag(DS.getRestrictSpecLoc(),
218               diag::err_typecheck_invalid_restrict_invalid_pointee)
219            << EltTy << DS.getSourceRange();
220          TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
221        }
222      } else {
223        Diag(DS.getRestrictSpecLoc(),
224             diag::err_typecheck_invalid_restrict_not_pointer)
225          << Result << DS.getSourceRange();
226        TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
227      }
228    }
229
230    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
231    // of a function type includes any type qualifiers, the behavior is
232    // undefined."
233    if (Result->isFunctionType() && TypeQuals) {
234      // Get some location to point at, either the C or V location.
235      SourceLocation Loc;
236      if (TypeQuals & QualType::Const)
237        Loc = DS.getConstSpecLoc();
238      else {
239        assert((TypeQuals & QualType::Volatile) &&
240               "Has CV quals but not C or V?");
241        Loc = DS.getVolatileSpecLoc();
242      }
243      Diag(Loc, diag::warn_typecheck_function_qualifiers)
244        << Result << DS.getSourceRange();
245    }
246
247    // C++ [dcl.ref]p1:
248    //   Cv-qualified references are ill-formed except when the
249    //   cv-qualifiers are introduced through the use of a typedef
250    //   (7.1.3) or of a template type argument (14.3), in which
251    //   case the cv-qualifiers are ignored.
252    // FIXME: Shouldn't we be checking SCS_typedef here?
253    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
254        TypeQuals && Result->isReferenceType()) {
255      TypeQuals &= ~QualType::Const;
256      TypeQuals &= ~QualType::Volatile;
257    }
258
259    Result = Result.getQualifiedType(TypeQuals);
260  }
261  return Result;
262}
263
264static std::string getPrintableNameForEntity(DeclarationName Entity) {
265  if (Entity)
266    return Entity.getAsString();
267
268  return "type name";
269}
270
271/// \brief Build a pointer type.
272///
273/// \param T The type to which we'll be building a pointer.
274///
275/// \param Quals The cvr-qualifiers to be applied to the pointer type.
276///
277/// \param Loc The location of the entity whose type involves this
278/// pointer type or, if there is no such entity, the location of the
279/// type that will have pointer type.
280///
281/// \param Entity The name of the entity that involves the pointer
282/// type, if known.
283///
284/// \returns A suitable pointer type, if there are no
285/// errors. Otherwise, returns a NULL type.
286QualType Sema::BuildPointerType(QualType T, unsigned Quals,
287                                SourceLocation Loc, DeclarationName Entity) {
288  if (T->isReferenceType()) {
289    // C++ 8.3.2p4: There shall be no ... pointers to references ...
290    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
291      << getPrintableNameForEntity(Entity);
292    return QualType();
293  }
294
295  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
296  // object or incomplete types shall not be restrict-qualified."
297  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
298    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
299      << T;
300    Quals &= ~QualType::Restrict;
301  }
302
303  // Build the pointer type.
304  return Context.getPointerType(T).getQualifiedType(Quals);
305}
306
307/// \brief Build a reference type.
308///
309/// \param T The type to which we'll be building a reference.
310///
311/// \param Quals The cvr-qualifiers to be applied to the reference type.
312///
313/// \param Loc The location of the entity whose type involves this
314/// reference type or, if there is no such entity, the location of the
315/// type that will have reference type.
316///
317/// \param Entity The name of the entity that involves the reference
318/// type, if known.
319///
320/// \returns A suitable reference type, if there are no
321/// errors. Otherwise, returns a NULL type.
322QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
323                                  SourceLocation Loc, DeclarationName Entity) {
324  if (LValueRef) {
325    if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
326      // FIXME: Find the C++0x reference for reference collapsing.
327      // In reference collapsing, lvalue refs win over rvalue refs.
328      return Context.getLValueReferenceType(R->getPointeeType()).
329               getQualifiedType(Quals);
330    }
331  }
332  if (T->isReferenceType()) {
333    // C++ [dcl.ref]p4: There shall be no references to references.
334    //
335    // According to C++ DR 106, references to references are only
336    // diagnosed when they are written directly (e.g., "int & &"),
337    // but not when they happen via a typedef:
338    //
339    //   typedef int& intref;
340    //   typedef intref& intref2;
341    //
342    // Parser::ParserDeclaratorInternal diagnoses the case where
343    // references are written directly; here, we handle the
344    // collapsing of references-to-references as described in C++
345    // DR 106 and amended by C++ DR 540.
346    return T;
347  }
348
349  // C++ [dcl.ref]p1:
350  //   A declarator that specifies the type “reference to cv void”
351  //   is ill-formed.
352  if (T->isVoidType()) {
353    Diag(Loc, diag::err_reference_to_void);
354    return QualType();
355  }
356
357  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
358  // object or incomplete types shall not be restrict-qualified."
359  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
360    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
361      << T;
362    Quals &= ~QualType::Restrict;
363  }
364
365  // C++ [dcl.ref]p1:
366  //   [...] Cv-qualified references are ill-formed except when the
367  //   cv-qualifiers are introduced through the use of a typedef
368  //   (7.1.3) or of a template type argument (14.3), in which case
369  //   the cv-qualifiers are ignored.
370  //
371  // We diagnose extraneous cv-qualifiers for the non-typedef,
372  // non-template type argument case within the parser. Here, we just
373  // ignore any extraneous cv-qualifiers.
374  Quals &= ~QualType::Const;
375  Quals &= ~QualType::Volatile;
376
377  // Handle restrict on references.
378  if (LValueRef)
379    return Context.getLValueReferenceType(T).getQualifiedType(Quals);
380  return Context.getRValueReferenceType(T).getQualifiedType(Quals);
381}
382
383/// \brief Build an array type.
384///
385/// \param T The type of each element in the array.
386///
387/// \param ASM C99 array size modifier (e.g., '*', 'static').
388///
389/// \param ArraySize Expression describing the size of the array.
390///
391/// \param Quals The cvr-qualifiers to be applied to the array's
392/// element type.
393///
394/// \param Loc The location of the entity whose type involves this
395/// array type or, if there is no such entity, the location of the
396/// type that will have array type.
397///
398/// \param Entity The name of the entity that involves the array
399/// type, if known.
400///
401/// \returns A suitable array type, if there are no errors. Otherwise,
402/// returns a NULL type.
403QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
404                              Expr *ArraySize, unsigned Quals,
405                              SourceLocation Loc, DeclarationName Entity) {
406  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
407  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
408  if (RequireCompleteType(Loc, T,
409                             diag::err_illegal_decl_array_incomplete_type))
410    return QualType();
411
412  if (T->isFunctionType()) {
413    Diag(Loc, diag::err_illegal_decl_array_of_functions)
414      << getPrintableNameForEntity(Entity);
415    return QualType();
416  }
417
418  // C++ 8.3.2p4: There shall be no ... arrays of references ...
419  if (T->isReferenceType()) {
420    Diag(Loc, diag::err_illegal_decl_array_of_references)
421      << getPrintableNameForEntity(Entity);
422    return QualType();
423  }
424
425  if (const RecordType *EltTy = T->getAsRecordType()) {
426    // If the element type is a struct or union that contains a variadic
427    // array, accept it as a GNU extension: C99 6.7.2.1p2.
428    if (EltTy->getDecl()->hasFlexibleArrayMember())
429      Diag(Loc, diag::ext_flexible_array_in_array) << T;
430  } else if (T->isObjCInterfaceType()) {
431    Diag(Loc, diag::warn_objc_array_of_interfaces) << T;
432  }
433
434  // C99 6.7.5.2p1: The size expression shall have integer type.
435  if (ArraySize && !ArraySize->isTypeDependent() &&
436      !ArraySize->getType()->isIntegerType()) {
437    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
438      << ArraySize->getType() << ArraySize->getSourceRange();
439    ArraySize->Destroy(Context);
440    return QualType();
441  }
442  llvm::APSInt ConstVal(32);
443  if (!ArraySize) {
444    T = Context.getIncompleteArrayType(T, ASM, Quals);
445  } else if (ArraySize->isValueDependent()) {
446    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
447  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
448             (!T->isDependentType() && !T->isConstantSizeType())) {
449    // Per C99, a variable array is an array with either a non-constant
450    // size or an element type that has a non-constant-size
451    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
452  } else {
453    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
454    // have a value greater than zero.
455    if (ConstVal.isSigned()) {
456      if (ConstVal.isNegative()) {
457        Diag(ArraySize->getLocStart(),
458             diag::err_typecheck_negative_array_size)
459          << ArraySize->getSourceRange();
460        return QualType();
461      } else if (ConstVal == 0) {
462        // GCC accepts zero sized static arrays.
463        Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
464          << ArraySize->getSourceRange();
465      }
466    }
467    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
468  }
469  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
470  if (!getLangOptions().C99) {
471    if (ArraySize && !ArraySize->isTypeDependent() &&
472        !ArraySize->isValueDependent() &&
473        !ArraySize->isIntegerConstantExpr(Context))
474      Diag(Loc, diag::ext_vla);
475    else if (ASM != ArrayType::Normal || Quals != 0)
476      Diag(Loc, diag::ext_c99_array_usage);
477  }
478
479  return T;
480}
481
482/// \brief Build a function type.
483///
484/// This routine checks the function type according to C++ rules and
485/// under the assumption that the result type and parameter types have
486/// just been instantiated from a template. It therefore duplicates
487/// some of the behavior of GetTypeForDeclarator, but in a much
488/// simpler form that is only suitable for this narrow use case.
489///
490/// \param T The return type of the function.
491///
492/// \param ParamTypes The parameter types of the function. This array
493/// will be modified to account for adjustments to the types of the
494/// function parameters.
495///
496/// \param NumParamTypes The number of parameter types in ParamTypes.
497///
498/// \param Variadic Whether this is a variadic function type.
499///
500/// \param Quals The cvr-qualifiers to be applied to the function type.
501///
502/// \param Loc The location of the entity whose type involves this
503/// function type or, if there is no such entity, the location of the
504/// type that will have function type.
505///
506/// \param Entity The name of the entity that involves the function
507/// type, if known.
508///
509/// \returns A suitable function type, if there are no
510/// errors. Otherwise, returns a NULL type.
511QualType Sema::BuildFunctionType(QualType T,
512                                 QualType *ParamTypes,
513                                 unsigned NumParamTypes,
514                                 bool Variadic, unsigned Quals,
515                                 SourceLocation Loc, DeclarationName Entity) {
516  if (T->isArrayType() || T->isFunctionType()) {
517    Diag(Loc, diag::err_func_returning_array_function) << T;
518    return QualType();
519  }
520
521  bool Invalid = false;
522  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
523    QualType ParamType = ParamTypes[Idx];
524    if (ParamType->isArrayType())
525      ParamType = Context.getArrayDecayedType(ParamType);
526    else if (ParamType->isFunctionType())
527      ParamType = Context.getPointerType(ParamType);
528    else if (ParamType->isVoidType()) {
529      Diag(Loc, diag::err_param_with_void_type);
530      Invalid = true;
531    }
532
533    ParamTypes[Idx] = ParamType;
534  }
535
536  if (Invalid)
537    return QualType();
538
539  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
540                                 Quals);
541}
542
543/// GetTypeForDeclarator - Convert the type for the specified
544/// declarator to Type instances. Skip the outermost Skip type
545/// objects.
546QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) {
547  bool OmittedReturnType = false;
548
549  if (D.getContext() == Declarator::BlockLiteralContext
550      && Skip == 0
551      && !D.getDeclSpec().hasTypeSpecifier()
552      && (D.getNumTypeObjects() == 0
553          || (D.getNumTypeObjects() == 1
554              && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
555    OmittedReturnType = true;
556
557  // long long is a C99 feature.
558  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
559      D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
560    Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
561
562  // Determine the type of the declarator. Not all forms of declarator
563  // have a type.
564  QualType T;
565  switch (D.getKind()) {
566  case Declarator::DK_Abstract:
567  case Declarator::DK_Normal:
568  case Declarator::DK_Operator: {
569    const DeclSpec& DS = D.getDeclSpec();
570    if (OmittedReturnType)
571      // We default to a dependent type initially.  Can be modified by
572      // the first return statement.
573      T = Context.DependentTy;
574    else {
575      T = ConvertDeclSpecToType(DS);
576      if (T.isNull())
577        return T;
578    }
579    break;
580  }
581
582  case Declarator::DK_Constructor:
583  case Declarator::DK_Destructor:
584  case Declarator::DK_Conversion:
585    // Constructors and destructors don't have return types. Use
586    // "void" instead. Conversion operators will check their return
587    // types separately.
588    T = Context.VoidTy;
589    break;
590  }
591
592  // The name we're declaring, if any.
593  DeclarationName Name;
594  if (D.getIdentifier())
595    Name = D.getIdentifier();
596
597  // Walk the DeclTypeInfo, building the recursive type as we go.
598  // DeclTypeInfos are ordered from the identifier out, which is
599  // opposite of what we want :).
600  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
601    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
602    switch (DeclType.Kind) {
603    default: assert(0 && "Unknown decltype!");
604    case DeclaratorChunk::BlockPointer:
605      if (DeclType.Cls.TypeQuals)
606        Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type);
607      if (!T.getTypePtr()->isFunctionType())
608        Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type);
609      else
610        T = Context.getBlockPointerType(T);
611      break;
612    case DeclaratorChunk::Pointer:
613      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
614      break;
615    case DeclaratorChunk::Reference:
616      T = BuildReferenceType(T, DeclType.Ref.LValueRef,
617                             DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
618                             DeclType.Loc, Name);
619      break;
620    case DeclaratorChunk::Array: {
621      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
622      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
623      ArrayType::ArraySizeModifier ASM;
624      if (ATI.isStar)
625        ASM = ArrayType::Star;
626      else if (ATI.hasStatic)
627        ASM = ArrayType::Static;
628      else
629        ASM = ArrayType::Normal;
630      T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
631      break;
632    }
633    case DeclaratorChunk::Function: {
634      // If the function declarator has a prototype (i.e. it is not () and
635      // does not have a K&R-style identifier list), then the arguments are part
636      // of the type, otherwise the argument list is ().
637      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
638
639      // C99 6.7.5.3p1: The return type may not be a function or array type.
640      if (T->isArrayType() || T->isFunctionType()) {
641        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
642        T = Context.IntTy;
643        D.setInvalidType(true);
644      }
645
646      if (FTI.NumArgs == 0) {
647        if (getLangOptions().CPlusPlus) {
648          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
649          // function takes no arguments.
650          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals);
651        } else if (FTI.isVariadic) {
652          // We allow a zero-parameter variadic function in C if the
653          // function is marked with the "overloadable"
654          // attribute. Scan for this attribute now.
655          bool Overloadable = false;
656          for (const AttributeList *Attrs = D.getAttributes();
657               Attrs; Attrs = Attrs->getNext()) {
658            if (Attrs->getKind() == AttributeList::AT_overloadable) {
659              Overloadable = true;
660              break;
661            }
662          }
663
664          if (!Overloadable)
665            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
666          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
667        } else {
668          // Simple void foo(), where the incoming T is the result type.
669          T = Context.getFunctionNoProtoType(T);
670        }
671      } else if (FTI.ArgInfo[0].Param == 0) {
672        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
673        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
674      } else {
675        // Otherwise, we have a function with an argument list that is
676        // potentially variadic.
677        llvm::SmallVector<QualType, 16> ArgTys;
678
679        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
680          ParmVarDecl *Param = (ParmVarDecl *)FTI.ArgInfo[i].Param;
681          QualType ArgTy = Param->getType();
682          assert(!ArgTy.isNull() && "Couldn't parse type?");
683          //
684          // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
685          // This matches the conversion that is done in
686          // Sema::ActOnParamDeclarator(). Without this conversion, the
687          // argument type in the function prototype *will not* match the
688          // type in ParmVarDecl (which makes the code generator unhappy).
689          //
690          // FIXME: We still apparently need the conversion in
691          // Sema::ActOnParamDeclarator(). This doesn't make any sense, since
692          // it should be driving off the type being created here.
693          //
694          // FIXME: If a source translation tool needs to see the original type,
695          // then we need to consider storing both types somewhere...
696          //
697          if (ArgTy->isArrayType()) {
698            ArgTy = Context.getArrayDecayedType(ArgTy);
699          } else if (ArgTy->isFunctionType())
700            ArgTy = Context.getPointerType(ArgTy);
701
702          // Look for 'void'.  void is allowed only as a single argument to a
703          // function with no other parameters (C99 6.7.5.3p10).  We record
704          // int(void) as a FunctionProtoType with an empty argument list.
705          else if (ArgTy->isVoidType()) {
706            // If this is something like 'float(int, void)', reject it.  'void'
707            // is an incomplete type (C99 6.2.5p19) and function decls cannot
708            // have arguments of incomplete type.
709            if (FTI.NumArgs != 1 || FTI.isVariadic) {
710              Diag(DeclType.Loc, diag::err_void_only_param);
711              ArgTy = Context.IntTy;
712              Param->setType(ArgTy);
713            } else if (FTI.ArgInfo[i].Ident) {
714              // Reject, but continue to parse 'int(void abc)'.
715              Diag(FTI.ArgInfo[i].IdentLoc,
716                   diag::err_param_with_void_type);
717              ArgTy = Context.IntTy;
718              Param->setType(ArgTy);
719            } else {
720              // Reject, but continue to parse 'float(const void)'.
721              if (ArgTy.getCVRQualifiers())
722                Diag(DeclType.Loc, diag::err_void_param_qualified);
723
724              // Do not add 'void' to the ArgTys list.
725              break;
726            }
727          } else if (!FTI.hasPrototype) {
728            if (ArgTy->isPromotableIntegerType()) {
729              ArgTy = Context.IntTy;
730            } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
731              if (BTy->getKind() == BuiltinType::Float)
732                ArgTy = Context.DoubleTy;
733            }
734          }
735
736          ArgTys.push_back(ArgTy);
737        }
738        T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
739                                    FTI.isVariadic, FTI.TypeQuals);
740      }
741      break;
742    }
743    case DeclaratorChunk::MemberPointer:
744      // The scope spec must refer to a class, or be dependent.
745      DeclContext *DC = getScopeRepAsDeclContext(DeclType.Mem.Scope());
746      QualType ClsType;
747      // FIXME: Extend for dependent types when it's actually supported.
748      // See ActOnCXXNestedNameSpecifier.
749      if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) {
750        ClsType = Context.getTagDeclType(RD);
751      } else {
752        if (DC) {
753          Diag(DeclType.Mem.Scope().getBeginLoc(),
754               diag::err_illegal_decl_mempointer_in_nonclass)
755            << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
756            << DeclType.Mem.Scope().getRange();
757        }
758        D.setInvalidType(true);
759        ClsType = Context.IntTy;
760      }
761
762      // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
763      //   with reference type, or "cv void."
764      if (T->isReferenceType()) {
765        Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference)
766          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
767        D.setInvalidType(true);
768        T = Context.IntTy;
769      }
770      if (T->isVoidType()) {
771        Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void)
772          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
773        T = Context.IntTy;
774      }
775
776      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
777      // object or incomplete types shall not be restrict-qualified."
778      if ((DeclType.Mem.TypeQuals & QualType::Restrict) &&
779          !T->isIncompleteOrObjectType()) {
780        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
781          << T;
782        DeclType.Mem.TypeQuals &= ~QualType::Restrict;
783      }
784
785      T = Context.getMemberPointerType(T, ClsType.getTypePtr()).
786                    getQualifiedType(DeclType.Mem.TypeQuals);
787
788      break;
789    }
790
791    if (T.isNull()) {
792      D.setInvalidType(true);
793      T = Context.IntTy;
794    }
795
796    // See if there are any attributes on this declarator chunk.
797    if (const AttributeList *AL = DeclType.getAttrs())
798      ProcessTypeAttributeList(T, AL);
799  }
800
801  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
802    const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
803    assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
804
805    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
806    // for a nonstatic member function, the function type to which a pointer
807    // to member refers, or the top-level function type of a function typedef
808    // declaration.
809    if (FnTy->getTypeQuals() != 0 &&
810        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
811        ((D.getContext() != Declarator::MemberContext &&
812          (!D.getCXXScopeSpec().isSet() ||
813           !static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep())
814              ->isRecord())) ||
815         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
816      if (D.isFunctionDeclarator())
817        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
818      else
819        Diag(D.getIdentifierLoc(),
820             diag::err_invalid_qualified_typedef_function_type_use);
821
822      // Strip the cv-quals from the type.
823      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
824                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
825    }
826  }
827
828  // If there were any type attributes applied to the decl itself (not the
829  // type, apply the type attribute to the type!)
830  if (const AttributeList *Attrs = D.getAttributes())
831    ProcessTypeAttributeList(T, Attrs);
832
833  return T;
834}
835
836/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
837/// declarator
838QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) {
839  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(static_cast<Decl *>(D));
840  QualType T = MDecl->getResultType();
841  llvm::SmallVector<QualType, 16> ArgTys;
842
843  // Add the first two invisible argument types for self and _cmd.
844  if (MDecl->isInstanceMethod()) {
845    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
846    selfTy = Context.getPointerType(selfTy);
847    ArgTys.push_back(selfTy);
848  } else
849    ArgTys.push_back(Context.getObjCIdType());
850  ArgTys.push_back(Context.getObjCSelType());
851
852  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
853       E = MDecl->param_end(); PI != E; ++PI) {
854    QualType ArgTy = (*PI)->getType();
855    assert(!ArgTy.isNull() && "Couldn't parse type?");
856    // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
857    // This matches the conversion that is done in
858    // Sema::ActOnParamDeclarator().
859    if (ArgTy->isArrayType())
860      ArgTy = Context.getArrayDecayedType(ArgTy);
861    else if (ArgTy->isFunctionType())
862      ArgTy = Context.getPointerType(ArgTy);
863    ArgTys.push_back(ArgTy);
864  }
865  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
866                              MDecl->isVariadic(), 0);
867  return T;
868}
869
870/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
871/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
872/// they point to and return true. If T1 and T2 aren't pointer types
873/// or pointer-to-member types, or if they are not similar at this
874/// level, returns false and leaves T1 and T2 unchanged. Top-level
875/// qualifiers on T1 and T2 are ignored. This function will typically
876/// be called in a loop that successively "unwraps" pointer and
877/// pointer-to-member types to compare them at each level.
878bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
879  const PointerType *T1PtrType = T1->getAsPointerType(),
880                    *T2PtrType = T2->getAsPointerType();
881  if (T1PtrType && T2PtrType) {
882    T1 = T1PtrType->getPointeeType();
883    T2 = T2PtrType->getPointeeType();
884    return true;
885  }
886
887  const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
888                          *T2MPType = T2->getAsMemberPointerType();
889  if (T1MPType && T2MPType &&
890      Context.getCanonicalType(T1MPType->getClass()) ==
891      Context.getCanonicalType(T2MPType->getClass())) {
892    T1 = T1MPType->getPointeeType();
893    T2 = T2MPType->getPointeeType();
894    return true;
895  }
896  return false;
897}
898
899Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
900  // C99 6.7.6: Type names have no identifier.  This is already validated by
901  // the parser.
902  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
903
904  QualType T = GetTypeForDeclarator(D, S);
905  if (T.isNull())
906    return true;
907
908  // Check that there are no default arguments (C++ only).
909  if (getLangOptions().CPlusPlus)
910    CheckExtraCXXDefaultArguments(D);
911
912  return T.getAsOpaquePtr();
913}
914
915
916
917//===----------------------------------------------------------------------===//
918// Type Attribute Processing
919//===----------------------------------------------------------------------===//
920
921/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
922/// specified type.  The attribute contains 1 argument, the id of the address
923/// space for the type.
924static void HandleAddressSpaceTypeAttribute(QualType &Type,
925                                            const AttributeList &Attr, Sema &S){
926  // If this type is already address space qualified, reject it.
927  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
928  // for two or more different address spaces."
929  if (Type.getAddressSpace()) {
930    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
931    return;
932  }
933
934  // Check the attribute arguments.
935  if (Attr.getNumArgs() != 1) {
936    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
937    return;
938  }
939  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
940  llvm::APSInt addrSpace(32);
941  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
942    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
943      << ASArgExpr->getSourceRange();
944    return;
945  }
946
947  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
948  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
949}
950
951/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
952/// specified type.  The attribute contains 1 argument, weak or strong.
953static void HandleObjCGCTypeAttribute(QualType &Type,
954                                      const AttributeList &Attr, Sema &S) {
955  if (Type.getObjCGCAttr() != QualType::GCNone) {
956    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
957    return;
958  }
959
960  // Check the attribute arguments.
961  if (!Attr.getParameterName()) {
962    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
963      << "objc_gc" << 1;
964    return;
965  }
966  QualType::GCAttrTypes GCAttr;
967  if (Attr.getNumArgs() != 0) {
968    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
969    return;
970  }
971  if (Attr.getParameterName()->isStr("weak"))
972    GCAttr = QualType::Weak;
973  else if (Attr.getParameterName()->isStr("strong"))
974    GCAttr = QualType::Strong;
975  else {
976    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
977      << "objc_gc" << Attr.getParameterName();
978    return;
979  }
980
981  Type = S.Context.getObjCGCQualType(Type, GCAttr);
982}
983
984void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
985  // Scan through and apply attributes to this type where it makes sense.  Some
986  // attributes (such as __address_space__, __vector_size__, etc) apply to the
987  // type, but others can be present in the type specifiers even though they
988  // apply to the decl.  Here we apply type attributes and ignore the rest.
989  for (; AL; AL = AL->getNext()) {
990    // If this is an attribute we can handle, do so now, otherwise, add it to
991    // the LeftOverAttrs list for rechaining.
992    switch (AL->getKind()) {
993    default: break;
994    case AttributeList::AT_address_space:
995      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
996      break;
997    case AttributeList::AT_objc_gc:
998      HandleObjCGCTypeAttribute(Result, *AL, *this);
999      break;
1000    }
1001  }
1002}
1003
1004/// @brief Ensure that the type T is a complete type.
1005///
1006/// This routine checks whether the type @p T is complete in any
1007/// context where a complete type is required. If @p T is a complete
1008/// type, returns false. If @p T is a class template specialization,
1009/// this routine then attempts to perform class template
1010/// instantiation. If instantiation fails, or if @p T is incomplete
1011/// and cannot be completed, issues the diagnostic @p diag (giving it
1012/// the type @p T) and returns true.
1013///
1014/// @param Loc  The location in the source that the incomplete type
1015/// diagnostic should refer to.
1016///
1017/// @param T  The type that this routine is examining for completeness.
1018///
1019/// @param diag The diagnostic value (e.g.,
1020/// @c diag::err_typecheck_decl_incomplete_type) that will be used
1021/// for the error message if @p T is incomplete.
1022///
1023/// @param Range1  An optional range in the source code that will be a
1024/// part of the "incomplete type" error message.
1025///
1026/// @param Range2  An optional range in the source code that will be a
1027/// part of the "incomplete type" error message.
1028///
1029/// @param PrintType If non-NULL, the type that should be printed
1030/// instead of @p T. This parameter should be used when the type that
1031/// we're checking for incompleteness isn't the type that should be
1032/// displayed to the user, e.g., when T is a type and PrintType is a
1033/// pointer to T.
1034///
1035/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1036/// @c false otherwise.
1037bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1038                                  SourceRange Range1, SourceRange Range2,
1039                                  QualType PrintType) {
1040  // If we have a complete type, we're done.
1041  if (!T->isIncompleteType())
1042    return false;
1043
1044  // If we have a class template specialization, try to instantiate
1045  // it.
1046  if (const RecordType *Record = T->getAsRecordType())
1047    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1048          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl()))
1049      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1050        // Update the class template specialization's location to
1051        // refer to the point of instantiation.
1052        if (Loc.isValid())
1053          ClassTemplateSpec->setLocation(Loc);
1054        return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1055                                             /*ExplicitInstantiation=*/false);
1056      }
1057
1058
1059  if (PrintType.isNull())
1060    PrintType = T;
1061
1062  // We have an incomplete type. Produce a diagnostic.
1063  Diag(Loc, diag) << PrintType << Range1 << Range2;
1064
1065  // If the type was a forward declaration of a class/struct/union
1066  // type, produce
1067  const TagType *Tag = 0;
1068  if (const RecordType *Record = T->getAsRecordType())
1069    Tag = Record;
1070  else if (const EnumType *Enum = T->getAsEnumType())
1071    Tag = Enum;
1072
1073  if (Tag && !Tag->getDecl()->isInvalidDecl())
1074    Diag(Tag->getDecl()->getLocation(),
1075         Tag->isBeingDefined() ? diag::note_type_being_defined
1076                               : diag::note_forward_declaration)
1077        << QualType(Tag, 0);
1078
1079  return true;
1080}
1081