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