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