1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
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"
26 using namespace clang;
28 /// \brief Perform adjustment on the parameter type of a function.
30 /// This routine adjusts the given parameter type @p T to the actual
31 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
32 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
33 QualType Sema::adjustParameterType(QualType T) {
35 // A declaration of a parameter as "array of type" shall be
36 // adjusted to "qualified pointer to type", where the type
37 // qualifiers (if any) are those specified within the [ and ] of
38 // the array type derivation.
40 return Context.getArrayDecayedType(T);
43 // A declaration of a parameter as "function returning type"
44 // shall be adjusted to "pointer to function returning type", as
46 if (T->isFunctionType())
47 return Context.getPointerType(T);
54 /// isOmittedBlockReturnType - Return true if this declarator is missing a
55 /// return type because this is a omitted return type on a block literal.
56 static bool isOmittedBlockReturnType(const Declarator &D) {
57 if (D.getContext() != Declarator::BlockLiteralContext ||
58 D.getDeclSpec().hasTypeSpecifier())
61 if (D.getNumTypeObjects() == 0)
62 return true; // ^{ ... }
64 if (D.getNumTypeObjects() == 1 &&
65 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
66 return true; // ^(int X, float Y) { ... }
71 typedef std::pair<const AttributeList*,QualType> DelayedAttribute;
72 typedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet;
74 static void ProcessTypeAttributeList(Sema &S, QualType &Type,
76 const AttributeList *Attrs,
77 DelayedAttributeSet &DelayedFnAttrs);
78 static bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr);
80 static void ProcessDelayedFnAttrs(Sema &S, QualType &Type,
81 DelayedAttributeSet &Attrs) {
82 for (DelayedAttributeSet::iterator I = Attrs.begin(),
83 E = Attrs.end(); I != E; ++I)
84 if (ProcessFnAttr(S, Type, *I->first))
85 S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
86 << I->first->getName() << I->second;
90 static void DiagnoseDelayedFnAttrs(Sema &S, DelayedAttributeSet &Attrs) {
91 for (DelayedAttributeSet::iterator I = Attrs.begin(),
92 E = Attrs.end(); I != E; ++I) {
93 S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
94 << I->first->getName() << I->second;
99 /// \brief Convert the specified declspec to the appropriate type
101 /// \param D the declarator containing the declaration specifier.
102 /// \returns The type described by the declaration specifiers. This function
103 /// never returns null.
104 static QualType ConvertDeclSpecToType(Sema &TheSema,
105 Declarator &TheDeclarator,
106 DelayedAttributeSet &Delayed) {
107 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
109 const DeclSpec &DS = TheDeclarator.getDeclSpec();
110 SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
111 if (DeclLoc.isInvalid())
112 DeclLoc = DS.getSourceRange().getBegin();
114 ASTContext &Context = TheSema.Context;
117 switch (DS.getTypeSpecType()) {
118 case DeclSpec::TST_void:
119 Result = Context.VoidTy;
121 case DeclSpec::TST_char:
122 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
123 Result = Context.CharTy;
124 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
125 Result = Context.SignedCharTy;
127 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
128 "Unknown TSS value");
129 Result = Context.UnsignedCharTy;
132 case DeclSpec::TST_wchar:
133 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
134 Result = Context.WCharTy;
135 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
136 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
137 << DS.getSpecifierName(DS.getTypeSpecType());
138 Result = Context.getSignedWCharType();
140 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
141 "Unknown TSS value");
142 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
143 << DS.getSpecifierName(DS.getTypeSpecType());
144 Result = Context.getUnsignedWCharType();
147 case DeclSpec::TST_char16:
148 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
149 "Unknown TSS value");
150 Result = Context.Char16Ty;
152 case DeclSpec::TST_char32:
153 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
154 "Unknown TSS value");
155 Result = Context.Char32Ty;
157 case DeclSpec::TST_unspecified:
158 // "<proto1,proto2>" is an objc qualified ID with a missing id.
159 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
160 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
161 (ObjCProtocolDecl**)PQ,
162 DS.getNumProtocolQualifiers());
166 // If this is a missing declspec in a block literal return context, then it
167 // is inferred from the return statements inside the block.
168 if (isOmittedBlockReturnType(TheDeclarator)) {
169 Result = Context.DependentTy;
173 // Unspecified typespec defaults to int in C90. However, the C90 grammar
174 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
175 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
176 // Note that the one exception to this is function definitions, which are
177 // allowed to be completely missing a declspec. This is handled in the
178 // parser already though by it pretending to have seen an 'int' in this
180 if (TheSema.getLangOptions().ImplicitInt) {
181 // In C89 mode, we only warn if there is a completely missing declspec
182 // when one is not allowed.
184 TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
185 << DS.getSourceRange()
186 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
188 } else if (!DS.hasTypeSpecifier()) {
189 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
190 // "At least one type specifier shall be given in the declaration
191 // specifiers in each declaration, and in the specifier-qualifier list in
192 // each struct declaration and type name."
193 // FIXME: Does Microsoft really have the implicit int extension in C++?
194 if (TheSema.getLangOptions().CPlusPlus &&
195 !TheSema.getLangOptions().Microsoft) {
196 TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
197 << DS.getSourceRange();
199 // When this occurs in C++ code, often something is very broken with the
200 // value being declared, poison it as invalid so we don't get chains of
202 TheDeclarator.setInvalidType(true);
204 TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
205 << DS.getSourceRange();
210 case DeclSpec::TST_int: {
211 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
212 switch (DS.getTypeSpecWidth()) {
213 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
214 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
215 case DeclSpec::TSW_long: Result = Context.LongTy; break;
216 case DeclSpec::TSW_longlong:
217 Result = Context.LongLongTy;
219 // long long is a C99 feature.
220 if (!TheSema.getLangOptions().C99 &&
221 !TheSema.getLangOptions().CPlusPlus0x)
222 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
226 switch (DS.getTypeSpecWidth()) {
227 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
228 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
229 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
230 case DeclSpec::TSW_longlong:
231 Result = Context.UnsignedLongLongTy;
233 // long long is a C99 feature.
234 if (!TheSema.getLangOptions().C99 &&
235 !TheSema.getLangOptions().CPlusPlus0x)
236 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
242 case DeclSpec::TST_float: Result = Context.FloatTy; break;
243 case DeclSpec::TST_double:
244 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
245 Result = Context.LongDoubleTy;
247 Result = Context.DoubleTy;
249 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
250 case DeclSpec::TST_decimal32: // _Decimal32
251 case DeclSpec::TST_decimal64: // _Decimal64
252 case DeclSpec::TST_decimal128: // _Decimal128
253 TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
254 Result = Context.IntTy;
255 TheDeclarator.setInvalidType(true);
257 case DeclSpec::TST_class:
258 case DeclSpec::TST_enum:
259 case DeclSpec::TST_union:
260 case DeclSpec::TST_struct: {
262 = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
264 // This can happen in C++ with ambiguous lookups.
265 Result = Context.IntTy;
266 TheDeclarator.setInvalidType(true);
270 // If the type is deprecated or unavailable, diagnose it.
271 TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
273 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
274 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
276 // TypeQuals handled by caller.
277 Result = Context.getTypeDeclType(D);
279 // In C++, make an ElaboratedType.
280 if (TheSema.getLangOptions().CPlusPlus) {
282 = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType());
283 Result = Context.getElaboratedType(Result, Tag);
286 if (D->isInvalidDecl())
287 TheDeclarator.setInvalidType(true);
290 case DeclSpec::TST_typename: {
291 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
292 DS.getTypeSpecSign() == 0 &&
293 "Can't handle qualifiers on typedef names yet!");
294 Result = TheSema.GetTypeFromParser(DS.getTypeRep());
296 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
297 if (const ObjCInterfaceType *
298 Interface = Result->getAs<ObjCInterfaceType>()) {
299 // It would be nice if protocol qualifiers were only stored with the
300 // ObjCObjectPointerType. Unfortunately, this isn't possible due
301 // to the following typedef idiom (which is uncommon, but allowed):
304 // static void func() {
308 Result = Context.getObjCInterfaceType(Interface->getDecl(),
309 (ObjCProtocolDecl**)PQ,
310 DS.getNumProtocolQualifiers());
311 } else if (Result->isObjCIdType())
313 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
314 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
315 else if (Result->isObjCClassType()) {
316 // Class<protocol-list>
317 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
318 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
320 TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
321 << DS.getSourceRange();
322 TheDeclarator.setInvalidType(true);
326 // TypeQuals handled by caller.
329 case DeclSpec::TST_typeofType:
330 // FIXME: Preserve type source info.
331 Result = TheSema.GetTypeFromParser(DS.getTypeRep());
332 assert(!Result.isNull() && "Didn't get a type for typeof?");
333 // TypeQuals handled by caller.
334 Result = Context.getTypeOfType(Result);
336 case DeclSpec::TST_typeofExpr: {
337 Expr *E = static_cast<Expr *>(DS.getTypeRep());
338 assert(E && "Didn't get an expression for typeof?");
339 // TypeQuals handled by caller.
340 Result = TheSema.BuildTypeofExprType(E);
341 if (Result.isNull()) {
342 Result = Context.IntTy;
343 TheDeclarator.setInvalidType(true);
347 case DeclSpec::TST_decltype: {
348 Expr *E = static_cast<Expr *>(DS.getTypeRep());
349 assert(E && "Didn't get an expression for decltype?");
350 // TypeQuals handled by caller.
351 Result = TheSema.BuildDecltypeType(E);
352 if (Result.isNull()) {
353 Result = Context.IntTy;
354 TheDeclarator.setInvalidType(true);
358 case DeclSpec::TST_auto: {
359 // TypeQuals handled by caller.
360 Result = Context.UndeducedAutoTy;
364 case DeclSpec::TST_error:
365 Result = Context.IntTy;
366 TheDeclarator.setInvalidType(true);
370 // Handle complex types.
371 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
372 if (TheSema.getLangOptions().Freestanding)
373 TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
374 Result = Context.getComplexType(Result);
375 } else if (DS.isTypeAltiVecVector()) {
376 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
377 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
378 Result = Context.getVectorType(Result, 128/typeSize, true,
379 DS.isTypeAltiVecPixel());
382 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
383 "FIXME: imaginary types not supported yet!");
385 // See if there are any attributes on the declspec that apply to the type (as
386 // opposed to the decl).
387 if (const AttributeList *AL = DS.getAttributes())
388 ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed);
390 // Apply const/volatile/restrict qualifiers to T.
391 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
393 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
394 // or incomplete types shall not be restrict-qualified." C++ also allows
395 // restrict-qualified references.
396 if (TypeQuals & DeclSpec::TQ_restrict) {
397 if (Result->isAnyPointerType() || Result->isReferenceType()) {
399 if (Result->isObjCObjectPointerType())
402 EltTy = Result->isPointerType() ?
403 Result->getAs<PointerType>()->getPointeeType() :
404 Result->getAs<ReferenceType>()->getPointeeType();
406 // If we have a pointer or reference, the pointee must have an object
408 if (!EltTy->isIncompleteOrObjectType()) {
409 TheSema.Diag(DS.getRestrictSpecLoc(),
410 diag::err_typecheck_invalid_restrict_invalid_pointee)
411 << EltTy << DS.getSourceRange();
412 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
415 TheSema.Diag(DS.getRestrictSpecLoc(),
416 diag::err_typecheck_invalid_restrict_not_pointer)
417 << Result << DS.getSourceRange();
418 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
422 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
423 // of a function type includes any type qualifiers, the behavior is
425 if (Result->isFunctionType() && TypeQuals) {
426 // Get some location to point at, either the C or V location.
428 if (TypeQuals & DeclSpec::TQ_const)
429 Loc = DS.getConstSpecLoc();
430 else if (TypeQuals & DeclSpec::TQ_volatile)
431 Loc = DS.getVolatileSpecLoc();
433 assert((TypeQuals & DeclSpec::TQ_restrict) &&
434 "Has CVR quals but not C, V, or R?");
435 Loc = DS.getRestrictSpecLoc();
437 TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
438 << Result << DS.getSourceRange();
442 // Cv-qualified references are ill-formed except when the
443 // cv-qualifiers are introduced through the use of a typedef
444 // (7.1.3) or of a template type argument (14.3), in which
445 // case the cv-qualifiers are ignored.
446 // FIXME: Shouldn't we be checking SCS_typedef here?
447 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
448 TypeQuals && Result->isReferenceType()) {
449 TypeQuals &= ~DeclSpec::TQ_const;
450 TypeQuals &= ~DeclSpec::TQ_volatile;
453 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
454 Result = Context.getQualifiedType(Result, Quals);
460 static std::string getPrintableNameForEntity(DeclarationName Entity) {
462 return Entity.getAsString();
467 /// \brief Build a pointer type.
469 /// \param T The type to which we'll be building a pointer.
471 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
473 /// \param Loc The location of the entity whose type involves this
474 /// pointer type or, if there is no such entity, the location of the
475 /// type that will have pointer type.
477 /// \param Entity The name of the entity that involves the pointer
480 /// \returns A suitable pointer type, if there are no
481 /// errors. Otherwise, returns a NULL type.
482 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
483 SourceLocation Loc, DeclarationName Entity) {
484 if (T->isReferenceType()) {
485 // C++ 8.3.2p4: There shall be no ... pointers to references ...
486 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
487 << getPrintableNameForEntity(Entity) << T;
491 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
493 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
494 // object or incomplete types shall not be restrict-qualified."
495 if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
496 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
501 // Build the pointer type.
502 return Context.getQualifiedType(Context.getPointerType(T), Qs);
505 /// \brief Build a reference type.
507 /// \param T The type to which we'll be building a reference.
509 /// \param CVR The cvr-qualifiers to be applied to the reference type.
511 /// \param Loc The location of the entity whose type involves this
512 /// reference type or, if there is no such entity, the location of the
513 /// type that will have reference type.
515 /// \param Entity The name of the entity that involves the reference
518 /// \returns A suitable reference type, if there are no
519 /// errors. Otherwise, returns a NULL type.
520 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
521 unsigned CVR, SourceLocation Loc,
522 DeclarationName Entity) {
523 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
525 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
527 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
528 // reference to a type T, and attempt to create the type "lvalue
529 // reference to cv TD" creates the type "lvalue reference to T".
530 // We use the qualifiers (restrict or none) of the original reference,
531 // not the new ones. This is consistent with GCC.
533 // C++ [dcl.ref]p4: There shall be no references to references.
535 // According to C++ DR 106, references to references are only
536 // diagnosed when they are written directly (e.g., "int & &"),
537 // but not when they happen via a typedef:
539 // typedef int& intref;
540 // typedef intref& intref2;
542 // Parser::ParseDeclaratorInternal diagnoses the case where
543 // references are written directly; here, we handle the
544 // collapsing of references-to-references as described in C++
545 // DR 106 and amended by C++ DR 540.
548 // A declarator that specifies the type "reference to cv void"
550 if (T->isVoidType()) {
551 Diag(Loc, diag::err_reference_to_void);
555 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
556 // object or incomplete types shall not be restrict-qualified."
557 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
558 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
560 Quals.removeRestrict();
564 // [...] Cv-qualified references are ill-formed except when the
565 // cv-qualifiers are introduced through the use of a typedef
566 // (7.1.3) or of a template type argument (14.3), in which case
567 // the cv-qualifiers are ignored.
569 // We diagnose extraneous cv-qualifiers for the non-typedef,
570 // non-template type argument case within the parser. Here, we just
571 // ignore any extraneous cv-qualifiers.
573 Quals.removeVolatile();
575 // Handle restrict on references.
577 return Context.getQualifiedType(
578 Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
579 return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
582 /// \brief Build an array type.
584 /// \param T The type of each element in the array.
586 /// \param ASM C99 array size modifier (e.g., '*', 'static').
588 /// \param ArraySize Expression describing the size of the array.
590 /// \param Quals The cvr-qualifiers to be applied to the array's
593 /// \param Loc The location of the entity whose type involves this
594 /// array type or, if there is no such entity, the location of the
595 /// type that will have array type.
597 /// \param Entity The name of the entity that involves the array
600 /// \returns A suitable array type, if there are no errors. Otherwise,
601 /// returns a NULL type.
602 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
603 Expr *ArraySize, unsigned Quals,
604 SourceRange Brackets, DeclarationName Entity) {
606 SourceLocation Loc = Brackets.getBegin();
607 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
608 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
609 // Not in C++, though. There we only dislike void.
610 if (getLangOptions().CPlusPlus) {
611 if (T->isVoidType()) {
612 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
616 if (RequireCompleteType(Loc, T,
617 diag::err_illegal_decl_array_incomplete_type))
621 if (T->isFunctionType()) {
622 Diag(Loc, diag::err_illegal_decl_array_of_functions)
623 << getPrintableNameForEntity(Entity) << T;
627 // C++ 8.3.2p4: There shall be no ... arrays of references ...
628 if (T->isReferenceType()) {
629 Diag(Loc, diag::err_illegal_decl_array_of_references)
630 << getPrintableNameForEntity(Entity) << T;
634 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
635 Diag(Loc, diag::err_illegal_decl_array_of_auto)
636 << getPrintableNameForEntity(Entity);
640 if (const RecordType *EltTy = T->getAs<RecordType>()) {
641 // If the element type is a struct or union that contains a variadic
642 // array, accept it as a GNU extension: C99 6.7.2.1p2.
643 if (EltTy->getDecl()->hasFlexibleArrayMember())
644 Diag(Loc, diag::ext_flexible_array_in_array) << T;
645 } else if (T->isObjCInterfaceType()) {
646 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
650 // C99 6.7.5.2p1: The size expression shall have integer type.
651 if (ArraySize && !ArraySize->isTypeDependent() &&
652 !ArraySize->getType()->isIntegerType()) {
653 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
654 << ArraySize->getType() << ArraySize->getSourceRange();
655 ArraySize->Destroy(Context);
658 llvm::APSInt ConstVal(32);
660 if (ASM == ArrayType::Star)
661 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
663 T = Context.getIncompleteArrayType(T, ASM, Quals);
664 } else if (ArraySize->isValueDependent()) {
665 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
666 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
667 (!T->isDependentType() && !T->isIncompleteType() &&
668 !T->isConstantSizeType())) {
669 // Per C99, a variable array is an array with either a non-constant
670 // size or an element type that has a non-constant-size
671 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
673 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
674 // have a value greater than zero.
675 if (ConstVal.isSigned() && ConstVal.isNegative()) {
676 Diag(ArraySize->getLocStart(),
677 diag::err_typecheck_negative_array_size)
678 << ArraySize->getSourceRange();
682 // GCC accepts zero sized static arrays. We allow them when
683 // we're not in a SFINAE context.
684 Diag(ArraySize->getLocStart(),
685 isSFINAEContext()? diag::err_typecheck_zero_array_size
686 : diag::ext_typecheck_zero_array_size)
687 << ArraySize->getSourceRange();
689 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
691 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
692 if (!getLangOptions().C99) {
693 if (ArraySize && !ArraySize->isTypeDependent() &&
694 !ArraySize->isValueDependent() &&
695 !ArraySize->isIntegerConstantExpr(Context))
696 Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla);
697 else if (ASM != ArrayType::Normal || Quals != 0)
699 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
700 : diag::ext_c99_array_usage);
706 /// \brief Build an ext-vector type.
708 /// Run the required checks for the extended vector type.
709 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
710 SourceLocation AttrLoc) {
712 Expr *Arg = (Expr *)ArraySize.get();
714 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
715 // in conjunction with complex types (pointers, arrays, functions, etc.).
716 if (!T->isDependentType() &&
717 !T->isIntegerType() && !T->isRealFloatingType()) {
718 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
722 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
723 llvm::APSInt vecSize(32);
724 if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
725 Diag(AttrLoc, diag::err_attribute_argument_not_int)
726 << "ext_vector_type" << Arg->getSourceRange();
730 // unlike gcc's vector_size attribute, the size is specified as the
731 // number of elements, not the number of bytes.
732 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
734 if (vectorSize == 0) {
735 Diag(AttrLoc, diag::err_attribute_zero_size)
736 << Arg->getSourceRange();
740 if (!T->isDependentType())
741 return Context.getExtVectorType(T, vectorSize);
744 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
748 /// \brief Build a function type.
750 /// This routine checks the function type according to C++ rules and
751 /// under the assumption that the result type and parameter types have
752 /// just been instantiated from a template. It therefore duplicates
753 /// some of the behavior of GetTypeForDeclarator, but in a much
754 /// simpler form that is only suitable for this narrow use case.
756 /// \param T The return type of the function.
758 /// \param ParamTypes The parameter types of the function. This array
759 /// will be modified to account for adjustments to the types of the
760 /// function parameters.
762 /// \param NumParamTypes The number of parameter types in ParamTypes.
764 /// \param Variadic Whether this is a variadic function type.
766 /// \param Quals The cvr-qualifiers to be applied to the function type.
768 /// \param Loc The location of the entity whose type involves this
769 /// function type or, if there is no such entity, the location of the
770 /// type that will have function type.
772 /// \param Entity The name of the entity that involves the function
775 /// \returns A suitable function type, if there are no
776 /// errors. Otherwise, returns a NULL type.
777 QualType Sema::BuildFunctionType(QualType T,
778 QualType *ParamTypes,
779 unsigned NumParamTypes,
780 bool Variadic, unsigned Quals,
781 SourceLocation Loc, DeclarationName Entity) {
782 if (T->isArrayType() || T->isFunctionType()) {
783 Diag(Loc, diag::err_func_returning_array_function)
784 << T->isFunctionType() << T;
788 bool Invalid = false;
789 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
790 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
791 if (ParamType->isVoidType()) {
792 Diag(Loc, diag::err_param_with_void_type);
796 ParamTypes[Idx] = ParamType;
802 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
803 Quals, false, false, 0, 0,
804 FunctionType::ExtInfo());
807 /// \brief Build a member pointer type \c T Class::*.
809 /// \param T the type to which the member pointer refers.
810 /// \param Class the class type into which the member pointer points.
811 /// \param CVR Qualifiers applied to the member pointer type
812 /// \param Loc the location where this type begins
813 /// \param Entity the name of the entity that will have this member pointer type
815 /// \returns a member pointer type, if successful, or a NULL type if there was
817 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
818 unsigned CVR, SourceLocation Loc,
819 DeclarationName Entity) {
820 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
822 // Verify that we're not building a pointer to pointer to function with
823 // exception specification.
824 if (CheckDistantExceptionSpec(T)) {
825 Diag(Loc, diag::err_distant_exception_spec);
827 // FIXME: If we're doing this as part of template instantiation,
828 // we should return immediately.
830 // Build the type anyway, but use the canonical type so that the
831 // exception specifiers are stripped off.
832 T = Context.getCanonicalType(T);
835 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
836 // with reference type, or "cv void."
837 if (T->isReferenceType()) {
838 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
839 << (Entity? Entity.getAsString() : "type name") << T;
843 if (T->isVoidType()) {
844 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
845 << (Entity? Entity.getAsString() : "type name");
849 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
850 // object or incomplete types shall not be restrict-qualified."
851 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
852 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
855 // FIXME: If we're doing this as part of template instantiation,
856 // we should return immediately.
857 Quals.removeRestrict();
860 if (!Class->isDependentType() && !Class->isRecordType()) {
861 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
865 return Context.getQualifiedType(
866 Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
869 /// \brief Build a block pointer type.
871 /// \param T The type to which we'll be building a block pointer.
873 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
875 /// \param Loc The location of the entity whose type involves this
876 /// block pointer type or, if there is no such entity, the location of the
877 /// type that will have block pointer type.
879 /// \param Entity The name of the entity that involves the block pointer
882 /// \returns A suitable block pointer type, if there are no
883 /// errors. Otherwise, returns a NULL type.
884 QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
886 DeclarationName Entity) {
887 if (!T->isFunctionType()) {
888 Diag(Loc, diag::err_nonfunction_block_type);
892 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
893 return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
896 QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) {
897 QualType QT = QualType::getFromOpaquePtr(Ty);
899 if (TInfo) *TInfo = 0;
903 TypeSourceInfo *DI = 0;
904 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
906 DI = LIT->getTypeSourceInfo();
909 if (TInfo) *TInfo = DI;
913 /// GetTypeForDeclarator - Convert the type for the specified
914 /// declarator to Type instances.
916 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
917 /// owns the declaration of a type (e.g., the definition of a struct
918 /// type), then *OwnedDecl will receive the owned declaration.
919 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
920 TypeSourceInfo **TInfo,
921 TagDecl **OwnedDecl) {
922 // Determine the type of the declarator. Not all forms of declarator
926 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec;
928 switch (D.getName().getKind()) {
929 case UnqualifiedId::IK_Identifier:
930 case UnqualifiedId::IK_OperatorFunctionId:
931 case UnqualifiedId::IK_LiteralOperatorId:
932 case UnqualifiedId::IK_TemplateId:
933 T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec);
935 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
936 TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
937 // Owned is embedded if it was defined here, or if it is the
938 // very first (i.e., canonical) declaration of this tag type.
939 Owned->setEmbeddedInDeclarator(Owned->isDefinition() ||
940 Owned->isCanonicalDecl());
941 if (OwnedDecl) *OwnedDecl = Owned;
945 case UnqualifiedId::IK_ConstructorName:
946 case UnqualifiedId::IK_ConstructorTemplateId:
947 case UnqualifiedId::IK_DestructorName:
948 // Constructors and destructors don't have return types. Use
953 case UnqualifiedId::IK_ConversionFunctionId:
954 // The result type of a conversion function is the type that it
956 T = GetTypeFromParser(D.getName().ConversionFunctionId);
963 if (T == Context.UndeducedAutoTy) {
966 switch (D.getContext()) {
967 case Declarator::KNRTypeListContext:
968 assert(0 && "K&R type lists aren't allowed in C++");
970 case Declarator::PrototypeContext:
971 Error = 0; // Function prototype
973 case Declarator::MemberContext:
974 switch (cast<TagDecl>(CurContext)->getTagKind()) {
975 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
976 case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
977 case TagDecl::TK_union: Error = 2; /* Union member */ break;
978 case TagDecl::TK_class: Error = 3; /* Class member */ break;
981 case Declarator::CXXCatchContext:
982 Error = 4; // Exception declaration
984 case Declarator::TemplateParamContext:
985 Error = 5; // Template parameter
987 case Declarator::BlockLiteralContext:
988 Error = 6; // Block literal
990 case Declarator::FileContext:
991 case Declarator::BlockContext:
992 case Declarator::ForContext:
993 case Declarator::ConditionContext:
994 case Declarator::TypeNameContext:
999 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1002 D.setInvalidType(true);
1006 // The name we're declaring, if any.
1007 DeclarationName Name;
1008 if (D.getIdentifier())
1009 Name = D.getIdentifier();
1011 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk;
1013 // Walk the DeclTypeInfo, building the recursive type as we go.
1014 // DeclTypeInfos are ordered from the identifier out, which is
1015 // opposite of what we want :).
1016 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1017 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
1018 switch (DeclType.Kind) {
1019 default: assert(0 && "Unknown decltype!");
1020 case DeclaratorChunk::BlockPointer:
1021 // If blocks are disabled, emit an error.
1022 if (!LangOpts.Blocks)
1023 Diag(DeclType.Loc, diag::err_blocks_disable);
1025 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
1028 case DeclaratorChunk::Pointer:
1029 // Verify that we're not building a pointer to pointer to function with
1030 // exception specification.
1031 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1032 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1033 D.setInvalidType(true);
1034 // Build the type anyway.
1036 if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
1037 const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>();
1038 T = Context.getObjCObjectPointerType(T,
1039 (ObjCProtocolDecl **)OIT->qual_begin(),
1040 OIT->getNumProtocols(),
1041 DeclType.Ptr.TypeQuals);
1044 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
1046 case DeclaratorChunk::Reference: {
1048 if (DeclType.Ref.HasRestrict) Quals.addRestrict();
1050 // Verify that we're not building a reference to pointer to function with
1051 // exception specification.
1052 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1053 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1054 D.setInvalidType(true);
1055 // Build the type anyway.
1057 T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
1058 DeclType.Loc, Name);
1061 case DeclaratorChunk::Array: {
1062 // Verify that we're not building an array of pointers to function with
1063 // exception specification.
1064 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1065 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1066 D.setInvalidType(true);
1067 // Build the type anyway.
1069 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1070 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1071 ArrayType::ArraySizeModifier ASM;
1073 ASM = ArrayType::Star;
1074 else if (ATI.hasStatic)
1075 ASM = ArrayType::Static;
1077 ASM = ArrayType::Normal;
1078 if (ASM == ArrayType::Star &&
1079 D.getContext() != Declarator::PrototypeContext) {
1080 // FIXME: This check isn't quite right: it allows star in prototypes
1081 // for function definitions, and disallows some edge cases detailed
1082 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1083 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1084 ASM = ArrayType::Normal;
1085 D.setInvalidType(true);
1087 T = BuildArrayType(T, ASM, ArraySize,
1088 Qualifiers::fromCVRMask(ATI.TypeQuals),
1089 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1092 case DeclaratorChunk::Function: {
1093 // If the function declarator has a prototype (i.e. it is not () and
1094 // does not have a K&R-style identifier list), then the arguments are part
1095 // of the type, otherwise the argument list is ().
1096 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1098 // C99 6.7.5.3p1: The return type may not be a function or array type.
1099 // For conversion functions, we'll diagnose this particular error later.
1100 if ((T->isArrayType() || T->isFunctionType()) &&
1101 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1102 Diag(DeclType.Loc, diag::err_func_returning_array_function)
1103 << T->isFunctionType() << T;
1105 D.setInvalidType(true);
1108 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1110 // Types shall not be defined in return or parameter types.
1111 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1112 if (Tag->isDefinition())
1113 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1114 << Context.getTypeDeclType(Tag);
1117 // Exception specs are not allowed in typedefs. Complain, but add it
1119 if (FTI.hasExceptionSpec &&
1120 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1121 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1123 if (FTI.NumArgs == 0) {
1124 if (getLangOptions().CPlusPlus) {
1125 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1126 // function takes no arguments.
1127 llvm::SmallVector<QualType, 4> Exceptions;
1128 Exceptions.reserve(FTI.NumExceptions);
1129 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1130 // FIXME: Preserve type source info.
1131 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1132 // Check that the type is valid for an exception spec, and drop it
1134 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1135 Exceptions.push_back(ET);
1137 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1138 FTI.hasExceptionSpec,
1139 FTI.hasAnyExceptionSpec,
1140 Exceptions.size(), Exceptions.data(),
1141 FunctionType::ExtInfo());
1142 } else if (FTI.isVariadic) {
1143 // We allow a zero-parameter variadic function in C if the
1144 // function is marked with the "overloadable"
1145 // attribute. Scan for this attribute now.
1146 bool Overloadable = false;
1147 for (const AttributeList *Attrs = D.getAttributes();
1148 Attrs; Attrs = Attrs->getNext()) {
1149 if (Attrs->getKind() == AttributeList::AT_overloadable) {
1150 Overloadable = true;
1156 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1157 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0,
1159 FunctionType::ExtInfo());
1161 // Simple void foo(), where the incoming T is the result type.
1162 T = Context.getFunctionNoProtoType(T);
1164 } else if (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);
1169 // Otherwise, we have a function with an argument list that is
1170 // potentially variadic.
1171 llvm::SmallVector<QualType, 16> ArgTys;
1173 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1174 ParmVarDecl *Param =
1175 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1176 QualType ArgTy = Param->getType();
1177 assert(!ArgTy.isNull() && "Couldn't parse type?");
1179 // Adjust the parameter type.
1180 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1182 // Look for 'void'. void is allowed only as a single argument to a
1183 // function with no other parameters (C99 6.7.5.3p10). We record
1184 // int(void) as a FunctionProtoType with an empty argument list.
1185 if (ArgTy->isVoidType()) {
1186 // If this is something like 'float(int, void)', reject it. 'void'
1187 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1188 // have arguments of incomplete type.
1189 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1190 Diag(DeclType.Loc, diag::err_void_only_param);
1191 ArgTy = Context.IntTy;
1192 Param->setType(ArgTy);
1193 } else if (FTI.ArgInfo[i].Ident) {
1194 // Reject, but continue to parse 'int(void abc)'.
1195 Diag(FTI.ArgInfo[i].IdentLoc,
1196 diag::err_param_with_void_type);
1197 ArgTy = Context.IntTy;
1198 Param->setType(ArgTy);
1200 // Reject, but continue to parse 'float(const void)'.
1201 if (ArgTy.hasQualifiers())
1202 Diag(DeclType.Loc, diag::err_void_param_qualified);
1204 // Do not add 'void' to the ArgTys list.
1207 } else if (!FTI.hasPrototype) {
1208 if (ArgTy->isPromotableIntegerType()) {
1209 ArgTy = Context.getPromotedIntegerType(ArgTy);
1210 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1211 if (BTy->getKind() == BuiltinType::Float)
1212 ArgTy = Context.DoubleTy;
1216 ArgTys.push_back(ArgTy);
1219 llvm::SmallVector<QualType, 4> Exceptions;
1220 Exceptions.reserve(FTI.NumExceptions);
1221 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1222 // FIXME: Preserve type source info.
1223 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1224 // Check that the type is valid for an exception spec, and drop it if
1226 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1227 Exceptions.push_back(ET);
1230 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1231 FTI.isVariadic, FTI.TypeQuals,
1232 FTI.hasExceptionSpec,
1233 FTI.hasAnyExceptionSpec,
1234 Exceptions.size(), Exceptions.data(),
1235 FunctionType::ExtInfo());
1238 // For GCC compatibility, we allow attributes that apply only to
1239 // function types to be placed on a function's return type
1240 // instead (as long as that type doesn't happen to be function
1241 // or function-pointer itself).
1242 ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk);
1246 case DeclaratorChunk::MemberPointer:
1247 // Verify that we're not building a pointer to pointer to function with
1248 // exception specification.
1249 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1250 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1251 D.setInvalidType(true);
1252 // Build the type anyway.
1254 // The scope spec must refer to a class, or be dependent.
1256 if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1257 || dyn_cast_or_null<CXXRecordDecl>(
1258 computeDeclContext(DeclType.Mem.Scope()))) {
1259 NestedNameSpecifier *NNS
1260 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1261 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1262 switch (NNS->getKind()) {
1263 case NestedNameSpecifier::Identifier:
1264 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
1265 NNS->getAsIdentifier());
1268 case NestedNameSpecifier::Namespace:
1269 case NestedNameSpecifier::Global:
1270 llvm_unreachable("Nested-name-specifier must name a type");
1273 case NestedNameSpecifier::TypeSpec:
1274 case NestedNameSpecifier::TypeSpecWithTemplate:
1275 ClsType = QualType(NNS->getAsType(), 0);
1277 ClsType = Context.getQualifiedNameType(NNSPrefix, ClsType);
1281 Diag(DeclType.Mem.Scope().getBeginLoc(),
1282 diag::err_illegal_decl_mempointer_in_nonclass)
1283 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1284 << DeclType.Mem.Scope().getRange();
1285 D.setInvalidType(true);
1288 if (!ClsType.isNull())
1289 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1290 DeclType.Loc, D.getIdentifier());
1293 D.setInvalidType(true);
1299 D.setInvalidType(true);
1303 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
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);
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?");
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
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)
1324 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1325 if (D.isFunctionDeclarator())
1326 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1328 Diag(D.getIdentifierLoc(),
1329 diag::err_invalid_qualified_typedef_function_type_use);
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());
1338 // Process any function attributes we might have delayed from the
1339 // declaration-specifiers.
1340 ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec);
1342 // If there were any type attributes applied to the decl itself, not
1343 // the type, apply them to the result type. But don't do this for
1344 // block-literal expressions, which are parsed wierdly.
1345 if (D.getContext() != Declarator::BlockLiteralContext)
1346 if (const AttributeList *Attrs = D.getAttributes())
1347 ProcessTypeAttributeList(*this, T, false, Attrs,
1348 FnAttrsFromPreviousChunk);
1350 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1353 if (D.isInvalidType())
1356 *TInfo = GetTypeSourceInfoForDeclarator(D, T);
1363 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1367 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1369 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1370 Visit(TL.getUnqualifiedLoc());
1372 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1373 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1375 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1376 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1378 if (DS.getProtocolQualifiers()) {
1379 assert(TL.getNumProtocols() > 0);
1380 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1381 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1382 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1383 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1384 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1386 assert(TL.getNumProtocols() == 0);
1387 TL.setLAngleLoc(SourceLocation());
1388 TL.setRAngleLoc(SourceLocation());
1391 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1392 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1394 TL.setStarLoc(SourceLocation());
1396 if (DS.getProtocolQualifiers()) {
1397 assert(TL.getNumProtocols() > 0);
1398 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1399 TL.setHasProtocolsAsWritten(true);
1400 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1401 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1402 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1403 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1406 assert(TL.getNumProtocols() == 0);
1407 TL.setHasProtocolsAsWritten(false);
1408 TL.setLAngleLoc(SourceLocation());
1409 TL.setRAngleLoc(SourceLocation());
1412 // This might not have been written with an inner type.
1413 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1414 TL.setHasBaseTypeAsWritten(false);
1415 TL.getBaseTypeLoc().initialize(SourceLocation());
1417 TL.setHasBaseTypeAsWritten(true);
1418 Visit(TL.getBaseTypeLoc());
1421 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1422 TypeSourceInfo *TInfo = 0;
1423 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1425 // If we got no declarator info from previous Sema routines,
1426 // just fill with the typespec loc.
1428 TL.initialize(DS.getTypeSpecTypeLoc());
1432 TemplateSpecializationTypeLoc OldTL =
1433 cast<TemplateSpecializationTypeLoc>(TInfo->getTypeLoc());
1436 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1437 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
1438 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1439 TL.setParensRange(DS.getTypeofParensRange());
1441 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1442 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
1443 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1444 TL.setParensRange(DS.getTypeofParensRange());
1445 assert(DS.getTypeRep());
1446 TypeSourceInfo *TInfo = 0;
1447 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1448 TL.setUnderlyingTInfo(TInfo);
1450 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1451 // By default, use the source location of the type specifier.
1452 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
1453 if (TL.needsExtraLocalData()) {
1454 // Set info for the written builtin specifiers.
1455 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
1456 // Try to have a meaningful source location.
1457 if (TL.getWrittenSignSpec() != TSS_unspecified)
1458 // Sign spec loc overrides the others (e.g., 'unsigned long').
1459 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
1460 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
1461 // Width spec loc overrides type spec loc (e.g., 'short int').
1462 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
1465 void VisitTypeLoc(TypeLoc TL) {
1466 // FIXME: add other typespec types and change this to an assert.
1467 TL.initialize(DS.getTypeSpecTypeLoc());
1471 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1472 const DeclaratorChunk &Chunk;
1475 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1477 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1478 llvm_unreachable("qualified type locs not expected here!");
1481 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1482 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1483 TL.setCaretLoc(Chunk.Loc);
1485 void VisitPointerTypeLoc(PointerTypeLoc TL) {
1486 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1487 TL.setStarLoc(Chunk.Loc);
1489 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1490 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1491 TL.setStarLoc(Chunk.Loc);
1492 TL.setHasBaseTypeAsWritten(true);
1493 TL.setHasProtocolsAsWritten(false);
1494 TL.setLAngleLoc(SourceLocation());
1495 TL.setRAngleLoc(SourceLocation());
1497 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1498 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1499 TL.setStarLoc(Chunk.Loc);
1500 // FIXME: nested name specifier
1502 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1503 assert(Chunk.Kind == DeclaratorChunk::Reference);
1504 // 'Amp' is misleading: this might have been originally
1505 /// spelled with AmpAmp.
1506 TL.setAmpLoc(Chunk.Loc);
1508 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1509 assert(Chunk.Kind == DeclaratorChunk::Reference);
1510 assert(!Chunk.Ref.LValueRef);
1511 TL.setAmpAmpLoc(Chunk.Loc);
1513 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1514 assert(Chunk.Kind == DeclaratorChunk::Array);
1515 TL.setLBracketLoc(Chunk.Loc);
1516 TL.setRBracketLoc(Chunk.EndLoc);
1517 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1519 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1520 assert(Chunk.Kind == DeclaratorChunk::Function);
1521 TL.setLParenLoc(Chunk.Loc);
1522 TL.setRParenLoc(Chunk.EndLoc);
1524 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1525 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1526 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1527 TL.setArg(tpi++, Param);
1529 // FIXME: exception specs
1532 void VisitTypeLoc(TypeLoc TL) {
1533 llvm_unreachable("unsupported TypeLoc kind in declarator!");
1538 /// \brief Create and instantiate a TypeSourceInfo with type source information.
1540 /// \param T QualType referring to the type as written in source code.
1542 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T) {
1543 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
1544 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
1546 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1547 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1548 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1551 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1556 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
1557 QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) {
1558 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1559 // and Sema during declaration parsing. Try deallocating/caching them when
1560 // it's appropriate, instead of allocating them and keeping them around.
1561 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1562 new (LocT) LocInfoType(T, TInfo);
1563 assert(LocT->getTypeClass() != T->getTypeClass() &&
1564 "LocInfoType's TypeClass conflicts with an existing Type class");
1565 return QualType(LocT, 0);
1568 void LocInfoType::getAsStringInternal(std::string &Str,
1569 const PrintingPolicy &Policy) const {
1570 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1571 " was used directly instead of getting the QualType through"
1572 " GetTypeFromParser");
1575 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1576 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1577 /// they point to and return true. If T1 and T2 aren't pointer types
1578 /// or pointer-to-member types, or if they are not similar at this
1579 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1580 /// qualifiers on T1 and T2 are ignored. This function will typically
1581 /// be called in a loop that successively "unwraps" pointer and
1582 /// pointer-to-member types to compare them at each level.
1583 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1584 const PointerType *T1PtrType = T1->getAs<PointerType>(),
1585 *T2PtrType = T2->getAs<PointerType>();
1586 if (T1PtrType && T2PtrType) {
1587 T1 = T1PtrType->getPointeeType();
1588 T2 = T2PtrType->getPointeeType();
1592 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1593 *T2MPType = T2->getAs<MemberPointerType>();
1594 if (T1MPType && T2MPType &&
1595 Context.getCanonicalType(T1MPType->getClass()) ==
1596 Context.getCanonicalType(T2MPType->getClass())) {
1597 T1 = T1MPType->getPointeeType();
1598 T2 = T2MPType->getPointeeType();
1604 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1605 // C99 6.7.6: Type names have no identifier. This is already validated by
1607 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1609 TypeSourceInfo *TInfo = 0;
1610 TagDecl *OwnedTag = 0;
1611 QualType T = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
1612 if (D.isInvalidType())
1615 if (getLangOptions().CPlusPlus) {
1616 // Check that there are no default arguments (C++ only).
1617 CheckExtraCXXDefaultArguments(D);
1619 // C++0x [dcl.type]p3:
1620 // A type-specifier-seq shall not define a class or enumeration
1621 // unless it appears in the type-id of an alias-declaration
1623 if (OwnedTag && OwnedTag->isDefinition())
1624 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1625 << Context.getTypeDeclType(OwnedTag);
1629 T = CreateLocInfoType(T, TInfo);
1631 return T.getAsOpaquePtr();
1636 //===----------------------------------------------------------------------===//
1637 // Type Attribute Processing
1638 //===----------------------------------------------------------------------===//
1640 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1641 /// specified type. The attribute contains 1 argument, the id of the address
1642 /// space for the type.
1643 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1644 const AttributeList &Attr, Sema &S){
1646 // If this type is already address space qualified, reject it.
1647 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1648 // for two or more different address spaces."
1649 if (Type.getAddressSpace()) {
1650 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1654 // Check the attribute arguments.
1655 if (Attr.getNumArgs() != 1) {
1656 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1659 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1660 llvm::APSInt addrSpace(32);
1661 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1662 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1663 << ASArgExpr->getSourceRange();
1668 if (addrSpace.isSigned()) {
1669 if (addrSpace.isNegative()) {
1670 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1671 << ASArgExpr->getSourceRange();
1674 addrSpace.setIsSigned(false);
1676 llvm::APSInt max(addrSpace.getBitWidth());
1677 max = Qualifiers::MaxAddressSpace;
1678 if (addrSpace > max) {
1679 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1680 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1684 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1685 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1688 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1689 /// specified type. The attribute contains 1 argument, weak or strong.
1690 static void HandleObjCGCTypeAttribute(QualType &Type,
1691 const AttributeList &Attr, Sema &S) {
1692 if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1693 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1697 // Check the attribute arguments.
1698 if (!Attr.getParameterName()) {
1699 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1703 Qualifiers::GC GCAttr;
1704 if (Attr.getNumArgs() != 0) {
1705 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1708 if (Attr.getParameterName()->isStr("weak"))
1709 GCAttr = Qualifiers::Weak;
1710 else if (Attr.getParameterName()->isStr("strong"))
1711 GCAttr = Qualifiers::Strong;
1713 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1714 << "objc_gc" << Attr.getParameterName();
1718 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1721 /// Process an individual function attribute. Returns true if the
1722 /// attribute does not make sense to apply to this type.
1723 bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) {
1724 if (Attr.getKind() == AttributeList::AT_noreturn) {
1725 // Complain immediately if the arg count is wrong.
1726 if (Attr.getNumArgs() != 0) {
1727 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1731 // Delay if this is not a function or pointer to block.
1732 if (!Type->isFunctionPointerType()
1733 && !Type->isBlockPointerType()
1734 && !Type->isFunctionType())
1737 // Otherwise we can process right away.
1738 Type = S.Context.getNoReturnType(Type);
1742 if (Attr.getKind() == AttributeList::AT_regparm) {
1743 // The warning is emitted elsewhere
1744 if (Attr.getNumArgs() != 1) {
1748 // Delay if this is not a function or pointer to block.
1749 if (!Type->isFunctionPointerType()
1750 && !Type->isBlockPointerType()
1751 && !Type->isFunctionType())
1754 // Otherwise we can process right away.
1755 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0));
1756 llvm::APSInt NumParams(32);
1758 // The warning is emitted elsewhere
1759 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context))
1762 Type = S.Context.getRegParmType(Type, NumParams.getZExtValue());
1766 // Otherwise, a calling convention.
1767 if (Attr.getNumArgs() != 0) {
1768 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1773 if (const PointerType *PT = Type->getAs<PointerType>())
1774 T = PT->getPointeeType();
1775 const FunctionType *Fn = T->getAs<FunctionType>();
1777 // Delay if the type didn't work out to a function.
1778 if (!Fn) return true;
1780 // TODO: diagnose uses of these conventions on the wrong target.
1782 switch (Attr.getKind()) {
1783 case AttributeList::AT_cdecl: CC = CC_C; break;
1784 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
1785 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
1786 default: llvm_unreachable("unexpected attribute kind"); return false;
1789 CallingConv CCOld = Fn->getCallConv();
1790 if (S.Context.getCanonicalCallConv(CC) ==
1791 S.Context.getCanonicalCallConv(CCOld)) return false;
1793 if (CCOld != CC_Default) {
1794 // Should we diagnose reapplications of the same convention?
1795 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1796 << FunctionType::getNameForCallConv(CC)
1797 << FunctionType::getNameForCallConv(CCOld);
1801 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
1802 if (CC == CC_X86FastCall) {
1803 if (isa<FunctionNoProtoType>(Fn)) {
1804 S.Diag(Attr.getLoc(), diag::err_cconv_knr)
1805 << FunctionType::getNameForCallConv(CC);
1809 const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn);
1810 if (FnP->isVariadic()) {
1811 S.Diag(Attr.getLoc(), diag::err_cconv_varargs)
1812 << FunctionType::getNameForCallConv(CC);
1817 Type = S.Context.getCallConvType(Type, CC);
1821 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
1822 /// and float scalars, although arrays, pointers, and function return values are
1823 /// allowed in conjunction with this construct. Aggregates with this attribute
1824 /// are invalid, even if they are of the same size as a corresponding scalar.
1825 /// The raw attribute should contain precisely 1 argument, the vector size for
1826 /// the variable, measured in bytes. If curType and rawAttr are well formed,
1827 /// this routine will return a new vector type.
1828 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) {
1829 // Check the attribute arugments.
1830 if (Attr.getNumArgs() != 1) {
1831 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1834 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
1835 llvm::APSInt vecSize(32);
1836 if (!sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
1837 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1838 << "vector_size" << sizeExpr->getSourceRange();
1841 // the base type must be integer or float, and can't already be a vector.
1842 if (CurType->isVectorType() ||
1843 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
1844 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
1847 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
1848 // vecSize is specified in bytes - convert to bits.
1849 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1851 // the vector size needs to be an integral multiple of the type size.
1852 if (vectorSize % typeSize) {
1853 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
1854 << sizeExpr->getSourceRange();
1857 if (vectorSize == 0) {
1858 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
1859 << sizeExpr->getSourceRange();
1863 // Success! Instantiate the vector type, the number of elements is > 0, and
1864 // not required to be a power of 2, unlike GCC.
1865 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false);
1868 void ProcessTypeAttributeList(Sema &S, QualType &Result,
1869 bool IsDeclSpec, const AttributeList *AL,
1870 DelayedAttributeSet &FnAttrs) {
1871 // Scan through and apply attributes to this type where it makes sense. Some
1872 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1873 // type, but others can be present in the type specifiers even though they
1874 // apply to the decl. Here we apply type attributes and ignore the rest.
1875 for (; AL; AL = AL->getNext()) {
1876 // If this is an attribute we can handle, do so now, otherwise, add it to
1877 // the LeftOverAttrs list for rechaining.
1878 switch (AL->getKind()) {
1881 case AttributeList::AT_address_space:
1882 HandleAddressSpaceTypeAttribute(Result, *AL, S);
1884 case AttributeList::AT_objc_gc:
1885 HandleObjCGCTypeAttribute(Result, *AL, S);
1887 case AttributeList::AT_vector_size:
1888 HandleVectorSizeAttr(Result, *AL, S);
1891 case AttributeList::AT_noreturn:
1892 case AttributeList::AT_cdecl:
1893 case AttributeList::AT_fastcall:
1894 case AttributeList::AT_stdcall:
1895 case AttributeList::AT_regparm:
1896 // Don't process these on the DeclSpec.
1898 ProcessFnAttr(S, Result, *AL))
1899 FnAttrs.push_back(DelayedAttribute(AL, Result));
1905 /// @brief Ensure that the type T is a complete type.
1907 /// This routine checks whether the type @p T is complete in any
1908 /// context where a complete type is required. If @p T is a complete
1909 /// type, returns false. If @p T is a class template specialization,
1910 /// this routine then attempts to perform class template
1911 /// instantiation. If instantiation fails, or if @p T is incomplete
1912 /// and cannot be completed, issues the diagnostic @p diag (giving it
1913 /// the type @p T) and returns true.
1915 /// @param Loc The location in the source that the incomplete type
1916 /// diagnostic should refer to.
1918 /// @param T The type that this routine is examining for completeness.
1920 /// @param PD The partial diagnostic that will be printed out if T is not a
1923 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1924 /// @c false otherwise.
1925 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1926 const PartialDiagnostic &PD,
1927 std::pair<SourceLocation,
1928 PartialDiagnostic> Note) {
1929 unsigned diag = PD.getDiagID();
1931 // FIXME: Add this assertion to make sure we always get instantiation points.
1932 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
1933 // FIXME: Add this assertion to help us flush out problems with
1934 // checking for dependent types and type-dependent expressions.
1936 // assert(!T->isDependentType() &&
1937 // "Can't ask whether a dependent type is complete");
1939 // If we have a complete type, we're done.
1940 if (!T->isIncompleteType())
1943 // If we have a class template specialization or a class member of a
1944 // class template specialization, or an array with known size of such,
1945 // try to instantiate it.
1946 QualType MaybeTemplate = T;
1947 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
1948 MaybeTemplate = Array->getElementType();
1949 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
1950 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1951 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1952 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
1953 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
1954 TSK_ImplicitInstantiation,
1955 /*Complain=*/diag != 0);
1956 } else if (CXXRecordDecl *Rec
1957 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1958 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1959 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
1960 assert(MSInfo && "Missing member specialization information?");
1961 // This record was instantiated from a class within a template.
1962 if (MSInfo->getTemplateSpecializationKind()
1963 != TSK_ExplicitSpecialization)
1964 return InstantiateClass(Loc, Rec, Pattern,
1965 getTemplateInstantiationArgs(Rec),
1966 TSK_ImplicitInstantiation,
1967 /*Complain=*/diag != 0);
1975 const TagType *Tag = 0;
1976 if (const RecordType *Record = T->getAs<RecordType>())
1978 else if (const EnumType *Enum = T->getAs<EnumType>())
1981 // Avoid diagnosing invalid decls as incomplete.
1982 if (Tag && Tag->getDecl()->isInvalidDecl())
1985 // We have an incomplete type. Produce a diagnostic.
1988 // If we have a note, produce it.
1989 if (!Note.first.isInvalid())
1990 Diag(Note.first, Note.second);
1992 // If the type was a forward declaration of a class/struct/union
1993 // type, produce a note.
1994 if (Tag && !Tag->getDecl()->isInvalidDecl())
1995 Diag(Tag->getDecl()->getLocation(),
1996 Tag->isBeingDefined() ? diag::note_type_being_defined
1997 : diag::note_forward_declaration)
1998 << QualType(Tag, 0);
2003 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2004 const PartialDiagnostic &PD) {
2005 return RequireCompleteType(Loc, T, PD,
2006 std::make_pair(SourceLocation(), PDiag(0)));
2009 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2011 return RequireCompleteType(Loc, T, PDiag(DiagID),
2012 std::make_pair(SourceLocation(), PDiag(0)));
2015 /// \brief Retrieve a version of the type 'T' that is qualified by the
2016 /// nested-name-specifier contained in SS.
2017 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
2018 if (!SS.isSet() || SS.isInvalid() || T.isNull())
2021 NestedNameSpecifier *NNS
2022 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2023 return Context.getQualifiedNameType(NNS, T);
2026 QualType Sema::BuildTypeofExprType(Expr *E) {
2027 if (E->getType() == Context.OverloadTy) {
2028 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2029 // function template specialization wherever deduction cannot occur.
2030 if (FunctionDecl *Specialization
2031 = ResolveSingleFunctionTemplateSpecialization(E)) {
2032 E = FixOverloadedFunctionReference(E, Specialization, Specialization);
2036 Diag(E->getLocStart(),
2037 diag::err_cannot_determine_declared_type_of_overloaded_function)
2038 << false << E->getSourceRange();
2043 return Context.getTypeOfExprType(E);
2046 QualType Sema::BuildDecltypeType(Expr *E) {
2047 if (E->getType() == Context.OverloadTy) {
2048 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2049 // function template specialization wherever deduction cannot occur.
2050 if (FunctionDecl *Specialization
2051 = ResolveSingleFunctionTemplateSpecialization(E)) {
2052 E = FixOverloadedFunctionReference(E, Specialization, Specialization);
2056 Diag(E->getLocStart(),
2057 diag::err_cannot_determine_declared_type_of_overloaded_function)
2058 << true << E->getSourceRange();
2063 return Context.getDecltypeType(E);