SemaType.cpp revision b95faf5b7275f7d3d87f89f4e8bf840d7764af7a
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/TypeLocVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Parse/DeclSpec.h"
24#include "llvm/ADT/SmallPtrSet.h"
25using namespace clang;
26
27/// \brief Perform adjustment on the parameter type of a function.
28///
29/// This routine adjusts the given parameter type @p T to the actual
30/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
31/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
32QualType Sema::adjustParameterType(QualType T) {
33  // C99 6.7.5.3p7:
34  //   A declaration of a parameter as "array of type" shall be
35  //   adjusted to "qualified pointer to type", where the type
36  //   qualifiers (if any) are those specified within the [ and ] of
37  //   the array type derivation.
38  if (T->isArrayType())
39    return Context.getArrayDecayedType(T);
40
41  // C99 6.7.5.3p8:
42  //   A declaration of a parameter as "function returning type"
43  //   shall be adjusted to "pointer to function returning type", as
44  //   in 6.3.2.1.
45  if (T->isFunctionType())
46    return Context.getPointerType(T);
47
48  return T;
49}
50
51
52
53/// isOmittedBlockReturnType - Return true if this declarator is missing a
54/// return type because this is a omitted return type on a block literal.
55static bool isOmittedBlockReturnType(const Declarator &D, unsigned Skip) {
56  if (D.getContext() != Declarator::BlockLiteralContext ||
57      Skip != 0 || D.getDeclSpec().hasTypeSpecifier())
58    return false;
59
60  if (D.getNumTypeObjects() == 0)
61    return true;
62
63  if (D.getNumTypeObjects() == 1 &&
64      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
65    return true;
66
67  return false;
68}
69
70/// \brief Convert the specified declspec to the appropriate type
71/// object.
72/// \param D  the declarator containing the declaration specifier.
73/// \returns The type described by the declaration specifiers.  This function
74/// never returns null.
75static QualType ConvertDeclSpecToType(Declarator &TheDeclarator, unsigned Skip,
76                                      Sema &TheSema) {
77  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
78  // checking.
79  const DeclSpec &DS = TheDeclarator.getDeclSpec();
80  SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
81  if (DeclLoc.isInvalid())
82    DeclLoc = DS.getSourceRange().getBegin();
83
84  ASTContext &Context = TheSema.Context;
85
86  QualType Result;
87  switch (DS.getTypeSpecType()) {
88  case DeclSpec::TST_void:
89    Result = Context.VoidTy;
90    break;
91  case DeclSpec::TST_char:
92    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
93      Result = Context.CharTy;
94    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
95      Result = Context.SignedCharTy;
96    else {
97      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
98             "Unknown TSS value");
99      Result = Context.UnsignedCharTy;
100    }
101    break;
102  case DeclSpec::TST_wchar:
103    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
104      Result = Context.WCharTy;
105    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
106      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
107        << DS.getSpecifierName(DS.getTypeSpecType());
108      Result = Context.getSignedWCharType();
109    } else {
110      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
111        "Unknown TSS value");
112      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
113        << DS.getSpecifierName(DS.getTypeSpecType());
114      Result = Context.getUnsignedWCharType();
115    }
116    break;
117  case DeclSpec::TST_char16:
118      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
119        "Unknown TSS value");
120      Result = Context.Char16Ty;
121    break;
122  case DeclSpec::TST_char32:
123      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
124        "Unknown TSS value");
125      Result = Context.Char32Ty;
126    break;
127  case DeclSpec::TST_unspecified:
128    // "<proto1,proto2>" is an objc qualified ID with a missing id.
129    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
130      Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
131                                                (ObjCProtocolDecl**)PQ,
132                                                DS.getNumProtocolQualifiers());
133      break;
134    }
135
136    // If this is a missing declspec in a block literal return context, then it
137    // is inferred from the return statements inside the block.
138    if (isOmittedBlockReturnType(TheDeclarator, Skip)) {
139      Result = Context.DependentTy;
140      break;
141    }
142
143    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
144    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
145    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
146    // Note that the one exception to this is function definitions, which are
147    // allowed to be completely missing a declspec.  This is handled in the
148    // parser already though by it pretending to have seen an 'int' in this
149    // case.
150    if (TheSema.getLangOptions().ImplicitInt) {
151      // In C89 mode, we only warn if there is a completely missing declspec
152      // when one is not allowed.
153      if (DS.isEmpty()) {
154        TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
155          << DS.getSourceRange()
156        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
157                                                 "int");
158      }
159    } else if (!DS.hasTypeSpecifier()) {
160      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
161      // "At least one type specifier shall be given in the declaration
162      // specifiers in each declaration, and in the specifier-qualifier list in
163      // each struct declaration and type name."
164      // FIXME: Does Microsoft really have the implicit int extension in C++?
165      if (TheSema.getLangOptions().CPlusPlus &&
166          !TheSema.getLangOptions().Microsoft) {
167        TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
168          << DS.getSourceRange();
169
170        // When this occurs in C++ code, often something is very broken with the
171        // value being declared, poison it as invalid so we don't get chains of
172        // errors.
173        TheDeclarator.setInvalidType(true);
174      } else {
175        TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
176          << DS.getSourceRange();
177      }
178    }
179
180    // FALL THROUGH.
181  case DeclSpec::TST_int: {
182    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
183      switch (DS.getTypeSpecWidth()) {
184      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
185      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
186      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
187      case DeclSpec::TSW_longlong:
188        Result = Context.LongLongTy;
189
190        // long long is a C99 feature.
191        if (!TheSema.getLangOptions().C99 &&
192            !TheSema.getLangOptions().CPlusPlus0x)
193          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
194        break;
195      }
196    } else {
197      switch (DS.getTypeSpecWidth()) {
198      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
199      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
200      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
201      case DeclSpec::TSW_longlong:
202        Result = Context.UnsignedLongLongTy;
203
204        // long long is a C99 feature.
205        if (!TheSema.getLangOptions().C99 &&
206            !TheSema.getLangOptions().CPlusPlus0x)
207          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
208        break;
209      }
210    }
211    break;
212  }
213  case DeclSpec::TST_float: Result = Context.FloatTy; break;
214  case DeclSpec::TST_double:
215    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
216      Result = Context.LongDoubleTy;
217    else
218      Result = Context.DoubleTy;
219    break;
220  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
221  case DeclSpec::TST_decimal32:    // _Decimal32
222  case DeclSpec::TST_decimal64:    // _Decimal64
223  case DeclSpec::TST_decimal128:   // _Decimal128
224    TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
225    Result = Context.IntTy;
226    TheDeclarator.setInvalidType(true);
227    break;
228  case DeclSpec::TST_class:
229  case DeclSpec::TST_enum:
230  case DeclSpec::TST_union:
231  case DeclSpec::TST_struct: {
232    Decl *D = static_cast<Decl *>(DS.getTypeRep());
233    if (!D) {
234      // This can happen in C++ with ambiguous lookups.
235      Result = Context.IntTy;
236      TheDeclarator.setInvalidType(true);
237      break;
238    }
239
240    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
241           DS.getTypeSpecSign() == 0 &&
242           "Can't handle qualifiers on typedef names yet!");
243    // TypeQuals handled by caller.
244    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
245
246    // In C++, make an ElaboratedType.
247    if (TheSema.getLangOptions().CPlusPlus) {
248      TagDecl::TagKind Tag
249        = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType());
250      Result = Context.getElaboratedType(Result, Tag);
251    }
252
253    if (D->isInvalidDecl())
254      TheDeclarator.setInvalidType(true);
255    break;
256  }
257  case DeclSpec::TST_typename: {
258    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
259           DS.getTypeSpecSign() == 0 &&
260           "Can't handle qualifiers on typedef names yet!");
261    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
262
263    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
264      if (const ObjCInterfaceType *
265            Interface = Result->getAs<ObjCInterfaceType>()) {
266        // It would be nice if protocol qualifiers were only stored with the
267        // ObjCObjectPointerType. Unfortunately, this isn't possible due
268        // to the following typedef idiom (which is uncommon, but allowed):
269        //
270        // typedef Foo<P> T;
271        // static void func() {
272        //   Foo<P> *yy;
273        //   T *zz;
274        // }
275        Result = Context.getObjCInterfaceType(Interface->getDecl(),
276                                              (ObjCProtocolDecl**)PQ,
277                                              DS.getNumProtocolQualifiers());
278      } else if (Result->isObjCIdType())
279        // id<protocol-list>
280        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
281                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
282      else if (Result->isObjCClassType()) {
283        // Class<protocol-list>
284        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
285                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
286      } else {
287        TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
288          << DS.getSourceRange();
289        TheDeclarator.setInvalidType(true);
290      }
291    }
292
293    // If this is a reference to an invalid typedef, propagate the invalidity.
294    if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
295      if (TDT->getDecl()->isInvalidDecl())
296        TheDeclarator.setInvalidType(true);
297
298    // TypeQuals handled by caller.
299    break;
300  }
301  case DeclSpec::TST_typeofType:
302    // FIXME: Preserve type source info.
303    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
304    assert(!Result.isNull() && "Didn't get a type for typeof?");
305    // TypeQuals handled by caller.
306    Result = Context.getTypeOfType(Result);
307    break;
308  case DeclSpec::TST_typeofExpr: {
309    Expr *E = static_cast<Expr *>(DS.getTypeRep());
310    assert(E && "Didn't get an expression for typeof?");
311    // TypeQuals handled by caller.
312    Result = Context.getTypeOfExprType(E);
313    break;
314  }
315  case DeclSpec::TST_decltype: {
316    Expr *E = static_cast<Expr *>(DS.getTypeRep());
317    assert(E && "Didn't get an expression for decltype?");
318    // TypeQuals handled by caller.
319    Result = TheSema.BuildDecltypeType(E);
320    if (Result.isNull()) {
321      Result = Context.IntTy;
322      TheDeclarator.setInvalidType(true);
323    }
324    break;
325  }
326  case DeclSpec::TST_auto: {
327    // TypeQuals handled by caller.
328    Result = Context.UndeducedAutoTy;
329    break;
330  }
331
332  case DeclSpec::TST_error:
333    Result = Context.IntTy;
334    TheDeclarator.setInvalidType(true);
335    break;
336  }
337
338  // Handle complex types.
339  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
340    if (TheSema.getLangOptions().Freestanding)
341      TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
342    Result = Context.getComplexType(Result);
343  }
344
345  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
346         "FIXME: imaginary types not supported yet!");
347
348  // See if there are any attributes on the declspec that apply to the type (as
349  // opposed to the decl).
350  if (const AttributeList *AL = DS.getAttributes())
351    TheSema.ProcessTypeAttributeList(Result, AL);
352
353  // Apply const/volatile/restrict qualifiers to T.
354  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
355
356    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
357    // or incomplete types shall not be restrict-qualified."  C++ also allows
358    // restrict-qualified references.
359    if (TypeQuals & DeclSpec::TQ_restrict) {
360      if (Result->isPointerType() || Result->isReferenceType()) {
361        QualType EltTy = Result->isPointerType() ?
362          Result->getAs<PointerType>()->getPointeeType() :
363          Result->getAs<ReferenceType>()->getPointeeType();
364
365        // If we have a pointer or reference, the pointee must have an object
366        // incomplete type.
367        if (!EltTy->isIncompleteOrObjectType()) {
368          TheSema.Diag(DS.getRestrictSpecLoc(),
369               diag::err_typecheck_invalid_restrict_invalid_pointee)
370            << EltTy << DS.getSourceRange();
371          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
372        }
373      } else {
374        TheSema.Diag(DS.getRestrictSpecLoc(),
375             diag::err_typecheck_invalid_restrict_not_pointer)
376          << Result << DS.getSourceRange();
377        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
378      }
379    }
380
381    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
382    // of a function type includes any type qualifiers, the behavior is
383    // undefined."
384    if (Result->isFunctionType() && TypeQuals) {
385      // Get some location to point at, either the C or V location.
386      SourceLocation Loc;
387      if (TypeQuals & DeclSpec::TQ_const)
388        Loc = DS.getConstSpecLoc();
389      else if (TypeQuals & DeclSpec::TQ_volatile)
390        Loc = DS.getVolatileSpecLoc();
391      else {
392        assert((TypeQuals & DeclSpec::TQ_restrict) &&
393               "Has CVR quals but not C, V, or R?");
394        Loc = DS.getRestrictSpecLoc();
395      }
396      TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
397        << Result << DS.getSourceRange();
398    }
399
400    // C++ [dcl.ref]p1:
401    //   Cv-qualified references are ill-formed except when the
402    //   cv-qualifiers are introduced through the use of a typedef
403    //   (7.1.3) or of a template type argument (14.3), in which
404    //   case the cv-qualifiers are ignored.
405    // FIXME: Shouldn't we be checking SCS_typedef here?
406    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
407        TypeQuals && Result->isReferenceType()) {
408      TypeQuals &= ~DeclSpec::TQ_const;
409      TypeQuals &= ~DeclSpec::TQ_volatile;
410    }
411
412    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
413    Result = Context.getQualifiedType(Result, Quals);
414  }
415
416  return Result;
417}
418
419static std::string getPrintableNameForEntity(DeclarationName Entity) {
420  if (Entity)
421    return Entity.getAsString();
422
423  return "type name";
424}
425
426/// \brief Build a pointer type.
427///
428/// \param T The type to which we'll be building a pointer.
429///
430/// \param Quals The cvr-qualifiers to be applied to the pointer type.
431///
432/// \param Loc The location of the entity whose type involves this
433/// pointer type or, if there is no such entity, the location of the
434/// type that will have pointer type.
435///
436/// \param Entity The name of the entity that involves the pointer
437/// type, if known.
438///
439/// \returns A suitable pointer type, if there are no
440/// errors. Otherwise, returns a NULL type.
441QualType Sema::BuildPointerType(QualType T, unsigned Quals,
442                                SourceLocation Loc, DeclarationName Entity) {
443  if (T->isReferenceType()) {
444    // C++ 8.3.2p4: There shall be no ... pointers to references ...
445    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
446      << getPrintableNameForEntity(Entity);
447    return QualType();
448  }
449
450  Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
451
452  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
453  // object or incomplete types shall not be restrict-qualified."
454  if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
455    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
456      << T;
457    Qs.removeRestrict();
458  }
459
460  // Build the pointer type.
461  return Context.getQualifiedType(Context.getPointerType(T), Qs);
462}
463
464/// \brief Build a reference type.
465///
466/// \param T The type to which we'll be building a reference.
467///
468/// \param CVR The cvr-qualifiers to be applied to the reference type.
469///
470/// \param Loc The location of the entity whose type involves this
471/// reference type or, if there is no such entity, the location of the
472/// type that will have reference type.
473///
474/// \param Entity The name of the entity that involves the reference
475/// type, if known.
476///
477/// \returns A suitable reference type, if there are no
478/// errors. Otherwise, returns a NULL type.
479QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
480                                  unsigned CVR, SourceLocation Loc,
481                                  DeclarationName Entity) {
482  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
483
484  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
485
486  // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
487  //   reference to a type T, and attempt to create the type "lvalue
488  //   reference to cv TD" creates the type "lvalue reference to T".
489  // We use the qualifiers (restrict or none) of the original reference,
490  // not the new ones. This is consistent with GCC.
491
492  // C++ [dcl.ref]p4: There shall be no references to references.
493  //
494  // According to C++ DR 106, references to references are only
495  // diagnosed when they are written directly (e.g., "int & &"),
496  // but not when they happen via a typedef:
497  //
498  //   typedef int& intref;
499  //   typedef intref& intref2;
500  //
501  // Parser::ParseDeclaratorInternal diagnoses the case where
502  // references are written directly; here, we handle the
503  // collapsing of references-to-references as described in C++
504  // DR 106 and amended by C++ DR 540.
505
506  // C++ [dcl.ref]p1:
507  //   A declarator that specifies the type "reference to cv void"
508  //   is ill-formed.
509  if (T->isVoidType()) {
510    Diag(Loc, diag::err_reference_to_void);
511    return QualType();
512  }
513
514  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
515  // object or incomplete types shall not be restrict-qualified."
516  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
517    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
518      << T;
519    Quals.removeRestrict();
520  }
521
522  // C++ [dcl.ref]p1:
523  //   [...] Cv-qualified references are ill-formed except when the
524  //   cv-qualifiers are introduced through the use of a typedef
525  //   (7.1.3) or of a template type argument (14.3), in which case
526  //   the cv-qualifiers are ignored.
527  //
528  // We diagnose extraneous cv-qualifiers for the non-typedef,
529  // non-template type argument case within the parser. Here, we just
530  // ignore any extraneous cv-qualifiers.
531  Quals.removeConst();
532  Quals.removeVolatile();
533
534  // Handle restrict on references.
535  if (LValueRef)
536    return Context.getQualifiedType(
537               Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
538  return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
539}
540
541/// \brief Build an array type.
542///
543/// \param T The type of each element in the array.
544///
545/// \param ASM C99 array size modifier (e.g., '*', 'static').
546///
547/// \param ArraySize Expression describing the size of the array.
548///
549/// \param Quals The cvr-qualifiers to be applied to the array's
550/// element type.
551///
552/// \param Loc The location of the entity whose type involves this
553/// array type or, if there is no such entity, the location of the
554/// type that will have array type.
555///
556/// \param Entity The name of the entity that involves the array
557/// type, if known.
558///
559/// \returns A suitable array type, if there are no errors. Otherwise,
560/// returns a NULL type.
561QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
562                              Expr *ArraySize, unsigned Quals,
563                              SourceRange Brackets, DeclarationName Entity) {
564
565  SourceLocation Loc = Brackets.getBegin();
566  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
567  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
568  if (RequireCompleteType(Loc, T,
569                             diag::err_illegal_decl_array_incomplete_type))
570    return QualType();
571
572  if (T->isFunctionType()) {
573    Diag(Loc, diag::err_illegal_decl_array_of_functions)
574      << getPrintableNameForEntity(Entity);
575    return QualType();
576  }
577
578  // C++ 8.3.2p4: There shall be no ... arrays of references ...
579  if (T->isReferenceType()) {
580    Diag(Loc, diag::err_illegal_decl_array_of_references)
581      << getPrintableNameForEntity(Entity);
582    return QualType();
583  }
584
585  if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
586    Diag(Loc,  diag::err_illegal_decl_array_of_auto)
587      << getPrintableNameForEntity(Entity);
588    return QualType();
589  }
590
591  if (const RecordType *EltTy = T->getAs<RecordType>()) {
592    // If the element type is a struct or union that contains a variadic
593    // array, accept it as a GNU extension: C99 6.7.2.1p2.
594    if (EltTy->getDecl()->hasFlexibleArrayMember())
595      Diag(Loc, diag::ext_flexible_array_in_array) << T;
596  } else if (T->isObjCInterfaceType()) {
597    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
598    return QualType();
599  }
600
601  // C99 6.7.5.2p1: The size expression shall have integer type.
602  if (ArraySize && !ArraySize->isTypeDependent() &&
603      !ArraySize->getType()->isIntegerType()) {
604    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
605      << ArraySize->getType() << ArraySize->getSourceRange();
606    ArraySize->Destroy(Context);
607    return QualType();
608  }
609  llvm::APSInt ConstVal(32);
610  if (!ArraySize) {
611    if (ASM == ArrayType::Star)
612      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
613    else
614      T = Context.getIncompleteArrayType(T, ASM, Quals);
615  } else if (ArraySize->isValueDependent()) {
616    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
617  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
618             (!T->isDependentType() && !T->isConstantSizeType())) {
619    // Per C99, a variable array is an array with either a non-constant
620    // size or an element type that has a non-constant-size
621    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
622  } else {
623    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
624    // have a value greater than zero.
625    if (ConstVal.isSigned()) {
626      if (ConstVal.isNegative()) {
627        Diag(ArraySize->getLocStart(),
628             diag::err_typecheck_negative_array_size)
629          << ArraySize->getSourceRange();
630        return QualType();
631      } else if (ConstVal == 0) {
632        // GCC accepts zero sized static arrays.
633        Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
634          << ArraySize->getSourceRange();
635      }
636    }
637    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
638  }
639  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
640  if (!getLangOptions().C99) {
641    if (ArraySize && !ArraySize->isTypeDependent() &&
642        !ArraySize->isValueDependent() &&
643        !ArraySize->isIntegerConstantExpr(Context))
644      Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla);
645    else if (ASM != ArrayType::Normal || Quals != 0)
646      Diag(Loc,
647           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
648                                     : diag::ext_c99_array_usage);
649  }
650
651  return T;
652}
653
654/// \brief Build an ext-vector type.
655///
656/// Run the required checks for the extended vector type.
657QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
658                                  SourceLocation AttrLoc) {
659
660  Expr *Arg = (Expr *)ArraySize.get();
661
662  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
663  // in conjunction with complex types (pointers, arrays, functions, etc.).
664  if (!T->isDependentType() &&
665      !T->isIntegerType() && !T->isRealFloatingType()) {
666    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
667    return QualType();
668  }
669
670  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
671    llvm::APSInt vecSize(32);
672    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
673      Diag(AttrLoc, diag::err_attribute_argument_not_int)
674      << "ext_vector_type" << Arg->getSourceRange();
675      return QualType();
676    }
677
678    // unlike gcc's vector_size attribute, the size is specified as the
679    // number of elements, not the number of bytes.
680    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
681
682    if (vectorSize == 0) {
683      Diag(AttrLoc, diag::err_attribute_zero_size)
684      << Arg->getSourceRange();
685      return QualType();
686    }
687
688    if (!T->isDependentType())
689      return Context.getExtVectorType(T, vectorSize);
690  }
691
692  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
693                                                AttrLoc);
694}
695
696/// \brief Build a function type.
697///
698/// This routine checks the function type according to C++ rules and
699/// under the assumption that the result type and parameter types have
700/// just been instantiated from a template. It therefore duplicates
701/// some of the behavior of GetTypeForDeclarator, but in a much
702/// simpler form that is only suitable for this narrow use case.
703///
704/// \param T The return type of the function.
705///
706/// \param ParamTypes The parameter types of the function. This array
707/// will be modified to account for adjustments to the types of the
708/// function parameters.
709///
710/// \param NumParamTypes The number of parameter types in ParamTypes.
711///
712/// \param Variadic Whether this is a variadic function type.
713///
714/// \param Quals The cvr-qualifiers to be applied to the function type.
715///
716/// \param Loc The location of the entity whose type involves this
717/// function type or, if there is no such entity, the location of the
718/// type that will have function type.
719///
720/// \param Entity The name of the entity that involves the function
721/// type, if known.
722///
723/// \returns A suitable function type, if there are no
724/// errors. Otherwise, returns a NULL type.
725QualType Sema::BuildFunctionType(QualType T,
726                                 QualType *ParamTypes,
727                                 unsigned NumParamTypes,
728                                 bool Variadic, unsigned Quals,
729                                 SourceLocation Loc, DeclarationName Entity) {
730  if (T->isArrayType() || T->isFunctionType()) {
731    Diag(Loc, diag::err_func_returning_array_function) << T;
732    return QualType();
733  }
734
735  bool Invalid = false;
736  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
737    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
738    if (ParamType->isVoidType()) {
739      Diag(Loc, diag::err_param_with_void_type);
740      Invalid = true;
741    }
742
743    ParamTypes[Idx] = ParamType;
744  }
745
746  if (Invalid)
747    return QualType();
748
749  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
750                                 Quals);
751}
752
753/// \brief Build a member pointer type \c T Class::*.
754///
755/// \param T the type to which the member pointer refers.
756/// \param Class the class type into which the member pointer points.
757/// \param CVR Qualifiers applied to the member pointer type
758/// \param Loc the location where this type begins
759/// \param Entity the name of the entity that will have this member pointer type
760///
761/// \returns a member pointer type, if successful, or a NULL type if there was
762/// an error.
763QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
764                                      unsigned CVR, SourceLocation Loc,
765                                      DeclarationName Entity) {
766  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
767
768  // Verify that we're not building a pointer to pointer to function with
769  // exception specification.
770  if (CheckDistantExceptionSpec(T)) {
771    Diag(Loc, diag::err_distant_exception_spec);
772
773    // FIXME: If we're doing this as part of template instantiation,
774    // we should return immediately.
775
776    // Build the type anyway, but use the canonical type so that the
777    // exception specifiers are stripped off.
778    T = Context.getCanonicalType(T);
779  }
780
781  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
782  //   with reference type, or "cv void."
783  if (T->isReferenceType()) {
784    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
785      << (Entity? Entity.getAsString() : "type name");
786    return QualType();
787  }
788
789  if (T->isVoidType()) {
790    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
791      << (Entity? Entity.getAsString() : "type name");
792    return QualType();
793  }
794
795  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
796  // object or incomplete types shall not be restrict-qualified."
797  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
798    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
799      << T;
800
801    // FIXME: If we're doing this as part of template instantiation,
802    // we should return immediately.
803    Quals.removeRestrict();
804  }
805
806  if (!Class->isDependentType() && !Class->isRecordType()) {
807    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
808    return QualType();
809  }
810
811  return Context.getQualifiedType(
812           Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
813}
814
815/// \brief Build a block pointer type.
816///
817/// \param T The type to which we'll be building a block pointer.
818///
819/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
820///
821/// \param Loc The location of the entity whose type involves this
822/// block pointer type or, if there is no such entity, the location of the
823/// type that will have block pointer type.
824///
825/// \param Entity The name of the entity that involves the block pointer
826/// type, if known.
827///
828/// \returns A suitable block pointer type, if there are no
829/// errors. Otherwise, returns a NULL type.
830QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
831                                     SourceLocation Loc,
832                                     DeclarationName Entity) {
833  if (!T->isFunctionType()) {
834    Diag(Loc, diag::err_nonfunction_block_type);
835    return QualType();
836  }
837
838  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
839  return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
840}
841
842QualType Sema::GetTypeFromParser(TypeTy *Ty, DeclaratorInfo **DInfo) {
843  QualType QT = QualType::getFromOpaquePtr(Ty);
844  DeclaratorInfo *DI = 0;
845  if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
846    QT = LIT->getType();
847    DI = LIT->getDeclaratorInfo();
848  }
849
850  if (DInfo) *DInfo = DI;
851  return QT;
852}
853
854/// GetTypeForDeclarator - Convert the type for the specified
855/// declarator to Type instances. Skip the outermost Skip type
856/// objects.
857///
858/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
859/// owns the declaration of a type (e.g., the definition of a struct
860/// type), then *OwnedDecl will receive the owned declaration.
861QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
862                                    DeclaratorInfo **DInfo, unsigned Skip,
863                                    TagDecl **OwnedDecl) {
864  // Determine the type of the declarator. Not all forms of declarator
865  // have a type.
866  QualType T;
867
868  switch (D.getKind()) {
869  case Declarator::DK_Abstract:
870  case Declarator::DK_Normal:
871  case Declarator::DK_Operator:
872  case Declarator::DK_TemplateId:
873    T = ConvertDeclSpecToType(D, Skip, *this);
874
875    if (!D.isInvalidType() && OwnedDecl && D.getDeclSpec().isTypeSpecOwned())
876      *OwnedDecl = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
877    break;
878
879  case Declarator::DK_Constructor:
880  case Declarator::DK_Destructor:
881  case Declarator::DK_Conversion:
882    // Constructors and destructors don't have return types. Use
883    // "void" instead. Conversion operators will check their return
884    // types separately.
885    T = Context.VoidTy;
886    break;
887  }
888
889  if (T == Context.UndeducedAutoTy) {
890    int Error = -1;
891
892    switch (D.getContext()) {
893    case Declarator::KNRTypeListContext:
894      assert(0 && "K&R type lists aren't allowed in C++");
895      break;
896    case Declarator::PrototypeContext:
897      Error = 0; // Function prototype
898      break;
899    case Declarator::MemberContext:
900      switch (cast<TagDecl>(CurContext)->getTagKind()) {
901      case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
902      case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
903      case TagDecl::TK_union:  Error = 2; /* Union member */ break;
904      case TagDecl::TK_class:  Error = 3; /* Class member */ break;
905      }
906      break;
907    case Declarator::CXXCatchContext:
908      Error = 4; // Exception declaration
909      break;
910    case Declarator::TemplateParamContext:
911      Error = 5; // Template parameter
912      break;
913    case Declarator::BlockLiteralContext:
914      Error = 6;  // Block literal
915      break;
916    case Declarator::FileContext:
917    case Declarator::BlockContext:
918    case Declarator::ForContext:
919    case Declarator::ConditionContext:
920    case Declarator::TypeNameContext:
921      break;
922    }
923
924    if (Error != -1) {
925      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
926        << Error;
927      T = Context.IntTy;
928      D.setInvalidType(true);
929    }
930  }
931
932  // The name we're declaring, if any.
933  DeclarationName Name;
934  if (D.getIdentifier())
935    Name = D.getIdentifier();
936
937  // Walk the DeclTypeInfo, building the recursive type as we go.
938  // DeclTypeInfos are ordered from the identifier out, which is
939  // opposite of what we want :).
940  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
941    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
942    switch (DeclType.Kind) {
943    default: assert(0 && "Unknown decltype!");
944    case DeclaratorChunk::BlockPointer:
945      // If blocks are disabled, emit an error.
946      if (!LangOpts.Blocks)
947        Diag(DeclType.Loc, diag::err_blocks_disable);
948
949      T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
950                                Name);
951      break;
952    case DeclaratorChunk::Pointer:
953      // Verify that we're not building a pointer to pointer to function with
954      // exception specification.
955      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
956        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
957        D.setInvalidType(true);
958        // Build the type anyway.
959      }
960      if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
961        const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>();
962        T = Context.getObjCObjectPointerType(T,
963                                         (ObjCProtocolDecl **)OIT->qual_begin(),
964                                         OIT->getNumProtocols());
965        break;
966      }
967      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
968      break;
969    case DeclaratorChunk::Reference: {
970      Qualifiers Quals;
971      if (DeclType.Ref.HasRestrict) Quals.addRestrict();
972
973      // Verify that we're not building a reference to pointer to function with
974      // exception specification.
975      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
976        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
977        D.setInvalidType(true);
978        // Build the type anyway.
979      }
980      T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
981                             DeclType.Loc, Name);
982      break;
983    }
984    case DeclaratorChunk::Array: {
985      // Verify that we're not building an array of pointers to function with
986      // exception specification.
987      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
988        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
989        D.setInvalidType(true);
990        // Build the type anyway.
991      }
992      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
993      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
994      ArrayType::ArraySizeModifier ASM;
995      if (ATI.isStar)
996        ASM = ArrayType::Star;
997      else if (ATI.hasStatic)
998        ASM = ArrayType::Static;
999      else
1000        ASM = ArrayType::Normal;
1001      if (ASM == ArrayType::Star &&
1002          D.getContext() != Declarator::PrototypeContext) {
1003        // FIXME: This check isn't quite right: it allows star in prototypes
1004        // for function definitions, and disallows some edge cases detailed
1005        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1006        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1007        ASM = ArrayType::Normal;
1008        D.setInvalidType(true);
1009      }
1010      T = BuildArrayType(T, ASM, ArraySize,
1011                         Qualifiers::fromCVRMask(ATI.TypeQuals),
1012                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1013      break;
1014    }
1015    case DeclaratorChunk::Function: {
1016      // If the function declarator has a prototype (i.e. it is not () and
1017      // does not have a K&R-style identifier list), then the arguments are part
1018      // of the type, otherwise the argument list is ().
1019      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1020
1021      // C99 6.7.5.3p1: The return type may not be a function or array type.
1022      if (T->isArrayType() || T->isFunctionType()) {
1023        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
1024        T = Context.IntTy;
1025        D.setInvalidType(true);
1026      }
1027
1028      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1029        // C++ [dcl.fct]p6:
1030        //   Types shall not be defined in return or parameter types.
1031        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1032        if (Tag->isDefinition())
1033          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1034            << Context.getTypeDeclType(Tag);
1035      }
1036
1037      // Exception specs are not allowed in typedefs. Complain, but add it
1038      // anyway.
1039      if (FTI.hasExceptionSpec &&
1040          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1041        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1042
1043      if (FTI.NumArgs == 0) {
1044        if (getLangOptions().CPlusPlus) {
1045          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1046          // function takes no arguments.
1047          llvm::SmallVector<QualType, 4> Exceptions;
1048          Exceptions.reserve(FTI.NumExceptions);
1049          for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1050            // FIXME: Preserve type source info.
1051            QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1052            // Check that the type is valid for an exception spec, and drop it
1053            // if not.
1054            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1055              Exceptions.push_back(ET);
1056          }
1057          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1058                                      FTI.hasExceptionSpec,
1059                                      FTI.hasAnyExceptionSpec,
1060                                      Exceptions.size(), Exceptions.data());
1061        } else if (FTI.isVariadic) {
1062          // We allow a zero-parameter variadic function in C if the
1063          // function is marked with the "overloadable"
1064          // attribute. Scan for this attribute now.
1065          bool Overloadable = false;
1066          for (const AttributeList *Attrs = D.getAttributes();
1067               Attrs; Attrs = Attrs->getNext()) {
1068            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1069              Overloadable = true;
1070              break;
1071            }
1072          }
1073
1074          if (!Overloadable)
1075            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1076          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
1077        } else {
1078          // Simple void foo(), where the incoming T is the result type.
1079          T = Context.getFunctionNoProtoType(T);
1080        }
1081      } else if (FTI.ArgInfo[0].Param == 0) {
1082        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1083        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1084        D.setInvalidType(true);
1085      } else {
1086        // Otherwise, we have a function with an argument list that is
1087        // potentially variadic.
1088        llvm::SmallVector<QualType, 16> ArgTys;
1089
1090        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1091          ParmVarDecl *Param =
1092            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1093          QualType ArgTy = Param->getType();
1094          assert(!ArgTy.isNull() && "Couldn't parse type?");
1095
1096          // Adjust the parameter type.
1097          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1098
1099          // Look for 'void'.  void is allowed only as a single argument to a
1100          // function with no other parameters (C99 6.7.5.3p10).  We record
1101          // int(void) as a FunctionProtoType with an empty argument list.
1102          if (ArgTy->isVoidType()) {
1103            // If this is something like 'float(int, void)', reject it.  'void'
1104            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1105            // have arguments of incomplete type.
1106            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1107              Diag(DeclType.Loc, diag::err_void_only_param);
1108              ArgTy = Context.IntTy;
1109              Param->setType(ArgTy);
1110            } else if (FTI.ArgInfo[i].Ident) {
1111              // Reject, but continue to parse 'int(void abc)'.
1112              Diag(FTI.ArgInfo[i].IdentLoc,
1113                   diag::err_param_with_void_type);
1114              ArgTy = Context.IntTy;
1115              Param->setType(ArgTy);
1116            } else {
1117              // Reject, but continue to parse 'float(const void)'.
1118              if (ArgTy.hasQualifiers())
1119                Diag(DeclType.Loc, diag::err_void_param_qualified);
1120
1121              // Do not add 'void' to the ArgTys list.
1122              break;
1123            }
1124          } else if (!FTI.hasPrototype) {
1125            if (ArgTy->isPromotableIntegerType()) {
1126              ArgTy = Context.getPromotedIntegerType(ArgTy);
1127            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1128              if (BTy->getKind() == BuiltinType::Float)
1129                ArgTy = Context.DoubleTy;
1130            }
1131          }
1132
1133          ArgTys.push_back(ArgTy);
1134        }
1135
1136        llvm::SmallVector<QualType, 4> Exceptions;
1137        Exceptions.reserve(FTI.NumExceptions);
1138        for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1139          // FIXME: Preserve type source info.
1140          QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1141          // Check that the type is valid for an exception spec, and drop it if
1142          // not.
1143          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1144            Exceptions.push_back(ET);
1145        }
1146
1147        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1148                                    FTI.isVariadic, FTI.TypeQuals,
1149                                    FTI.hasExceptionSpec,
1150                                    FTI.hasAnyExceptionSpec,
1151                                    Exceptions.size(), Exceptions.data());
1152      }
1153      break;
1154    }
1155    case DeclaratorChunk::MemberPointer:
1156      // Verify that we're not building a pointer to pointer to function with
1157      // exception specification.
1158      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1159        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1160        D.setInvalidType(true);
1161        // Build the type anyway.
1162      }
1163      // The scope spec must refer to a class, or be dependent.
1164      QualType ClsType;
1165      if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
1166        NestedNameSpecifier *NNS
1167          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1168        assert(NNS->getAsType() && "Nested-name-specifier must name a type");
1169        ClsType = QualType(NNS->getAsType(), 0);
1170      } else if (CXXRecordDecl *RD
1171                   = dyn_cast_or_null<CXXRecordDecl>(
1172                                    computeDeclContext(DeclType.Mem.Scope()))) {
1173        ClsType = Context.getTagDeclType(RD);
1174      } else {
1175        Diag(DeclType.Mem.Scope().getBeginLoc(),
1176             diag::err_illegal_decl_mempointer_in_nonclass)
1177          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1178          << DeclType.Mem.Scope().getRange();
1179        D.setInvalidType(true);
1180      }
1181
1182      if (!ClsType.isNull())
1183        T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1184                                   DeclType.Loc, D.getIdentifier());
1185      if (T.isNull()) {
1186        T = Context.IntTy;
1187        D.setInvalidType(true);
1188      }
1189      break;
1190    }
1191
1192    if (T.isNull()) {
1193      D.setInvalidType(true);
1194      T = Context.IntTy;
1195    }
1196
1197    // See if there are any attributes on this declarator chunk.
1198    if (const AttributeList *AL = DeclType.getAttrs())
1199      ProcessTypeAttributeList(T, AL);
1200  }
1201
1202  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1203    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1204    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1205
1206    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1207    // for a nonstatic member function, the function type to which a pointer
1208    // to member refers, or the top-level function type of a function typedef
1209    // declaration.
1210    if (FnTy->getTypeQuals() != 0 &&
1211        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1212        ((D.getContext() != Declarator::MemberContext &&
1213          (!D.getCXXScopeSpec().isSet() ||
1214           !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1215              ->isRecord())) ||
1216         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1217      if (D.isFunctionDeclarator())
1218        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1219      else
1220        Diag(D.getIdentifierLoc(),
1221             diag::err_invalid_qualified_typedef_function_type_use);
1222
1223      // Strip the cv-quals from the type.
1224      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1225                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1226    }
1227  }
1228
1229  // If there were any type attributes applied to the decl itself (not the
1230  // type, apply the type attribute to the type!)
1231  if (const AttributeList *Attrs = D.getAttributes())
1232    ProcessTypeAttributeList(T, Attrs);
1233
1234  if (DInfo) {
1235    if (D.isInvalidType())
1236      *DInfo = 0;
1237    else
1238      *DInfo = GetDeclaratorInfoForDeclarator(D, T, Skip);
1239  }
1240
1241  return T;
1242}
1243
1244namespace {
1245  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1246    const DeclSpec &DS;
1247
1248  public:
1249    TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1250
1251    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1252      Visit(TL.getUnqualifiedLoc());
1253    }
1254    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1255      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1256    }
1257    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1258      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1259
1260      if (DS.getProtocolQualifiers()) {
1261        assert(TL.getNumProtocols() > 0);
1262        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1263        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1264        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1265        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1266          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1267      } else {
1268        assert(TL.getNumProtocols() == 0);
1269        TL.setLAngleLoc(SourceLocation());
1270        TL.setRAngleLoc(SourceLocation());
1271      }
1272    }
1273    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1274      assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1275
1276      TL.setStarLoc(SourceLocation());
1277
1278      if (DS.getProtocolQualifiers()) {
1279        assert(TL.getNumProtocols() > 0);
1280        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1281        TL.setHasProtocolsAsWritten(true);
1282        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1283        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1284        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1285          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1286
1287      } else {
1288        assert(TL.getNumProtocols() == 0);
1289        TL.setHasProtocolsAsWritten(false);
1290        TL.setLAngleLoc(SourceLocation());
1291        TL.setRAngleLoc(SourceLocation());
1292      }
1293
1294      // This might not have been written with an inner type.
1295      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1296        TL.setHasBaseTypeAsWritten(false);
1297        TL.getBaseTypeLoc().initialize(SourceLocation());
1298      } else {
1299        TL.setHasBaseTypeAsWritten(true);
1300        Visit(TL.getBaseTypeLoc());
1301      }
1302    }
1303    void VisitTypeLoc(TypeLoc TL) {
1304      // FIXME: add other typespec types and change this to an assert.
1305      TL.initialize(DS.getTypeSpecTypeLoc());
1306    }
1307  };
1308
1309  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1310    const DeclaratorChunk &Chunk;
1311
1312  public:
1313    DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1314
1315    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1316      llvm::llvm_unreachable("qualified type locs not expected here!");
1317    }
1318
1319    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1320      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1321      TL.setCaretLoc(Chunk.Loc);
1322    }
1323    void VisitPointerTypeLoc(PointerTypeLoc TL) {
1324      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1325      TL.setStarLoc(Chunk.Loc);
1326    }
1327    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1328      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1329      TL.setStarLoc(Chunk.Loc);
1330      TL.setHasBaseTypeAsWritten(true);
1331      TL.setHasProtocolsAsWritten(false);
1332      TL.setLAngleLoc(SourceLocation());
1333      TL.setRAngleLoc(SourceLocation());
1334    }
1335    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1336      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1337      TL.setStarLoc(Chunk.Loc);
1338      // FIXME: nested name specifier
1339    }
1340    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1341      assert(Chunk.Kind == DeclaratorChunk::Reference);
1342      // 'Amp' is misleading: this might have been originally
1343      /// spelled with AmpAmp.
1344      TL.setAmpLoc(Chunk.Loc);
1345    }
1346    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1347      assert(Chunk.Kind == DeclaratorChunk::Reference);
1348      assert(!Chunk.Ref.LValueRef);
1349      TL.setAmpAmpLoc(Chunk.Loc);
1350    }
1351    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1352      assert(Chunk.Kind == DeclaratorChunk::Array);
1353      TL.setLBracketLoc(Chunk.Loc);
1354      TL.setRBracketLoc(Chunk.EndLoc);
1355      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1356    }
1357    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1358      assert(Chunk.Kind == DeclaratorChunk::Function);
1359      TL.setLParenLoc(Chunk.Loc);
1360      TL.setRParenLoc(Chunk.EndLoc);
1361
1362      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1363      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1364        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1365        TL.setArg(tpi++, Param);
1366      }
1367      // FIXME: exception specs
1368    }
1369
1370    void VisitTypeLoc(TypeLoc TL) {
1371      llvm::llvm_unreachable("unsupported TypeLoc kind in declarator!");
1372    }
1373  };
1374}
1375
1376/// \brief Create and instantiate a DeclaratorInfo with type source information.
1377///
1378/// \param T QualType referring to the type as written in source code.
1379DeclaratorInfo *
1380Sema::GetDeclaratorInfoForDeclarator(Declarator &D, QualType T, unsigned Skip) {
1381  DeclaratorInfo *DInfo = Context.CreateDeclaratorInfo(T);
1382  UnqualTypeLoc CurrTL = DInfo->getTypeLoc().getUnqualifiedLoc();
1383
1384  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
1385    DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1386    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1387  }
1388
1389  TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1390
1391  return DInfo;
1392}
1393
1394/// \brief Create a LocInfoType to hold the given QualType and DeclaratorInfo.
1395QualType Sema::CreateLocInfoType(QualType T, DeclaratorInfo *DInfo) {
1396  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1397  // and Sema during declaration parsing. Try deallocating/caching them when
1398  // it's appropriate, instead of allocating them and keeping them around.
1399  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1400  new (LocT) LocInfoType(T, DInfo);
1401  assert(LocT->getTypeClass() != T->getTypeClass() &&
1402         "LocInfoType's TypeClass conflicts with an existing Type class");
1403  return QualType(LocT, 0);
1404}
1405
1406void LocInfoType::getAsStringInternal(std::string &Str,
1407                                      const PrintingPolicy &Policy) const {
1408  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1409         " was used directly instead of getting the QualType through"
1410         " GetTypeFromParser");
1411}
1412
1413/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1414/// declarator
1415QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1416  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1417  QualType T = MDecl->getResultType();
1418  llvm::SmallVector<QualType, 16> ArgTys;
1419
1420  // Add the first two invisible argument types for self and _cmd.
1421  if (MDecl->isInstanceMethod()) {
1422    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1423    selfTy = Context.getPointerType(selfTy);
1424    ArgTys.push_back(selfTy);
1425  } else
1426    ArgTys.push_back(Context.getObjCIdType());
1427  ArgTys.push_back(Context.getObjCSelType());
1428
1429  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1430       E = MDecl->param_end(); PI != E; ++PI) {
1431    QualType ArgTy = (*PI)->getType();
1432    assert(!ArgTy.isNull() && "Couldn't parse type?");
1433    ArgTy = adjustParameterType(ArgTy);
1434    ArgTys.push_back(ArgTy);
1435  }
1436  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1437                              MDecl->isVariadic(), 0);
1438  return T;
1439}
1440
1441/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1442/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1443/// they point to and return true. If T1 and T2 aren't pointer types
1444/// or pointer-to-member types, or if they are not similar at this
1445/// level, returns false and leaves T1 and T2 unchanged. Top-level
1446/// qualifiers on T1 and T2 are ignored. This function will typically
1447/// be called in a loop that successively "unwraps" pointer and
1448/// pointer-to-member types to compare them at each level.
1449bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1450  const PointerType *T1PtrType = T1->getAs<PointerType>(),
1451                    *T2PtrType = T2->getAs<PointerType>();
1452  if (T1PtrType && T2PtrType) {
1453    T1 = T1PtrType->getPointeeType();
1454    T2 = T2PtrType->getPointeeType();
1455    return true;
1456  }
1457
1458  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1459                          *T2MPType = T2->getAs<MemberPointerType>();
1460  if (T1MPType && T2MPType &&
1461      Context.getCanonicalType(T1MPType->getClass()) ==
1462      Context.getCanonicalType(T2MPType->getClass())) {
1463    T1 = T1MPType->getPointeeType();
1464    T2 = T2MPType->getPointeeType();
1465    return true;
1466  }
1467  return false;
1468}
1469
1470Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1471  // C99 6.7.6: Type names have no identifier.  This is already validated by
1472  // the parser.
1473  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1474
1475  DeclaratorInfo *DInfo = 0;
1476  TagDecl *OwnedTag = 0;
1477  QualType T = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
1478  if (D.isInvalidType())
1479    return true;
1480
1481  if (getLangOptions().CPlusPlus) {
1482    // Check that there are no default arguments (C++ only).
1483    CheckExtraCXXDefaultArguments(D);
1484
1485    // C++0x [dcl.type]p3:
1486    //   A type-specifier-seq shall not define a class or enumeration
1487    //   unless it appears in the type-id of an alias-declaration
1488    //   (7.1.3).
1489    if (OwnedTag && OwnedTag->isDefinition())
1490      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1491        << Context.getTypeDeclType(OwnedTag);
1492  }
1493
1494  if (DInfo)
1495    T = CreateLocInfoType(T, DInfo);
1496
1497  return T.getAsOpaquePtr();
1498}
1499
1500
1501
1502//===----------------------------------------------------------------------===//
1503// Type Attribute Processing
1504//===----------------------------------------------------------------------===//
1505
1506/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1507/// specified type.  The attribute contains 1 argument, the id of the address
1508/// space for the type.
1509static void HandleAddressSpaceTypeAttribute(QualType &Type,
1510                                            const AttributeList &Attr, Sema &S){
1511
1512  // If this type is already address space qualified, reject it.
1513  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1514  // for two or more different address spaces."
1515  if (Type.getAddressSpace()) {
1516    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1517    return;
1518  }
1519
1520  // Check the attribute arguments.
1521  if (Attr.getNumArgs() != 1) {
1522    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1523    return;
1524  }
1525  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1526  llvm::APSInt addrSpace(32);
1527  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1528    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1529      << ASArgExpr->getSourceRange();
1530    return;
1531  }
1532
1533  // Bounds checking.
1534  if (addrSpace.isSigned()) {
1535    if (addrSpace.isNegative()) {
1536      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1537        << ASArgExpr->getSourceRange();
1538      return;
1539    }
1540    addrSpace.setIsSigned(false);
1541  }
1542  llvm::APSInt max(addrSpace.getBitWidth());
1543  max = Qualifiers::MaxAddressSpace;
1544  if (addrSpace > max) {
1545    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1546      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1547    return;
1548  }
1549
1550  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1551  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1552}
1553
1554/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1555/// specified type.  The attribute contains 1 argument, weak or strong.
1556static void HandleObjCGCTypeAttribute(QualType &Type,
1557                                      const AttributeList &Attr, Sema &S) {
1558  if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1559    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1560    return;
1561  }
1562
1563  // Check the attribute arguments.
1564  if (!Attr.getParameterName()) {
1565    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1566      << "objc_gc" << 1;
1567    return;
1568  }
1569  Qualifiers::GC GCAttr;
1570  if (Attr.getNumArgs() != 0) {
1571    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1572    return;
1573  }
1574  if (Attr.getParameterName()->isStr("weak"))
1575    GCAttr = Qualifiers::Weak;
1576  else if (Attr.getParameterName()->isStr("strong"))
1577    GCAttr = Qualifiers::Strong;
1578  else {
1579    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1580      << "objc_gc" << Attr.getParameterName();
1581    return;
1582  }
1583
1584  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1585}
1586
1587/// HandleNoReturnTypeAttribute - Process the noreturn attribute on the
1588/// specified type.  The attribute contains 0 arguments.
1589static void HandleNoReturnTypeAttribute(QualType &Type,
1590                                        const AttributeList &Attr, Sema &S) {
1591  if (Attr.getNumArgs() != 0)
1592    return;
1593
1594  // We only apply this to a pointer to function or a pointer to block.
1595  if (!Type->isFunctionPointerType()
1596      && !Type->isBlockPointerType()
1597      && !Type->isFunctionType())
1598    return;
1599
1600  Type = S.Context.getNoReturnType(Type);
1601}
1602
1603void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1604  // Scan through and apply attributes to this type where it makes sense.  Some
1605  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1606  // type, but others can be present in the type specifiers even though they
1607  // apply to the decl.  Here we apply type attributes and ignore the rest.
1608  for (; AL; AL = AL->getNext()) {
1609    // If this is an attribute we can handle, do so now, otherwise, add it to
1610    // the LeftOverAttrs list for rechaining.
1611    switch (AL->getKind()) {
1612    default: break;
1613    case AttributeList::AT_address_space:
1614      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1615      break;
1616    case AttributeList::AT_objc_gc:
1617      HandleObjCGCTypeAttribute(Result, *AL, *this);
1618      break;
1619    case AttributeList::AT_noreturn:
1620      HandleNoReturnTypeAttribute(Result, *AL, *this);
1621      break;
1622    }
1623  }
1624}
1625
1626/// @brief Ensure that the type T is a complete type.
1627///
1628/// This routine checks whether the type @p T is complete in any
1629/// context where a complete type is required. If @p T is a complete
1630/// type, returns false. If @p T is a class template specialization,
1631/// this routine then attempts to perform class template
1632/// instantiation. If instantiation fails, or if @p T is incomplete
1633/// and cannot be completed, issues the diagnostic @p diag (giving it
1634/// the type @p T) and returns true.
1635///
1636/// @param Loc  The location in the source that the incomplete type
1637/// diagnostic should refer to.
1638///
1639/// @param T  The type that this routine is examining for completeness.
1640///
1641/// @param PD The partial diagnostic that will be printed out if T is not a
1642/// complete type.
1643///
1644/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1645/// @c false otherwise.
1646bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1647                               const PartialDiagnostic &PD,
1648                               std::pair<SourceLocation,
1649                                         PartialDiagnostic> Note) {
1650  unsigned diag = PD.getDiagID();
1651
1652  // FIXME: Add this assertion to make sure we always get instantiation points.
1653  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
1654  // FIXME: Add this assertion to help us flush out problems with
1655  // checking for dependent types and type-dependent expressions.
1656  //
1657  //  assert(!T->isDependentType() &&
1658  //         "Can't ask whether a dependent type is complete");
1659
1660  // If we have a complete type, we're done.
1661  if (!T->isIncompleteType())
1662    return false;
1663
1664  // If we have a class template specialization or a class member of a
1665  // class template specialization, try to instantiate it.
1666  if (const RecordType *Record = T->getAs<RecordType>()) {
1667    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1668          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1669      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1670        if (Loc.isValid())
1671          ClassTemplateSpec->setPointOfInstantiation(Loc);
1672        return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1673                                                      TSK_ImplicitInstantiation,
1674                                                      /*Complain=*/diag != 0);
1675      }
1676    } else if (CXXRecordDecl *Rec
1677                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1678      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1679        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
1680        assert(MSInfo && "Missing member specialization information?");
1681        // This record was instantiated from a class within a template.
1682        if (MSInfo->getTemplateSpecializationKind()
1683                                               != TSK_ExplicitSpecialization) {
1684          MSInfo->setPointOfInstantiation(Loc);
1685          return InstantiateClass(Loc, Rec, Pattern,
1686                                  getTemplateInstantiationArgs(Rec),
1687                                  TSK_ImplicitInstantiation,
1688                                  /*Complain=*/diag != 0);
1689        }
1690      }
1691    }
1692  }
1693
1694  if (diag == 0)
1695    return true;
1696
1697  // We have an incomplete type. Produce a diagnostic.
1698  Diag(Loc, PD) << T;
1699
1700  // If we have a note, produce it.
1701  if (!Note.first.isInvalid())
1702    Diag(Note.first, Note.second);
1703
1704  // If the type was a forward declaration of a class/struct/union
1705  // type, produce
1706  const TagType *Tag = 0;
1707  if (const RecordType *Record = T->getAs<RecordType>())
1708    Tag = Record;
1709  else if (const EnumType *Enum = T->getAs<EnumType>())
1710    Tag = Enum;
1711
1712  if (Tag && !Tag->getDecl()->isInvalidDecl())
1713    Diag(Tag->getDecl()->getLocation(),
1714         Tag->isBeingDefined() ? diag::note_type_being_defined
1715                               : diag::note_forward_declaration)
1716        << QualType(Tag, 0);
1717
1718  return true;
1719}
1720
1721/// \brief Retrieve a version of the type 'T' that is qualified by the
1722/// nested-name-specifier contained in SS.
1723QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1724  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1725    return T;
1726
1727  NestedNameSpecifier *NNS
1728    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1729  return Context.getQualifiedNameType(NNS, T);
1730}
1731
1732QualType Sema::BuildTypeofExprType(Expr *E) {
1733  return Context.getTypeOfExprType(E);
1734}
1735
1736QualType Sema::BuildDecltypeType(Expr *E) {
1737  if (E->getType() == Context.OverloadTy) {
1738    Diag(E->getLocStart(),
1739         diag::err_cannot_determine_declared_type_of_overloaded_function);
1740    return QualType();
1741  }
1742  return Context.getDecltypeType(E);
1743}
1744