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