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