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