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