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