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;
30 /// \brief Perform adjustment on the parameter type of a function.
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.
35 QualType Sema::adjustParameterType(QualType T) {
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.
42 return Context.getArrayDecayedType(T);
45 // A declaration of a parameter as "function returning type"
46 // shall be adjusted to "pointer to function returning type", as
48 if (T->isFunctionType())
49 return Context.getPointerType(T);
56 /// isOmittedBlockReturnType - Return true if this declarator is missing a
57 /// return type because this is a omitted return type on a block literal.
58 static bool isOmittedBlockReturnType(const Declarator &D) {
59 if (D.getContext() != Declarator::BlockLiteralContext ||
60 D.getDeclSpec().hasTypeSpecifier())
63 if (D.getNumTypeObjects() == 0)
64 return true; // ^{ ... }
66 if (D.getNumTypeObjects() == 1 &&
67 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
68 return true; // ^(int X, float Y) { ... }
73 typedef std::pair<const AttributeList*,QualType> DelayedAttribute;
74 typedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet;
76 static void ProcessTypeAttributeList(Sema &S, QualType &Type,
78 const AttributeList *Attrs,
79 DelayedAttributeSet &DelayedFnAttrs);
80 static bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr);
82 static 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();
95 static 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();
106 /// \brief Convert the specified declspec to the appropriate type
108 /// \param D the declarator containing the declaration specifier.
109 /// \returns The type described by the declaration specifiers. This function
110 /// never returns null.
111 static QualType ConvertDeclSpecToType(Sema &TheSema,
112 Declarator &TheDeclarator,
113 DelayedAttributeSet &Delayed) {
114 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
116 const DeclSpec &DS = TheDeclarator.getDeclSpec();
117 SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
118 if (DeclLoc.isInvalid())
119 DeclLoc = DS.getSourceRange().getBegin();
121 ASTContext &Context = TheSema.Context;
124 switch (DS.getTypeSpecType()) {
125 case DeclSpec::TST_void:
126 Result = Context.VoidTy;
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;
134 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
135 "Unknown TSS value");
136 Result = Context.UnsignedCharTy;
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();
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();
154 case DeclSpec::TST_char16:
155 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
156 "Unknown TSS value");
157 Result = Context.Char16Ty;
159 case DeclSpec::TST_char32:
160 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
161 "Unknown TSS value");
162 Result = Context.Char32Ty;
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);
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;
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
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.
192 TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
193 << DS.getSourceRange()
194 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
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();
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
210 TheDeclarator.setInvalidType(true);
212 TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
213 << DS.getSourceRange();
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;
227 // long long is a C99 feature.
228 if (!TheSema.getLangOptions().C99 &&
229 !TheSema.getLangOptions().CPlusPlus0x)
230 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
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;
241 // long long is a C99 feature.
242 if (!TheSema.getLangOptions().C99 &&
243 !TheSema.getLangOptions().CPlusPlus0x)
244 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
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;
255 Result = Context.DoubleTy;
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);
265 case DeclSpec::TST_class:
266 case DeclSpec::TST_enum:
267 case DeclSpec::TST_union:
268 case DeclSpec::TST_struct: {
270 = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
272 // This can happen in C++ with ambiguous lookups.
273 Result = Context.IntTy;
274 TheDeclarator.setInvalidType(true);
278 // If the type is deprecated or unavailable, diagnose it.
279 TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
281 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
282 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
284 // TypeQuals handled by caller.
285 Result = Context.getTypeDeclType(D);
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(),
294 if (D->isInvalidDecl())
295 TheDeclarator.setInvalidType(true);
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());
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();
311 if (DS.getNumProtocolQualifiers())
312 Result = Context.getObjCObjectType(Result,
313 (ObjCProtocolDecl**) PQ,
314 DS.getNumProtocolQualifiers());
315 } else if (Result->isObjCIdType()) {
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);
328 TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
329 << DS.getSourceRange();
330 TheDeclarator.setInvalidType(true);
334 // TypeQuals handled by caller.
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);
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);
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);
366 case DeclSpec::TST_auto: {
367 // TypeQuals handled by caller.
368 Result = Context.UndeducedAutoTy;
372 case DeclSpec::TST_error:
373 Result = Context.IntTy;
374 TheDeclarator.setInvalidType(true);
378 // Handle complex types.
379 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
380 if (TheSema.getLangOptions().Freestanding)
381 TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
382 Result = Context.getComplexType(Result);
383 } else if (DS.isTypeAltiVecVector()) {
384 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
385 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
386 Result = Context.getVectorType(Result, 128/typeSize, true,
387 DS.isTypeAltiVecPixel());
390 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
391 "FIXME: imaginary types not supported yet!");
393 // See if there are any attributes on the declspec that apply to the type (as
394 // opposed to the decl).
395 if (const AttributeList *AL = DS.getAttributes())
396 ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed);
398 // Apply const/volatile/restrict qualifiers to T.
399 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
401 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
402 // or incomplete types shall not be restrict-qualified." C++ also allows
403 // restrict-qualified references.
404 if (TypeQuals & DeclSpec::TQ_restrict) {
405 if (Result->isAnyPointerType() || Result->isReferenceType()) {
407 if (Result->isObjCObjectPointerType())
410 EltTy = Result->isPointerType() ?
411 Result->getAs<PointerType>()->getPointeeType() :
412 Result->getAs<ReferenceType>()->getPointeeType();
414 // If we have a pointer or reference, the pointee must have an object
416 if (!EltTy->isIncompleteOrObjectType()) {
417 TheSema.Diag(DS.getRestrictSpecLoc(),
418 diag::err_typecheck_invalid_restrict_invalid_pointee)
419 << EltTy << DS.getSourceRange();
420 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
423 TheSema.Diag(DS.getRestrictSpecLoc(),
424 diag::err_typecheck_invalid_restrict_not_pointer)
425 << Result << DS.getSourceRange();
426 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
430 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
431 // of a function type includes any type qualifiers, the behavior is
433 if (Result->isFunctionType() && TypeQuals) {
434 // Get some location to point at, either the C or V location.
436 if (TypeQuals & DeclSpec::TQ_const)
437 Loc = DS.getConstSpecLoc();
438 else if (TypeQuals & DeclSpec::TQ_volatile)
439 Loc = DS.getVolatileSpecLoc();
441 assert((TypeQuals & DeclSpec::TQ_restrict) &&
442 "Has CVR quals but not C, V, or R?");
443 Loc = DS.getRestrictSpecLoc();
445 TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
446 << Result << DS.getSourceRange();
450 // Cv-qualified references are ill-formed except when the
451 // cv-qualifiers are introduced through the use of a typedef
452 // (7.1.3) or of a template type argument (14.3), in which
453 // case the cv-qualifiers are ignored.
454 // FIXME: Shouldn't we be checking SCS_typedef here?
455 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
456 TypeQuals && Result->isReferenceType()) {
457 TypeQuals &= ~DeclSpec::TQ_const;
458 TypeQuals &= ~DeclSpec::TQ_volatile;
461 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
462 Result = Context.getQualifiedType(Result, Quals);
468 static std::string getPrintableNameForEntity(DeclarationName Entity) {
470 return Entity.getAsString();
475 /// \brief Build a pointer type.
477 /// \param T The type to which we'll be building a pointer.
479 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
481 /// \param Loc The location of the entity whose type involves this
482 /// pointer type or, if there is no such entity, the location of the
483 /// type that will have pointer type.
485 /// \param Entity The name of the entity that involves the pointer
488 /// \returns A suitable pointer type, if there are no
489 /// errors. Otherwise, returns a NULL type.
490 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
491 SourceLocation Loc, DeclarationName Entity) {
492 if (T->isReferenceType()) {
493 // C++ 8.3.2p4: There shall be no ... pointers to references ...
494 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
495 << getPrintableNameForEntity(Entity) << T;
499 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
501 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
502 // object or incomplete types shall not be restrict-qualified."
503 if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
504 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
509 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
511 // Build the pointer type.
512 return Context.getQualifiedType(Context.getPointerType(T), Qs);
515 /// \brief Build a reference type.
517 /// \param T The type to which we'll be building a reference.
519 /// \param CVR The cvr-qualifiers to be applied to the reference type.
521 /// \param Loc The location of the entity whose type involves this
522 /// reference type or, if there is no such entity, the location of the
523 /// type that will have reference type.
525 /// \param Entity The name of the entity that involves the reference
528 /// \returns A suitable reference type, if there are no
529 /// errors. Otherwise, returns a NULL type.
530 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
531 unsigned CVR, SourceLocation Loc,
532 DeclarationName Entity) {
533 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
535 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
537 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
538 // reference to a type T, and attempt to create the type "lvalue
539 // reference to cv TD" creates the type "lvalue reference to T".
540 // We use the qualifiers (restrict or none) of the original reference,
541 // not the new ones. This is consistent with GCC.
543 // C++ [dcl.ref]p4: There shall be no references to references.
545 // According to C++ DR 106, references to references are only
546 // diagnosed when they are written directly (e.g., "int & &"),
547 // but not when they happen via a typedef:
549 // typedef int& intref;
550 // typedef intref& intref2;
552 // Parser::ParseDeclaratorInternal diagnoses the case where
553 // references are written directly; here, we handle the
554 // collapsing of references-to-references as described in C++
555 // DR 106 and amended by C++ DR 540.
558 // A declarator that specifies the type "reference to cv void"
560 if (T->isVoidType()) {
561 Diag(Loc, diag::err_reference_to_void);
565 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
566 // object or incomplete types shall not be restrict-qualified."
567 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
568 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
570 Quals.removeRestrict();
574 // [...] Cv-qualified references are ill-formed except when the
575 // cv-qualifiers are introduced through the use of a typedef
576 // (7.1.3) or of a template type argument (14.3), in which case
577 // the cv-qualifiers are ignored.
579 // We diagnose extraneous cv-qualifiers for the non-typedef,
580 // non-template type argument case within the parser. Here, we just
581 // ignore any extraneous cv-qualifiers.
583 Quals.removeVolatile();
585 // Handle restrict on references.
587 return Context.getQualifiedType(
588 Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
589 return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
592 /// \brief Build an array type.
594 /// \param T The type of each element in the array.
596 /// \param ASM C99 array size modifier (e.g., '*', 'static').
598 /// \param ArraySize Expression describing the size of the array.
600 /// \param Quals The cvr-qualifiers to be applied to the array's
603 /// \param Loc The location of the entity whose type involves this
604 /// array type or, if there is no such entity, the location of the
605 /// type that will have array type.
607 /// \param Entity The name of the entity that involves the array
610 /// \returns A suitable array type, if there are no errors. Otherwise,
611 /// returns a NULL type.
612 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
613 Expr *ArraySize, unsigned Quals,
614 SourceRange Brackets, DeclarationName Entity) {
616 SourceLocation Loc = Brackets.getBegin();
617 if (getLangOptions().CPlusPlus) {
618 // C++ [dcl.array]p1:
619 // T is called the array element type; this type shall not be a reference
620 // type, the (possibly cv-qualified) type void, a function type or an
621 // abstract class type.
623 // Note: function types are handled in the common path with C.
624 if (T->isReferenceType()) {
625 Diag(Loc, diag::err_illegal_decl_array_of_references)
626 << getPrintableNameForEntity(Entity) << T;
630 if (T->isVoidType()) {
631 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
635 if (RequireNonAbstractType(Brackets.getBegin(), T,
636 diag::err_array_of_abstract_type))
640 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
641 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
642 if (RequireCompleteType(Loc, T,
643 diag::err_illegal_decl_array_incomplete_type))
647 if (T->isFunctionType()) {
648 Diag(Loc, diag::err_illegal_decl_array_of_functions)
649 << getPrintableNameForEntity(Entity) << T;
653 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
654 Diag(Loc, diag::err_illegal_decl_array_of_auto)
655 << getPrintableNameForEntity(Entity);
659 if (const RecordType *EltTy = T->getAs<RecordType>()) {
660 // If the element type is a struct or union that contains a variadic
661 // array, accept it as a GNU extension: C99 6.7.2.1p2.
662 if (EltTy->getDecl()->hasFlexibleArrayMember())
663 Diag(Loc, diag::ext_flexible_array_in_array) << T;
664 } else if (T->isObjCObjectType()) {
665 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
669 // C99 6.7.5.2p1: The size expression shall have integer type.
670 if (ArraySize && !ArraySize->isTypeDependent() &&
671 !ArraySize->getType()->isIntegerType()) {
672 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
673 << ArraySize->getType() << ArraySize->getSourceRange();
674 ArraySize->Destroy(Context);
677 llvm::APSInt ConstVal(32);
679 if (ASM == ArrayType::Star)
680 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
682 T = Context.getIncompleteArrayType(T, ASM, Quals);
683 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
684 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
685 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
686 (!T->isDependentType() && !T->isIncompleteType() &&
687 !T->isConstantSizeType())) {
688 // Per C99, a variable array is an array with either a non-constant
689 // size or an element type that has a non-constant-size
690 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
692 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
693 // have a value greater than zero.
694 if (ConstVal.isSigned() && ConstVal.isNegative()) {
695 Diag(ArraySize->getLocStart(),
696 diag::err_typecheck_negative_array_size)
697 << ArraySize->getSourceRange();
701 // GCC accepts zero sized static arrays. We allow them when
702 // we're not in a SFINAE context.
703 Diag(ArraySize->getLocStart(),
704 isSFINAEContext()? diag::err_typecheck_zero_array_size
705 : diag::ext_typecheck_zero_array_size)
706 << ArraySize->getSourceRange();
708 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
710 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
711 if (!getLangOptions().C99) {
712 if (T->isVariableArrayType()) {
713 // Prohibit the use of non-POD types in VLAs.
714 if (!T->isDependentType() &&
715 !Context.getBaseElementType(T)->isPODType()) {
716 Diag(Loc, diag::err_vla_non_pod)
717 << Context.getBaseElementType(T);
720 // Prohibit the use of VLAs during template argument deduction.
721 else if (isSFINAEContext()) {
722 Diag(Loc, diag::err_vla_in_sfinae);
725 // Just extwarn about VLAs.
727 Diag(Loc, diag::ext_vla);
728 } else if (ASM != ArrayType::Normal || Quals != 0)
730 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
731 : diag::ext_c99_array_usage);
737 /// \brief Build an ext-vector type.
739 /// Run the required checks for the extended vector type.
740 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
741 SourceLocation AttrLoc) {
743 Expr *Arg = (Expr *)ArraySize.get();
745 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
746 // in conjunction with complex types (pointers, arrays, functions, etc.).
747 if (!T->isDependentType() &&
748 !T->isIntegerType() && !T->isRealFloatingType()) {
749 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
753 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
754 llvm::APSInt vecSize(32);
755 if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
756 Diag(AttrLoc, diag::err_attribute_argument_not_int)
757 << "ext_vector_type" << Arg->getSourceRange();
761 // unlike gcc's vector_size attribute, the size is specified as the
762 // number of elements, not the number of bytes.
763 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
765 if (vectorSize == 0) {
766 Diag(AttrLoc, diag::err_attribute_zero_size)
767 << Arg->getSourceRange();
771 if (!T->isDependentType())
772 return Context.getExtVectorType(T, vectorSize);
775 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
779 /// \brief Build a function type.
781 /// This routine checks the function type according to C++ rules and
782 /// under the assumption that the result type and parameter types have
783 /// just been instantiated from a template. It therefore duplicates
784 /// some of the behavior of GetTypeForDeclarator, but in a much
785 /// simpler form that is only suitable for this narrow use case.
787 /// \param T The return type of the function.
789 /// \param ParamTypes The parameter types of the function. This array
790 /// will be modified to account for adjustments to the types of the
791 /// function parameters.
793 /// \param NumParamTypes The number of parameter types in ParamTypes.
795 /// \param Variadic Whether this is a variadic function type.
797 /// \param Quals The cvr-qualifiers to be applied to the function type.
799 /// \param Loc The location of the entity whose type involves this
800 /// function type or, if there is no such entity, the location of the
801 /// type that will have function type.
803 /// \param Entity The name of the entity that involves the function
806 /// \returns A suitable function type, if there are no
807 /// errors. Otherwise, returns a NULL type.
808 QualType Sema::BuildFunctionType(QualType T,
809 QualType *ParamTypes,
810 unsigned NumParamTypes,
811 bool Variadic, unsigned Quals,
812 SourceLocation Loc, DeclarationName Entity) {
813 if (T->isArrayType() || T->isFunctionType()) {
814 Diag(Loc, diag::err_func_returning_array_function)
815 << T->isFunctionType() << T;
819 bool Invalid = false;
820 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
821 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
822 if (ParamType->isVoidType()) {
823 Diag(Loc, diag::err_param_with_void_type);
827 ParamTypes[Idx] = ParamType;
833 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
834 Quals, false, false, 0, 0,
835 FunctionType::ExtInfo());
838 /// \brief Build a member pointer type \c T Class::*.
840 /// \param T the type to which the member pointer refers.
841 /// \param Class the class type into which the member pointer points.
842 /// \param CVR Qualifiers applied to the member pointer type
843 /// \param Loc the location where this type begins
844 /// \param Entity the name of the entity that will have this member pointer type
846 /// \returns a member pointer type, if successful, or a NULL type if there was
848 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
849 unsigned CVR, SourceLocation Loc,
850 DeclarationName Entity) {
851 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
853 // Verify that we're not building a pointer to pointer to function with
854 // exception specification.
855 if (CheckDistantExceptionSpec(T)) {
856 Diag(Loc, diag::err_distant_exception_spec);
858 // FIXME: If we're doing this as part of template instantiation,
859 // we should return immediately.
861 // Build the type anyway, but use the canonical type so that the
862 // exception specifiers are stripped off.
863 T = Context.getCanonicalType(T);
866 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
867 // with reference type, or "cv void."
868 if (T->isReferenceType()) {
869 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
870 << (Entity? Entity.getAsString() : "type name") << T;
874 if (T->isVoidType()) {
875 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
876 << (Entity? Entity.getAsString() : "type name");
880 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
881 // object or incomplete types shall not be restrict-qualified."
882 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
883 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
886 // FIXME: If we're doing this as part of template instantiation,
887 // we should return immediately.
888 Quals.removeRestrict();
891 if (!Class->isDependentType() && !Class->isRecordType()) {
892 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
896 return Context.getQualifiedType(
897 Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
900 /// \brief Build a block pointer type.
902 /// \param T The type to which we'll be building a block pointer.
904 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
906 /// \param Loc The location of the entity whose type involves this
907 /// block pointer type or, if there is no such entity, the location of the
908 /// type that will have block pointer type.
910 /// \param Entity The name of the entity that involves the block pointer
913 /// \returns A suitable block pointer type, if there are no
914 /// errors. Otherwise, returns a NULL type.
915 QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
917 DeclarationName Entity) {
918 if (!T->isFunctionType()) {
919 Diag(Loc, diag::err_nonfunction_block_type);
923 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
924 return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
927 QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) {
928 QualType QT = QualType::getFromOpaquePtr(Ty);
930 if (TInfo) *TInfo = 0;
934 TypeSourceInfo *DI = 0;
935 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
937 DI = LIT->getTypeSourceInfo();
940 if (TInfo) *TInfo = DI;
944 /// GetTypeForDeclarator - Convert the type for the specified
945 /// declarator to Type instances.
947 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
948 /// owns the declaration of a type (e.g., the definition of a struct
949 /// type), then *OwnedDecl will receive the owned declaration.
950 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
951 TypeSourceInfo **TInfo,
952 TagDecl **OwnedDecl) {
953 // Determine the type of the declarator. Not all forms of declarator
956 TypeSourceInfo *ReturnTypeInfo = 0;
958 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec;
960 switch (D.getName().getKind()) {
961 case UnqualifiedId::IK_Identifier:
962 case UnqualifiedId::IK_OperatorFunctionId:
963 case UnqualifiedId::IK_LiteralOperatorId:
964 case UnqualifiedId::IK_TemplateId:
965 T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec);
967 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
968 TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
969 // Owned is embedded if it was defined here, or if it is the
970 // very first (i.e., canonical) declaration of this tag type.
971 Owned->setEmbeddedInDeclarator(Owned->isDefinition() ||
972 Owned->isCanonicalDecl());
973 if (OwnedDecl) *OwnedDecl = Owned;
977 case UnqualifiedId::IK_ConstructorName:
978 case UnqualifiedId::IK_ConstructorTemplateId:
979 case UnqualifiedId::IK_DestructorName:
980 // Constructors and destructors don't have return types. Use
985 ReturnTypeInfo = Context.getTrivialTypeSourceInfo(T,
986 D.getName().StartLocation);
989 case UnqualifiedId::IK_ConversionFunctionId:
990 // The result type of a conversion function is the type that it
992 T = GetTypeFromParser(D.getName().ConversionFunctionId,
993 TInfo? &ReturnTypeInfo : 0);
1000 if (T == Context.UndeducedAutoTy) {
1003 switch (D.getContext()) {
1004 case Declarator::KNRTypeListContext:
1005 assert(0 && "K&R type lists aren't allowed in C++");
1007 case Declarator::PrototypeContext:
1008 Error = 0; // Function prototype
1010 case Declarator::MemberContext:
1011 switch (cast<TagDecl>(CurContext)->getTagKind()) {
1012 case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1013 case TTK_Struct: Error = 1; /* Struct member */ break;
1014 case TTK_Union: Error = 2; /* Union member */ break;
1015 case TTK_Class: Error = 3; /* Class member */ break;
1018 case Declarator::CXXCatchContext:
1019 Error = 4; // Exception declaration
1021 case Declarator::TemplateParamContext:
1022 Error = 5; // Template parameter
1024 case Declarator::BlockLiteralContext:
1025 Error = 6; // Block literal
1027 case Declarator::FileContext:
1028 case Declarator::BlockContext:
1029 case Declarator::ForContext:
1030 case Declarator::ConditionContext:
1031 case Declarator::TypeNameContext:
1036 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1039 D.setInvalidType(true);
1043 // The name we're declaring, if any.
1044 DeclarationName Name;
1045 if (D.getIdentifier())
1046 Name = D.getIdentifier();
1048 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk;
1050 // Walk the DeclTypeInfo, building the recursive type as we go.
1051 // DeclTypeInfos are ordered from the identifier out, which is
1052 // opposite of what we want :).
1053 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1054 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
1055 switch (DeclType.Kind) {
1056 default: assert(0 && "Unknown decltype!");
1057 case DeclaratorChunk::BlockPointer:
1058 // If blocks are disabled, emit an error.
1059 if (!LangOpts.Blocks)
1060 Diag(DeclType.Loc, diag::err_blocks_disable);
1062 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
1065 case DeclaratorChunk::Pointer:
1066 // Verify that we're not building a pointer to pointer to function with
1067 // exception specification.
1068 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1069 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1070 D.setInvalidType(true);
1071 // Build the type anyway.
1073 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1074 T = Context.getObjCObjectPointerType(T);
1075 T = Context.getCVRQualifiedType(T, DeclType.Ptr.TypeQuals);
1078 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
1080 case DeclaratorChunk::Reference: {
1082 if (DeclType.Ref.HasRestrict) Quals.addRestrict();
1084 // Verify that we're not building a reference to pointer to function with
1085 // exception specification.
1086 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1087 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1088 D.setInvalidType(true);
1089 // Build the type anyway.
1091 T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
1092 DeclType.Loc, Name);
1095 case DeclaratorChunk::Array: {
1096 // Verify that we're not building an array of pointers to function with
1097 // exception specification.
1098 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1099 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1100 D.setInvalidType(true);
1101 // Build the type anyway.
1103 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1104 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1105 ArrayType::ArraySizeModifier ASM;
1107 ASM = ArrayType::Star;
1108 else if (ATI.hasStatic)
1109 ASM = ArrayType::Static;
1111 ASM = ArrayType::Normal;
1112 if (ASM == ArrayType::Star &&
1113 D.getContext() != Declarator::PrototypeContext) {
1114 // FIXME: This check isn't quite right: it allows star in prototypes
1115 // for function definitions, and disallows some edge cases detailed
1116 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1117 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1118 ASM = ArrayType::Normal;
1119 D.setInvalidType(true);
1121 T = BuildArrayType(T, ASM, ArraySize,
1122 Qualifiers::fromCVRMask(ATI.TypeQuals),
1123 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1126 case DeclaratorChunk::Function: {
1127 // If the function declarator has a prototype (i.e. it is not () and
1128 // does not have a K&R-style identifier list), then the arguments are part
1129 // of the type, otherwise the argument list is ().
1130 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1132 // C99 6.7.5.3p1: The return type may not be a function or array type.
1133 // For conversion functions, we'll diagnose this particular error later.
1134 if ((T->isArrayType() || T->isFunctionType()) &&
1135 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1136 Diag(DeclType.Loc, diag::err_func_returning_array_function)
1137 << T->isFunctionType() << T;
1139 D.setInvalidType(true);
1142 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1144 // Types shall not be defined in return or parameter types.
1145 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1146 if (Tag->isDefinition())
1147 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1148 << Context.getTypeDeclType(Tag);
1151 // Exception specs are not allowed in typedefs. Complain, but add it
1153 if (FTI.hasExceptionSpec &&
1154 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1155 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1157 if (FTI.NumArgs == 0) {
1158 if (getLangOptions().CPlusPlus) {
1159 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1160 // function takes no arguments.
1161 llvm::SmallVector<QualType, 4> Exceptions;
1162 Exceptions.reserve(FTI.NumExceptions);
1163 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1164 // FIXME: Preserve type source info.
1165 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1166 // Check that the type is valid for an exception spec, and drop it
1168 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1169 Exceptions.push_back(ET);
1171 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1172 FTI.hasExceptionSpec,
1173 FTI.hasAnyExceptionSpec,
1174 Exceptions.size(), Exceptions.data(),
1175 FunctionType::ExtInfo());
1176 } else if (FTI.isVariadic) {
1177 // We allow a zero-parameter variadic function in C if the
1178 // function is marked with the "overloadable"
1179 // attribute. Scan for this attribute now.
1180 bool Overloadable = false;
1181 for (const AttributeList *Attrs = D.getAttributes();
1182 Attrs; Attrs = Attrs->getNext()) {
1183 if (Attrs->getKind() == AttributeList::AT_overloadable) {
1184 Overloadable = true;
1190 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1191 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0,
1193 FunctionType::ExtInfo());
1195 // Simple void foo(), where the incoming T is the result type.
1196 T = Context.getFunctionNoProtoType(T);
1198 } else if (FTI.ArgInfo[0].Param == 0) {
1199 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1200 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1201 D.setInvalidType(true);
1203 // Otherwise, we have a function with an argument list that is
1204 // potentially variadic.
1205 llvm::SmallVector<QualType, 16> ArgTys;
1207 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1208 ParmVarDecl *Param =
1209 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1210 QualType ArgTy = Param->getType();
1211 assert(!ArgTy.isNull() && "Couldn't parse type?");
1213 // Adjust the parameter type.
1214 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1216 // Look for 'void'. void is allowed only as a single argument to a
1217 // function with no other parameters (C99 6.7.5.3p10). We record
1218 // int(void) as a FunctionProtoType with an empty argument list.
1219 if (ArgTy->isVoidType()) {
1220 // If this is something like 'float(int, void)', reject it. 'void'
1221 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1222 // have arguments of incomplete type.
1223 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1224 Diag(DeclType.Loc, diag::err_void_only_param);
1225 ArgTy = Context.IntTy;
1226 Param->setType(ArgTy);
1227 } else if (FTI.ArgInfo[i].Ident) {
1228 // Reject, but continue to parse 'int(void abc)'.
1229 Diag(FTI.ArgInfo[i].IdentLoc,
1230 diag::err_param_with_void_type);
1231 ArgTy = Context.IntTy;
1232 Param->setType(ArgTy);
1234 // Reject, but continue to parse 'float(const void)'.
1235 if (ArgTy.hasQualifiers())
1236 Diag(DeclType.Loc, diag::err_void_param_qualified);
1238 // Do not add 'void' to the ArgTys list.
1241 } else if (!FTI.hasPrototype) {
1242 if (ArgTy->isPromotableIntegerType()) {
1243 ArgTy = Context.getPromotedIntegerType(ArgTy);
1244 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1245 if (BTy->getKind() == BuiltinType::Float)
1246 ArgTy = Context.DoubleTy;
1250 ArgTys.push_back(ArgTy);
1253 llvm::SmallVector<QualType, 4> Exceptions;
1254 Exceptions.reserve(FTI.NumExceptions);
1255 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1256 // FIXME: Preserve type source info.
1257 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1258 // Check that the type is valid for an exception spec, and drop it if
1260 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1261 Exceptions.push_back(ET);
1264 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1265 FTI.isVariadic, FTI.TypeQuals,
1266 FTI.hasExceptionSpec,
1267 FTI.hasAnyExceptionSpec,
1268 Exceptions.size(), Exceptions.data(),
1269 FunctionType::ExtInfo());
1272 // For GCC compatibility, we allow attributes that apply only to
1273 // function types to be placed on a function's return type
1274 // instead (as long as that type doesn't happen to be function
1275 // or function-pointer itself).
1276 ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk);
1280 case DeclaratorChunk::MemberPointer:
1281 // Verify that we're not building a pointer to pointer to function with
1282 // exception specification.
1283 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1284 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1285 D.setInvalidType(true);
1286 // Build the type anyway.
1288 // The scope spec must refer to a class, or be dependent.
1290 if (DeclType.Mem.Scope().isInvalid()) {
1291 // Avoid emitting extra errors if we already errored on the scope.
1292 D.setInvalidType(true);
1293 } else if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1294 || dyn_cast_or_null<CXXRecordDecl>(
1295 computeDeclContext(DeclType.Mem.Scope()))) {
1296 NestedNameSpecifier *NNS
1297 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1298 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1299 switch (NNS->getKind()) {
1300 case NestedNameSpecifier::Identifier:
1301 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
1302 NNS->getAsIdentifier());
1305 case NestedNameSpecifier::Namespace:
1306 case NestedNameSpecifier::Global:
1307 llvm_unreachable("Nested-name-specifier must name a type");
1310 case NestedNameSpecifier::TypeSpec:
1311 case NestedNameSpecifier::TypeSpecWithTemplate:
1312 ClsType = QualType(NNS->getAsType(), 0);
1314 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
1318 Diag(DeclType.Mem.Scope().getBeginLoc(),
1319 diag::err_illegal_decl_mempointer_in_nonclass)
1320 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1321 << DeclType.Mem.Scope().getRange();
1322 D.setInvalidType(true);
1325 if (!ClsType.isNull())
1326 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1327 DeclType.Loc, D.getIdentifier());
1330 D.setInvalidType(true);
1336 D.setInvalidType(true);
1340 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1342 // See if there are any attributes on this declarator chunk.
1343 if (const AttributeList *AL = DeclType.getAttrs())
1344 ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk);
1347 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1348 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1349 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1351 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1352 // for a nonstatic member function, the function type to which a pointer
1353 // to member refers, or the top-level function type of a function typedef
1355 if (FnTy->getTypeQuals() != 0 &&
1356 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1357 ((D.getContext() != Declarator::MemberContext &&
1358 (!D.getCXXScopeSpec().isSet() ||
1359 !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1361 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1362 if (D.isFunctionDeclarator())
1363 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1365 Diag(D.getIdentifierLoc(),
1366 diag::err_invalid_qualified_typedef_function_type_use);
1368 // Strip the cv-quals from the type.
1369 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1370 FnTy->getNumArgs(), FnTy->isVariadic(), 0,
1371 false, false, 0, 0, FunctionType::ExtInfo());
1375 // Process any function attributes we might have delayed from the
1376 // declaration-specifiers.
1377 ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec);
1379 // If there were any type attributes applied to the decl itself, not
1380 // the type, apply them to the result type. But don't do this for
1381 // block-literal expressions, which are parsed wierdly.
1382 if (D.getContext() != Declarator::BlockLiteralContext)
1383 if (const AttributeList *Attrs = D.getAttributes())
1384 ProcessTypeAttributeList(*this, T, false, Attrs,
1385 FnAttrsFromPreviousChunk);
1387 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1390 if (D.isInvalidType())
1393 *TInfo = GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
1400 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1404 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1406 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1407 Visit(TL.getUnqualifiedLoc());
1409 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1410 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1412 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1413 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1415 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1416 // Handle the base type, which might not have been written explicitly.
1417 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1418 TL.setHasBaseTypeAsWritten(false);
1419 TL.getBaseLoc().initialize(SourceLocation());
1421 TL.setHasBaseTypeAsWritten(true);
1422 Visit(TL.getBaseLoc());
1425 // Protocol qualifiers.
1426 if (DS.getProtocolQualifiers()) {
1427 assert(TL.getNumProtocols() > 0);
1428 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1429 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1430 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1431 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1432 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1434 assert(TL.getNumProtocols() == 0);
1435 TL.setLAngleLoc(SourceLocation());
1436 TL.setRAngleLoc(SourceLocation());
1439 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1440 TL.setStarLoc(SourceLocation());
1441 Visit(TL.getPointeeLoc());
1443 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1444 TypeSourceInfo *TInfo = 0;
1445 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1447 // If we got no declarator info from previous Sema routines,
1448 // just fill with the typespec loc.
1450 TL.initialize(DS.getTypeSpecTypeLoc());
1454 TypeLoc OldTL = TInfo->getTypeLoc();
1455 if (TInfo->getType()->getAs<ElaboratedType>()) {
1456 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
1457 TemplateSpecializationTypeLoc NamedTL =
1458 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
1462 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
1464 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1465 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
1466 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1467 TL.setParensRange(DS.getTypeofParensRange());
1469 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1470 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
1471 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1472 TL.setParensRange(DS.getTypeofParensRange());
1473 assert(DS.getTypeRep());
1474 TypeSourceInfo *TInfo = 0;
1475 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1476 TL.setUnderlyingTInfo(TInfo);
1478 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1479 // By default, use the source location of the type specifier.
1480 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
1481 if (TL.needsExtraLocalData()) {
1482 // Set info for the written builtin specifiers.
1483 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
1484 // Try to have a meaningful source location.
1485 if (TL.getWrittenSignSpec() != TSS_unspecified)
1486 // Sign spec loc overrides the others (e.g., 'unsigned long').
1487 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
1488 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
1489 // Width spec loc overrides type spec loc (e.g., 'short int').
1490 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
1493 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1494 ElaboratedTypeKeyword Keyword
1495 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
1496 if (Keyword == ETK_Typename) {
1497 TypeSourceInfo *TInfo = 0;
1498 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1500 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
1504 TL.setKeywordLoc(Keyword != ETK_None
1505 ? DS.getTypeSpecTypeLoc()
1506 : SourceLocation());
1507 const CXXScopeSpec& SS = DS.getTypeSpecScope();
1508 TL.setQualifierRange(SS.isEmpty() ? SourceRange(): SS.getRange());
1509 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
1511 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1512 ElaboratedTypeKeyword Keyword
1513 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
1514 if (Keyword == ETK_Typename) {
1515 TypeSourceInfo *TInfo = 0;
1516 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1518 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
1522 TL.setKeywordLoc(Keyword != ETK_None
1523 ? DS.getTypeSpecTypeLoc()
1524 : SourceLocation());
1525 const CXXScopeSpec& SS = DS.getTypeSpecScope();
1526 TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange());
1527 // FIXME: load appropriate source location.
1528 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1531 void VisitTypeLoc(TypeLoc TL) {
1532 // FIXME: add other typespec types and change this to an assert.
1533 TL.initialize(DS.getTypeSpecTypeLoc());
1537 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1538 const DeclaratorChunk &Chunk;
1541 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1543 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1544 llvm_unreachable("qualified type locs not expected here!");
1547 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1548 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1549 TL.setCaretLoc(Chunk.Loc);
1551 void VisitPointerTypeLoc(PointerTypeLoc TL) {
1552 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1553 TL.setStarLoc(Chunk.Loc);
1555 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1556 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1557 TL.setStarLoc(Chunk.Loc);
1559 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1560 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1561 TL.setStarLoc(Chunk.Loc);
1562 // FIXME: nested name specifier
1564 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1565 assert(Chunk.Kind == DeclaratorChunk::Reference);
1566 // 'Amp' is misleading: this might have been originally
1567 /// spelled with AmpAmp.
1568 TL.setAmpLoc(Chunk.Loc);
1570 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1571 assert(Chunk.Kind == DeclaratorChunk::Reference);
1572 assert(!Chunk.Ref.LValueRef);
1573 TL.setAmpAmpLoc(Chunk.Loc);
1575 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1576 assert(Chunk.Kind == DeclaratorChunk::Array);
1577 TL.setLBracketLoc(Chunk.Loc);
1578 TL.setRBracketLoc(Chunk.EndLoc);
1579 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1581 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1582 assert(Chunk.Kind == DeclaratorChunk::Function);
1583 TL.setLParenLoc(Chunk.Loc);
1584 TL.setRParenLoc(Chunk.EndLoc);
1586 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1587 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1588 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1589 TL.setArg(tpi++, Param);
1591 // FIXME: exception specs
1594 void VisitTypeLoc(TypeLoc TL) {
1595 llvm_unreachable("unsupported TypeLoc kind in declarator!");
1600 /// \brief Create and instantiate a TypeSourceInfo with type source information.
1602 /// \param T QualType referring to the type as written in source code.
1604 /// \param ReturnTypeInfo For declarators whose return type does not show
1605 /// up in the normal place in the declaration specifiers (such as a C++
1606 /// conversion function), this pointer will refer to a type source information
1607 /// for that return type.
1609 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1610 TypeSourceInfo *ReturnTypeInfo) {
1611 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
1612 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
1614 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1615 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1616 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1619 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1621 // We have source information for the return type that was not in the
1622 // declaration specifiers; copy that information into the current type
1623 // location so that it will be retained. This occurs, for example, with
1624 // a C++ conversion function, where the return type occurs within the
1625 // declarator-id rather than in the declaration specifiers.
1626 if (ReturnTypeInfo && D.getDeclSpec().getTypeSpecType() == TST_unspecified) {
1627 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
1628 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
1629 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
1635 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
1636 QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) {
1637 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1638 // and Sema during declaration parsing. Try deallocating/caching them when
1639 // it's appropriate, instead of allocating them and keeping them around.
1640 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1641 new (LocT) LocInfoType(T, TInfo);
1642 assert(LocT->getTypeClass() != T->getTypeClass() &&
1643 "LocInfoType's TypeClass conflicts with an existing Type class");
1644 return QualType(LocT, 0);
1647 void LocInfoType::getAsStringInternal(std::string &Str,
1648 const PrintingPolicy &Policy) const {
1649 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1650 " was used directly instead of getting the QualType through"
1651 " GetTypeFromParser");
1654 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1655 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1656 /// they point to and return true. If T1 and T2 aren't pointer types
1657 /// or pointer-to-member types, or if they are not similar at this
1658 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1659 /// qualifiers on T1 and T2 are ignored. This function will typically
1660 /// be called in a loop that successively "unwraps" pointer and
1661 /// pointer-to-member types to compare them at each level.
1662 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1663 const PointerType *T1PtrType = T1->getAs<PointerType>(),
1664 *T2PtrType = T2->getAs<PointerType>();
1665 if (T1PtrType && T2PtrType) {
1666 T1 = T1PtrType->getPointeeType();
1667 T2 = T2PtrType->getPointeeType();
1671 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1672 *T2MPType = T2->getAs<MemberPointerType>();
1673 if (T1MPType && T2MPType &&
1674 Context.getCanonicalType(T1MPType->getClass()) ==
1675 Context.getCanonicalType(T2MPType->getClass())) {
1676 T1 = T1MPType->getPointeeType();
1677 T2 = T2MPType->getPointeeType();
1681 if (getLangOptions().ObjC1) {
1682 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
1683 *T2OPType = T2->getAs<ObjCObjectPointerType>();
1684 if (T1OPType && T2OPType) {
1685 T1 = T1OPType->getPointeeType();
1686 T2 = T2OPType->getPointeeType();
1693 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1694 // C99 6.7.6: Type names have no identifier. This is already validated by
1696 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1698 TypeSourceInfo *TInfo = 0;
1699 TagDecl *OwnedTag = 0;
1700 QualType T = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
1701 if (D.isInvalidType())
1704 if (getLangOptions().CPlusPlus) {
1705 // Check that there are no default arguments (C++ only).
1706 CheckExtraCXXDefaultArguments(D);
1708 // C++0x [dcl.type]p3:
1709 // A type-specifier-seq shall not define a class or enumeration
1710 // unless it appears in the type-id of an alias-declaration
1712 if (OwnedTag && OwnedTag->isDefinition())
1713 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1714 << Context.getTypeDeclType(OwnedTag);
1718 T = CreateLocInfoType(T, TInfo);
1720 return T.getAsOpaquePtr();
1725 //===----------------------------------------------------------------------===//
1726 // Type Attribute Processing
1727 //===----------------------------------------------------------------------===//
1729 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1730 /// specified type. The attribute contains 1 argument, the id of the address
1731 /// space for the type.
1732 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1733 const AttributeList &Attr, Sema &S){
1735 // If this type is already address space qualified, reject it.
1736 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1737 // for two or more different address spaces."
1738 if (Type.getAddressSpace()) {
1739 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1744 // Check the attribute arguments.
1745 if (Attr.getNumArgs() != 1) {
1746 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1750 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1751 llvm::APSInt addrSpace(32);
1752 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
1753 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1754 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1755 << ASArgExpr->getSourceRange();
1761 if (addrSpace.isSigned()) {
1762 if (addrSpace.isNegative()) {
1763 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1764 << ASArgExpr->getSourceRange();
1768 addrSpace.setIsSigned(false);
1770 llvm::APSInt max(addrSpace.getBitWidth());
1771 max = Qualifiers::MaxAddressSpace;
1772 if (addrSpace > max) {
1773 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1774 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1779 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1780 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1783 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1784 /// specified type. The attribute contains 1 argument, weak or strong.
1785 static void HandleObjCGCTypeAttribute(QualType &Type,
1786 const AttributeList &Attr, Sema &S) {
1787 if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1788 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1793 // Check the attribute arguments.
1794 if (!Attr.getParameterName()) {
1795 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1800 Qualifiers::GC GCAttr;
1801 if (Attr.getNumArgs() != 0) {
1802 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1806 if (Attr.getParameterName()->isStr("weak"))
1807 GCAttr = Qualifiers::Weak;
1808 else if (Attr.getParameterName()->isStr("strong"))
1809 GCAttr = Qualifiers::Strong;
1811 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1812 << "objc_gc" << Attr.getParameterName();
1817 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1820 /// Process an individual function attribute. Returns true if the
1821 /// attribute does not make sense to apply to this type.
1822 bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) {
1823 if (Attr.getKind() == AttributeList::AT_noreturn) {
1824 // Complain immediately if the arg count is wrong.
1825 if (Attr.getNumArgs() != 0) {
1826 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1831 // Delay if this is not a function or pointer to block.
1832 if (!Type->isFunctionPointerType()
1833 && !Type->isBlockPointerType()
1834 && !Type->isFunctionType())
1837 // Otherwise we can process right away.
1838 Type = S.Context.getNoReturnType(Type);
1842 if (Attr.getKind() == AttributeList::AT_regparm) {
1843 // The warning is emitted elsewhere
1844 if (Attr.getNumArgs() != 1) {
1848 // Delay if this is not a function or pointer to block.
1849 if (!Type->isFunctionPointerType()
1850 && !Type->isBlockPointerType()
1851 && !Type->isFunctionType())
1854 // Otherwise we can process right away.
1855 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0));
1856 llvm::APSInt NumParams(32);
1858 // The warning is emitted elsewhere
1859 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
1860 !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context))
1863 Type = S.Context.getRegParmType(Type, NumParams.getZExtValue());
1867 // Otherwise, a calling convention.
1868 if (Attr.getNumArgs() != 0) {
1869 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1875 if (const PointerType *PT = Type->getAs<PointerType>())
1876 T = PT->getPointeeType();
1877 const FunctionType *Fn = T->getAs<FunctionType>();
1879 // Delay if the type didn't work out to a function.
1880 if (!Fn) return true;
1882 // TODO: diagnose uses of these conventions on the wrong target.
1884 switch (Attr.getKind()) {
1885 case AttributeList::AT_cdecl: CC = CC_C; break;
1886 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
1887 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
1888 case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break;
1889 default: llvm_unreachable("unexpected attribute kind"); return false;
1892 CallingConv CCOld = Fn->getCallConv();
1893 if (S.Context.getCanonicalCallConv(CC) ==
1894 S.Context.getCanonicalCallConv(CCOld)) {
1899 if (CCOld != CC_Default) {
1900 // Should we diagnose reapplications of the same convention?
1901 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1902 << FunctionType::getNameForCallConv(CC)
1903 << FunctionType::getNameForCallConv(CCOld);
1908 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
1909 if (CC == CC_X86FastCall) {
1910 if (isa<FunctionNoProtoType>(Fn)) {
1911 S.Diag(Attr.getLoc(), diag::err_cconv_knr)
1912 << FunctionType::getNameForCallConv(CC);
1917 const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn);
1918 if (FnP->isVariadic()) {
1919 S.Diag(Attr.getLoc(), diag::err_cconv_varargs)
1920 << FunctionType::getNameForCallConv(CC);
1926 Type = S.Context.getCallConvType(Type, CC);
1930 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
1931 /// and float scalars, although arrays, pointers, and function return values are
1932 /// allowed in conjunction with this construct. Aggregates with this attribute
1933 /// are invalid, even if they are of the same size as a corresponding scalar.
1934 /// The raw attribute should contain precisely 1 argument, the vector size for
1935 /// the variable, measured in bytes. If curType and rawAttr are well formed,
1936 /// this routine will return a new vector type.
1937 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) {
1938 // Check the attribute arugments.
1939 if (Attr.getNumArgs() != 1) {
1940 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1944 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
1945 llvm::APSInt vecSize(32);
1946 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
1947 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
1948 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1949 << "vector_size" << sizeExpr->getSourceRange();
1953 // the base type must be integer or float, and can't already be a vector.
1954 if (CurType->isVectorType() ||
1955 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
1956 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
1960 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
1961 // vecSize is specified in bytes - convert to bits.
1962 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1964 // the vector size needs to be an integral multiple of the type size.
1965 if (vectorSize % typeSize) {
1966 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
1967 << sizeExpr->getSourceRange();
1971 if (vectorSize == 0) {
1972 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
1973 << sizeExpr->getSourceRange();
1978 // Success! Instantiate the vector type, the number of elements is > 0, and
1979 // not required to be a power of 2, unlike GCC.
1980 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false);
1983 void ProcessTypeAttributeList(Sema &S, QualType &Result,
1984 bool IsDeclSpec, const AttributeList *AL,
1985 DelayedAttributeSet &FnAttrs) {
1986 // Scan through and apply attributes to this type where it makes sense. Some
1987 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1988 // type, but others can be present in the type specifiers even though they
1989 // apply to the decl. Here we apply type attributes and ignore the rest.
1990 for (; AL; AL = AL->getNext()) {
1991 // Skip attributes that were marked to be invalid.
1992 if (AL->isInvalid())
1995 // If this is an attribute we can handle, do so now,
1996 // otherwise, add it to the FnAttrs list for rechaining.
1997 switch (AL->getKind()) {
2000 case AttributeList::AT_address_space:
2001 HandleAddressSpaceTypeAttribute(Result, *AL, S);
2003 case AttributeList::AT_objc_gc:
2004 HandleObjCGCTypeAttribute(Result, *AL, S);
2006 case AttributeList::AT_vector_size:
2007 HandleVectorSizeAttr(Result, *AL, S);
2010 case AttributeList::AT_noreturn:
2011 case AttributeList::AT_cdecl:
2012 case AttributeList::AT_fastcall:
2013 case AttributeList::AT_stdcall:
2014 case AttributeList::AT_thiscall:
2015 case AttributeList::AT_regparm:
2016 // Don't process these on the DeclSpec.
2018 ProcessFnAttr(S, Result, *AL))
2019 FnAttrs.push_back(DelayedAttribute(AL, Result));
2025 /// @brief Ensure that the type T is a complete type.
2027 /// This routine checks whether the type @p T is complete in any
2028 /// context where a complete type is required. If @p T is a complete
2029 /// type, returns false. If @p T is a class template specialization,
2030 /// this routine then attempts to perform class template
2031 /// instantiation. If instantiation fails, or if @p T is incomplete
2032 /// and cannot be completed, issues the diagnostic @p diag (giving it
2033 /// the type @p T) and returns true.
2035 /// @param Loc The location in the source that the incomplete type
2036 /// diagnostic should refer to.
2038 /// @param T The type that this routine is examining for completeness.
2040 /// @param PD The partial diagnostic that will be printed out if T is not a
2043 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
2044 /// @c false otherwise.
2045 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2046 const PartialDiagnostic &PD,
2047 std::pair<SourceLocation,
2048 PartialDiagnostic> Note) {
2049 unsigned diag = PD.getDiagID();
2051 // FIXME: Add this assertion to make sure we always get instantiation points.
2052 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
2053 // FIXME: Add this assertion to help us flush out problems with
2054 // checking for dependent types and type-dependent expressions.
2056 // assert(!T->isDependentType() &&
2057 // "Can't ask whether a dependent type is complete");
2059 // If we have a complete type, we're done.
2060 if (!T->isIncompleteType())
2063 // If we have a class template specialization or a class member of a
2064 // class template specialization, or an array with known size of such,
2065 // try to instantiate it.
2066 QualType MaybeTemplate = T;
2067 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
2068 MaybeTemplate = Array->getElementType();
2069 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
2070 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
2071 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
2072 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
2073 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
2074 TSK_ImplicitInstantiation,
2075 /*Complain=*/diag != 0);
2076 } else if (CXXRecordDecl *Rec
2077 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
2078 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
2079 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
2080 assert(MSInfo && "Missing member specialization information?");
2081 // This record was instantiated from a class within a template.
2082 if (MSInfo->getTemplateSpecializationKind()
2083 != TSK_ExplicitSpecialization)
2084 return InstantiateClass(Loc, Rec, Pattern,
2085 getTemplateInstantiationArgs(Rec),
2086 TSK_ImplicitInstantiation,
2087 /*Complain=*/diag != 0);
2095 const TagType *Tag = 0;
2096 if (const RecordType *Record = T->getAs<RecordType>())
2098 else if (const EnumType *Enum = T->getAs<EnumType>())
2101 // Avoid diagnosing invalid decls as incomplete.
2102 if (Tag && Tag->getDecl()->isInvalidDecl())
2105 // We have an incomplete type. Produce a diagnostic.
2108 // If we have a note, produce it.
2109 if (!Note.first.isInvalid())
2110 Diag(Note.first, Note.second);
2112 // If the type was a forward declaration of a class/struct/union
2113 // type, produce a note.
2114 if (Tag && !Tag->getDecl()->isInvalidDecl())
2115 Diag(Tag->getDecl()->getLocation(),
2116 Tag->isBeingDefined() ? diag::note_type_being_defined
2117 : diag::note_forward_declaration)
2118 << QualType(Tag, 0);
2123 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2124 const PartialDiagnostic &PD) {
2125 return RequireCompleteType(Loc, T, PD,
2126 std::make_pair(SourceLocation(), PDiag(0)));
2129 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2131 return RequireCompleteType(Loc, T, PDiag(DiagID),
2132 std::make_pair(SourceLocation(), PDiag(0)));
2135 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
2136 /// and qualified by the nested-name-specifier contained in SS.
2137 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
2138 const CXXScopeSpec &SS, QualType T) {
2141 NestedNameSpecifier *NNS;
2143 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2145 if (Keyword == ETK_None)
2149 return Context.getElaboratedType(Keyword, NNS, T);
2152 QualType Sema::BuildTypeofExprType(Expr *E) {
2153 if (E->getType() == Context.OverloadTy) {
2154 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2155 // function template specialization wherever deduction cannot occur.
2156 if (FunctionDecl *Specialization
2157 = ResolveSingleFunctionTemplateSpecialization(E)) {
2158 // The access doesn't really matter in this case.
2159 DeclAccessPair Found = DeclAccessPair::make(Specialization,
2160 Specialization->getAccess());
2161 E = FixOverloadedFunctionReference(E, Found, Specialization);
2165 Diag(E->getLocStart(),
2166 diag::err_cannot_determine_declared_type_of_overloaded_function)
2167 << false << E->getSourceRange();
2172 return Context.getTypeOfExprType(E);
2175 QualType Sema::BuildDecltypeType(Expr *E) {
2176 if (E->getType() == Context.OverloadTy) {
2177 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2178 // function template specialization wherever deduction cannot occur.
2179 if (FunctionDecl *Specialization
2180 = ResolveSingleFunctionTemplateSpecialization(E)) {
2181 // The access doesn't really matter in this case.
2182 DeclAccessPair Found = DeclAccessPair::make(Specialization,
2183 Specialization->getAccess());
2184 E = FixOverloadedFunctionReference(E, Found, Specialization);
2188 Diag(E->getLocStart(),
2189 diag::err_cannot_determine_declared_type_of_overloaded_function)
2190 << true << E->getSourceRange();
2195 return Context.getDecltypeType(E);