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/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/Parse/DeclSpec.h"
20 using namespace clang;
22 /// \brief Perform adjustment on the parameter type of a function.
24 /// This routine adjusts the given parameter type @p T to the actual
25 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
26 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
27 QualType Sema::adjustParameterType(QualType T) {
29 if (T->isArrayType()) {
31 // A declaration of a parameter as "array of type" shall be
32 // adjusted to "qualified pointer to type", where the type
33 // qualifiers (if any) are those specified within the [ and ] of
34 // the array type derivation.
35 return Context.getArrayDecayedType(T);
36 } else if (T->isFunctionType())
38 // A declaration of a parameter as "function returning type"
39 // shall be adjusted to "pointer to function returning type", as
41 return Context.getPointerType(T);
46 /// \brief Convert the specified declspec to the appropriate type
48 /// \param DS the declaration specifiers
49 /// \param DeclLoc The location of the declarator identifier or invalid if none.
50 /// \returns The type described by the declaration specifiers. This function
51 /// never returns null.
52 QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
53 SourceLocation DeclLoc,
55 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
59 switch (DS.getTypeSpecType()) {
60 case DeclSpec::TST_void:
61 Result = Context.VoidTy;
63 case DeclSpec::TST_char:
64 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
65 Result = Context.CharTy;
66 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
67 Result = Context.SignedCharTy;
69 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
71 Result = Context.UnsignedCharTy;
74 case DeclSpec::TST_wchar:
75 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
76 Result = Context.WCharTy;
77 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
78 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
79 << DS.getSpecifierName(DS.getTypeSpecType());
80 Result = Context.getSignedWCharType();
82 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
84 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
85 << DS.getSpecifierName(DS.getTypeSpecType());
86 Result = Context.getUnsignedWCharType();
89 case DeclSpec::TST_unspecified:
90 // "<proto1,proto2>" is an objc qualified ID with a missing id.
91 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
92 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
93 DS.getNumProtocolQualifiers());
97 // Unspecified typespec defaults to int in C90. However, the C90 grammar
98 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
99 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
100 // Note that the one exception to this is function definitions, which are
101 // allowed to be completely missing a declspec. This is handled in the
102 // parser already though by it pretending to have seen an 'int' in this
104 if (getLangOptions().ImplicitInt) {
105 // In C89 mode, we only warn if there is a completely missing declspec
106 // when one is not allowed.
108 if (DeclLoc.isInvalid())
109 DeclLoc = DS.getSourceRange().getBegin();
110 Diag(DeclLoc, diag::ext_missing_declspec)
111 << DS.getSourceRange()
112 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
115 } else if (!DS.hasTypeSpecifier()) {
116 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
117 // "At least one type specifier shall be given in the declaration
118 // specifiers in each declaration, and in the specifier-qualifier list in
119 // each struct declaration and type name."
120 // FIXME: Does Microsoft really have the implicit int extension in C++?
121 if (DeclLoc.isInvalid())
122 DeclLoc = DS.getSourceRange().getBegin();
124 if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft)
125 Diag(DeclLoc, diag::err_missing_type_specifier)
126 << DS.getSourceRange();
128 Diag(DeclLoc, diag::ext_missing_type_specifier)
129 << DS.getSourceRange();
131 // FIXME: If we could guarantee that the result would be well-formed, it
132 // would be useful to have a code insertion hint here. However, after
133 // emitting this warning/error, we often emit other errors.
137 case DeclSpec::TST_int: {
138 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
139 switch (DS.getTypeSpecWidth()) {
140 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
141 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
142 case DeclSpec::TSW_long: Result = Context.LongTy; break;
143 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break;
146 switch (DS.getTypeSpecWidth()) {
147 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
148 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
149 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
150 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break;
155 case DeclSpec::TST_float: Result = Context.FloatTy; break;
156 case DeclSpec::TST_double:
157 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
158 Result = Context.LongDoubleTy;
160 Result = Context.DoubleTy;
162 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
163 case DeclSpec::TST_decimal32: // _Decimal32
164 case DeclSpec::TST_decimal64: // _Decimal64
165 case DeclSpec::TST_decimal128: // _Decimal128
166 Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
167 Result = Context.IntTy;
170 case DeclSpec::TST_class:
171 case DeclSpec::TST_enum:
172 case DeclSpec::TST_union:
173 case DeclSpec::TST_struct: {
174 Decl *D = static_cast<Decl *>(DS.getTypeRep());
175 assert(D && "Didn't get a decl for a class/enum/union/struct?");
176 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
177 DS.getTypeSpecSign() == 0 &&
178 "Can't handle qualifiers on typedef names yet!");
179 // TypeQuals handled by caller.
180 Result = Context.getTypeDeclType(cast<TypeDecl>(D));
182 if (D->isInvalidDecl())
186 case DeclSpec::TST_typename: {
187 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
188 DS.getTypeSpecSign() == 0 &&
189 "Can't handle qualifiers on typedef names yet!");
190 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
192 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
193 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have
194 // this "hack" for now...
195 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
196 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
197 (ObjCProtocolDecl**)PQ,
198 DS.getNumProtocolQualifiers());
199 else if (Result == Context.getObjCIdType())
201 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
202 DS.getNumProtocolQualifiers());
203 else if (Result == Context.getObjCClassType()) {
204 if (DeclLoc.isInvalid())
205 DeclLoc = DS.getSourceRange().getBegin();
206 // Class<protocol-list>
207 Diag(DeclLoc, diag::err_qualified_class_unsupported)
208 << DS.getSourceRange();
210 if (DeclLoc.isInvalid())
211 DeclLoc = DS.getSourceRange().getBegin();
212 Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
213 << DS.getSourceRange();
218 // If this is a reference to an invalid typedef, propagate the invalidity.
219 if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
220 if (TDT->getDecl()->isInvalidDecl())
223 // TypeQuals handled by caller.
226 case DeclSpec::TST_typeofType:
227 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
228 assert(!Result.isNull() && "Didn't get a type for typeof?");
229 // TypeQuals handled by caller.
230 Result = Context.getTypeOfType(Result);
232 case DeclSpec::TST_typeofExpr: {
233 Expr *E = static_cast<Expr *>(DS.getTypeRep());
234 assert(E && "Didn't get an expression for typeof?");
235 // TypeQuals handled by caller.
236 Result = Context.getTypeOfExprType(E);
239 case DeclSpec::TST_error:
240 Result = Context.IntTy;
245 // Handle complex types.
246 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
247 if (getLangOptions().Freestanding)
248 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
249 Result = Context.getComplexType(Result);
252 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
253 "FIXME: imaginary types not supported yet!");
255 // See if there are any attributes on the declspec that apply to the type (as
256 // opposed to the decl).
257 if (const AttributeList *AL = DS.getAttributes())
258 ProcessTypeAttributeList(Result, AL);
260 // Apply const/volatile/restrict qualifiers to T.
261 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
263 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
264 // or incomplete types shall not be restrict-qualified." C++ also allows
265 // restrict-qualified references.
266 if (TypeQuals & QualType::Restrict) {
267 if (Result->isPointerType() || Result->isReferenceType()) {
268 QualType EltTy = Result->isPointerType() ?
269 Result->getAsPointerType()->getPointeeType() :
270 Result->getAsReferenceType()->getPointeeType();
272 // If we have a pointer or reference, the pointee must have an object
274 if (!EltTy->isIncompleteOrObjectType()) {
275 Diag(DS.getRestrictSpecLoc(),
276 diag::err_typecheck_invalid_restrict_invalid_pointee)
277 << EltTy << DS.getSourceRange();
278 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
281 Diag(DS.getRestrictSpecLoc(),
282 diag::err_typecheck_invalid_restrict_not_pointer)
283 << Result << DS.getSourceRange();
284 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
288 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
289 // of a function type includes any type qualifiers, the behavior is
291 if (Result->isFunctionType() && TypeQuals) {
292 // Get some location to point at, either the C or V location.
294 if (TypeQuals & QualType::Const)
295 Loc = DS.getConstSpecLoc();
297 assert((TypeQuals & QualType::Volatile) &&
298 "Has CV quals but not C or V?");
299 Loc = DS.getVolatileSpecLoc();
301 Diag(Loc, diag::warn_typecheck_function_qualifiers)
302 << Result << DS.getSourceRange();
306 // Cv-qualified references are ill-formed except when the
307 // cv-qualifiers are introduced through the use of a typedef
308 // (7.1.3) or of a template type argument (14.3), in which
309 // case the cv-qualifiers are ignored.
310 // FIXME: Shouldn't we be checking SCS_typedef here?
311 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
312 TypeQuals && Result->isReferenceType()) {
313 TypeQuals &= ~QualType::Const;
314 TypeQuals &= ~QualType::Volatile;
317 Result = Result.getQualifiedType(TypeQuals);
322 static std::string getPrintableNameForEntity(DeclarationName Entity) {
324 return Entity.getAsString();
329 /// \brief Build a pointer type.
331 /// \param T The type to which we'll be building a pointer.
333 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
335 /// \param Loc The location of the entity whose type involves this
336 /// pointer type or, if there is no such entity, the location of the
337 /// type that will have pointer type.
339 /// \param Entity The name of the entity that involves the pointer
342 /// \returns A suitable pointer type, if there are no
343 /// errors. Otherwise, returns a NULL type.
344 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
345 SourceLocation Loc, DeclarationName Entity) {
346 if (T->isReferenceType()) {
347 // C++ 8.3.2p4: There shall be no ... pointers to references ...
348 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
349 << getPrintableNameForEntity(Entity);
353 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
354 // object or incomplete types shall not be restrict-qualified."
355 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
356 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
358 Quals &= ~QualType::Restrict;
361 // Build the pointer type.
362 return Context.getPointerType(T).getQualifiedType(Quals);
365 /// \brief Build a reference type.
367 /// \param T The type to which we'll be building a reference.
369 /// \param Quals The cvr-qualifiers to be applied to the reference type.
371 /// \param Loc The location of the entity whose type involves this
372 /// reference type or, if there is no such entity, the location of the
373 /// type that will have reference type.
375 /// \param Entity The name of the entity that involves the reference
378 /// \returns A suitable reference type, if there are no
379 /// errors. Otherwise, returns a NULL type.
380 QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
381 SourceLocation Loc, DeclarationName Entity) {
383 if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
384 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
385 // reference to a type T, and attempt to create the type "lvalue
386 // reference to cv TD" creates the type "lvalue reference to T".
387 // We use the qualifiers (restrict or none) of the original reference,
388 // not the new ones. This is consistent with GCC.
389 return Context.getLValueReferenceType(R->getPointeeType()).
390 getQualifiedType(T.getCVRQualifiers());
393 if (T->isReferenceType()) {
394 // C++ [dcl.ref]p4: There shall be no references to references.
396 // According to C++ DR 106, references to references are only
397 // diagnosed when they are written directly (e.g., "int & &"),
398 // but not when they happen via a typedef:
400 // typedef int& intref;
401 // typedef intref& intref2;
403 // Parser::ParserDeclaratorInternal diagnoses the case where
404 // references are written directly; here, we handle the
405 // collapsing of references-to-references as described in C++
406 // DR 106 and amended by C++ DR 540.
411 // A declarator that specifies the type “reference to cv void”
413 if (T->isVoidType()) {
414 Diag(Loc, diag::err_reference_to_void);
418 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
419 // object or incomplete types shall not be restrict-qualified."
420 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
421 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
423 Quals &= ~QualType::Restrict;
427 // [...] Cv-qualified references are ill-formed except when the
428 // cv-qualifiers are introduced through the use of a typedef
429 // (7.1.3) or of a template type argument (14.3), in which case
430 // the cv-qualifiers are ignored.
432 // We diagnose extraneous cv-qualifiers for the non-typedef,
433 // non-template type argument case within the parser. Here, we just
434 // ignore any extraneous cv-qualifiers.
435 Quals &= ~QualType::Const;
436 Quals &= ~QualType::Volatile;
438 // Handle restrict on references.
440 return Context.getLValueReferenceType(T).getQualifiedType(Quals);
441 return Context.getRValueReferenceType(T).getQualifiedType(Quals);
444 /// \brief Build an array type.
446 /// \param T The type of each element in the array.
448 /// \param ASM C99 array size modifier (e.g., '*', 'static').
450 /// \param ArraySize Expression describing the size of the array.
452 /// \param Quals The cvr-qualifiers to be applied to the array's
455 /// \param Loc The location of the entity whose type involves this
456 /// array type or, if there is no such entity, the location of the
457 /// type that will have array type.
459 /// \param Entity The name of the entity that involves the array
462 /// \returns A suitable array type, if there are no errors. Otherwise,
463 /// returns a NULL type.
464 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
465 Expr *ArraySize, unsigned Quals,
466 SourceLocation Loc, DeclarationName Entity) {
467 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
468 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
469 if (RequireCompleteType(Loc, T,
470 diag::err_illegal_decl_array_incomplete_type))
473 if (T->isFunctionType()) {
474 Diag(Loc, diag::err_illegal_decl_array_of_functions)
475 << getPrintableNameForEntity(Entity);
479 // C++ 8.3.2p4: There shall be no ... arrays of references ...
480 if (T->isReferenceType()) {
481 Diag(Loc, diag::err_illegal_decl_array_of_references)
482 << getPrintableNameForEntity(Entity);
486 if (const RecordType *EltTy = T->getAsRecordType()) {
487 // If the element type is a struct or union that contains a variadic
488 // array, accept it as a GNU extension: C99 6.7.2.1p2.
489 if (EltTy->getDecl()->hasFlexibleArrayMember())
490 Diag(Loc, diag::ext_flexible_array_in_array) << T;
491 } else if (T->isObjCInterfaceType()) {
492 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
496 // C99 6.7.5.2p1: The size expression shall have integer type.
497 if (ArraySize && !ArraySize->isTypeDependent() &&
498 !ArraySize->getType()->isIntegerType()) {
499 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
500 << ArraySize->getType() << ArraySize->getSourceRange();
501 ArraySize->Destroy(Context);
504 llvm::APSInt ConstVal(32);
506 if (ASM == ArrayType::Star)
507 T = Context.getVariableArrayType(T, 0, ASM, Quals);
509 T = Context.getIncompleteArrayType(T, ASM, Quals);
510 } else if (ArraySize->isValueDependent()) {
511 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
512 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
513 (!T->isDependentType() && !T->isConstantSizeType())) {
514 // Per C99, a variable array is an array with either a non-constant
515 // size or an element type that has a non-constant-size
516 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
518 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
519 // have a value greater than zero.
520 if (ConstVal.isSigned()) {
521 if (ConstVal.isNegative()) {
522 Diag(ArraySize->getLocStart(),
523 diag::err_typecheck_negative_array_size)
524 << ArraySize->getSourceRange();
526 } else if (ConstVal == 0) {
527 // GCC accepts zero sized static arrays.
528 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
529 << ArraySize->getSourceRange();
532 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
534 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
535 if (!getLangOptions().C99) {
536 if (ArraySize && !ArraySize->isTypeDependent() &&
537 !ArraySize->isValueDependent() &&
538 !ArraySize->isIntegerConstantExpr(Context))
539 Diag(Loc, diag::ext_vla);
540 else if (ASM != ArrayType::Normal || Quals != 0)
541 Diag(Loc, diag::ext_c99_array_usage);
547 /// \brief Build a function type.
549 /// This routine checks the function type according to C++ rules and
550 /// under the assumption that the result type and parameter types have
551 /// just been instantiated from a template. It therefore duplicates
552 /// some of the behavior of GetTypeForDeclarator, but in a much
553 /// simpler form that is only suitable for this narrow use case.
555 /// \param T The return type of the function.
557 /// \param ParamTypes The parameter types of the function. This array
558 /// will be modified to account for adjustments to the types of the
559 /// function parameters.
561 /// \param NumParamTypes The number of parameter types in ParamTypes.
563 /// \param Variadic Whether this is a variadic function type.
565 /// \param Quals The cvr-qualifiers to be applied to the function type.
567 /// \param Loc The location of the entity whose type involves this
568 /// function type or, if there is no such entity, the location of the
569 /// type that will have function type.
571 /// \param Entity The name of the entity that involves the function
574 /// \returns A suitable function type, if there are no
575 /// errors. Otherwise, returns a NULL type.
576 QualType Sema::BuildFunctionType(QualType T,
577 QualType *ParamTypes,
578 unsigned NumParamTypes,
579 bool Variadic, unsigned Quals,
580 SourceLocation Loc, DeclarationName Entity) {
581 if (T->isArrayType() || T->isFunctionType()) {
582 Diag(Loc, diag::err_func_returning_array_function) << T;
586 bool Invalid = false;
587 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
588 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
589 if (ParamType->isVoidType()) {
590 Diag(Loc, diag::err_param_with_void_type);
594 ParamTypes[Idx] = ParamType;
600 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
604 /// \brief Build a member pointer type \c T Class::*.
606 /// \param T the type to which the member pointer refers.
607 /// \param Class the class type into which the member pointer points.
608 /// \param Quals Qualifiers applied to the member pointer type
609 /// \param Loc the location where this type begins
610 /// \param Entity the name of the entity that will have this member pointer type
612 /// \returns a member pointer type, if successful, or a NULL type if there was
614 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
615 unsigned Quals, SourceLocation Loc,
616 DeclarationName Entity) {
617 // Verify that we're not building a pointer to pointer to function with
618 // exception specification.
619 if (CheckDistantExceptionSpec(T)) {
620 Diag(Loc, diag::err_distant_exception_spec);
622 // FIXME: If we're doing this as part of template instantiation,
623 // we should return immediately.
625 // Build the type anyway, but use the canonical type so that the
626 // exception specifiers are stripped off.
627 T = Context.getCanonicalType(T);
630 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
631 // with reference type, or "cv void."
632 if (T->isReferenceType()) {
633 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
634 << (Entity? Entity.getAsString() : "type name");
638 if (T->isVoidType()) {
639 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
640 << (Entity? Entity.getAsString() : "type name");
644 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
645 // object or incomplete types shall not be restrict-qualified."
646 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
647 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
650 // FIXME: If we're doing this as part of template instantiation,
651 // we should return immediately.
652 Quals &= ~QualType::Restrict;
655 if (!Class->isDependentType() && !Class->isRecordType()) {
656 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
660 return Context.getMemberPointerType(T, Class.getTypePtr())
661 .getQualifiedType(Quals);
664 /// \brief Build a block pointer type.
666 /// \param T The type to which we'll be building a block pointer.
668 /// \param Quals The cvr-qualifiers to be applied to the block pointer type.
670 /// \param Loc The location of the entity whose type involves this
671 /// block pointer type or, if there is no such entity, the location of the
672 /// type that will have block pointer type.
674 /// \param Entity The name of the entity that involves the block pointer
677 /// \returns A suitable block pointer type, if there are no
678 /// errors. Otherwise, returns a NULL type.
679 QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals,
681 DeclarationName Entity) {
682 if (!T.getTypePtr()->isFunctionType()) {
683 Diag(Loc, diag::err_nonfunction_block_type);
687 return Context.getBlockPointerType(T).getQualifiedType(Quals);
690 /// GetTypeForDeclarator - Convert the type for the specified
691 /// declarator to Type instances. Skip the outermost Skip type
694 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
695 /// owns the declaration of a type (e.g., the definition of a struct
696 /// type), then *OwnedDecl will receive the owned declaration.
697 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip,
698 TagDecl **OwnedDecl) {
699 bool OmittedReturnType = false;
701 if (D.getContext() == Declarator::BlockLiteralContext
703 && !D.getDeclSpec().hasTypeSpecifier()
704 && (D.getNumTypeObjects() == 0
705 || (D.getNumTypeObjects() == 1
706 && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
707 OmittedReturnType = true;
709 // long long is a C99 feature.
710 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
711 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
712 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
714 // Determine the type of the declarator. Not all forms of declarator
717 switch (D.getKind()) {
718 case Declarator::DK_Abstract:
719 case Declarator::DK_Normal:
720 case Declarator::DK_Operator: {
721 const DeclSpec &DS = D.getDeclSpec();
722 if (OmittedReturnType) {
723 // We default to a dependent type initially. Can be modified by
724 // the first return statement.
725 T = Context.DependentTy;
727 bool isInvalid = false;
728 T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
730 D.setInvalidType(true);
731 else if (OwnedDecl && DS.isTypeSpecOwned())
732 *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep());
737 case Declarator::DK_Constructor:
738 case Declarator::DK_Destructor:
739 case Declarator::DK_Conversion:
740 // Constructors and destructors don't have return types. Use
741 // "void" instead. Conversion operators will check their return
747 // The name we're declaring, if any.
748 DeclarationName Name;
749 if (D.getIdentifier())
750 Name = D.getIdentifier();
752 // Walk the DeclTypeInfo, building the recursive type as we go.
753 // DeclTypeInfos are ordered from the identifier out, which is
754 // opposite of what we want :).
755 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
756 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
757 switch (DeclType.Kind) {
758 default: assert(0 && "Unknown decltype!");
759 case DeclaratorChunk::BlockPointer:
760 // If blocks are disabled, emit an error.
761 if (!LangOpts.Blocks)
762 Diag(DeclType.Loc, diag::err_blocks_disable);
764 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
767 case DeclaratorChunk::Pointer:
768 // Verify that we're not building a pointer to pointer to function with
769 // exception specification.
770 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
771 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
772 D.setInvalidType(true);
773 // Build the type anyway.
775 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
777 case DeclaratorChunk::Reference:
778 // Verify that we're not building a reference to pointer to function with
779 // exception specification.
780 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
781 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
782 D.setInvalidType(true);
783 // Build the type anyway.
785 T = BuildReferenceType(T, DeclType.Ref.LValueRef,
786 DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
789 case DeclaratorChunk::Array: {
790 // Verify that we're not building an array of pointers to function with
791 // exception specification.
792 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
793 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
794 D.setInvalidType(true);
795 // Build the type anyway.
797 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
798 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
799 ArrayType::ArraySizeModifier ASM;
801 ASM = ArrayType::Star;
802 else if (ATI.hasStatic)
803 ASM = ArrayType::Static;
805 ASM = ArrayType::Normal;
806 if (ASM == ArrayType::Star &&
807 D.getContext() != Declarator::PrototypeContext) {
808 // FIXME: This check isn't quite right: it allows star in prototypes
809 // for function definitions, and disallows some edge cases detailed
810 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
811 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
812 ASM = ArrayType::Normal;
813 D.setInvalidType(true);
815 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
818 case DeclaratorChunk::Function: {
819 // If the function declarator has a prototype (i.e. it is not () and
820 // does not have a K&R-style identifier list), then the arguments are part
821 // of the type, otherwise the argument list is ().
822 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
824 // C99 6.7.5.3p1: The return type may not be a function or array type.
825 if (T->isArrayType() || T->isFunctionType()) {
826 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
828 D.setInvalidType(true);
831 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
833 // Types shall not be defined in return or parameter types.
834 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
835 if (Tag->isDefinition())
836 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
837 << Context.getTypeDeclType(Tag);
840 // Exception specs are not allowed in typedefs. Complain, but add it
842 if (FTI.hasExceptionSpec &&
843 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
844 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
846 if (FTI.NumArgs == 0) {
847 if (getLangOptions().CPlusPlus) {
848 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
849 // function takes no arguments.
850 llvm::SmallVector<QualType, 4> Exceptions;
851 Exceptions.reserve(FTI.NumExceptions);
852 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
853 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
854 // Check that the type is valid for an exception spec, and drop it
856 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
857 Exceptions.push_back(ET);
859 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
860 FTI.hasExceptionSpec,
861 FTI.hasAnyExceptionSpec,
862 Exceptions.size(), Exceptions.data());
863 } else if (FTI.isVariadic) {
864 // We allow a zero-parameter variadic function in C if the
865 // function is marked with the "overloadable"
866 // attribute. Scan for this attribute now.
867 bool Overloadable = false;
868 for (const AttributeList *Attrs = D.getAttributes();
869 Attrs; Attrs = Attrs->getNext()) {
870 if (Attrs->getKind() == AttributeList::AT_overloadable) {
877 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
878 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
880 // Simple void foo(), where the incoming T is the result type.
881 T = Context.getFunctionNoProtoType(T);
883 } else if (FTI.ArgInfo[0].Param == 0) {
884 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
885 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
887 // Otherwise, we have a function with an argument list that is
888 // potentially variadic.
889 llvm::SmallVector<QualType, 16> ArgTys;
891 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
893 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
894 QualType ArgTy = Param->getType();
895 assert(!ArgTy.isNull() && "Couldn't parse type?");
897 // Adjust the parameter type.
898 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
900 // Look for 'void'. void is allowed only as a single argument to a
901 // function with no other parameters (C99 6.7.5.3p10). We record
902 // int(void) as a FunctionProtoType with an empty argument list.
903 if (ArgTy->isVoidType()) {
904 // If this is something like 'float(int, void)', reject it. 'void'
905 // is an incomplete type (C99 6.2.5p19) and function decls cannot
906 // have arguments of incomplete type.
907 if (FTI.NumArgs != 1 || FTI.isVariadic) {
908 Diag(DeclType.Loc, diag::err_void_only_param);
909 ArgTy = Context.IntTy;
910 Param->setType(ArgTy);
911 } else if (FTI.ArgInfo[i].Ident) {
912 // Reject, but continue to parse 'int(void abc)'.
913 Diag(FTI.ArgInfo[i].IdentLoc,
914 diag::err_param_with_void_type);
915 ArgTy = Context.IntTy;
916 Param->setType(ArgTy);
918 // Reject, but continue to parse 'float(const void)'.
919 if (ArgTy.getCVRQualifiers())
920 Diag(DeclType.Loc, diag::err_void_param_qualified);
922 // Do not add 'void' to the ArgTys list.
925 } else if (!FTI.hasPrototype) {
926 if (ArgTy->isPromotableIntegerType()) {
927 ArgTy = Context.IntTy;
928 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
929 if (BTy->getKind() == BuiltinType::Float)
930 ArgTy = Context.DoubleTy;
934 ArgTys.push_back(ArgTy);
937 llvm::SmallVector<QualType, 4> Exceptions;
938 Exceptions.reserve(FTI.NumExceptions);
939 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
940 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
941 // Check that the type is valid for an exception spec, and drop it if
943 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
944 Exceptions.push_back(ET);
947 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
948 FTI.isVariadic, FTI.TypeQuals,
949 FTI.hasExceptionSpec,
950 FTI.hasAnyExceptionSpec,
951 Exceptions.size(), Exceptions.data());
955 case DeclaratorChunk::MemberPointer:
956 // The scope spec must refer to a class, or be dependent.
958 if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
959 NestedNameSpecifier *NNS
960 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
961 assert(NNS->getAsType() && "Nested-name-specifier must name a type");
962 ClsType = QualType(NNS->getAsType(), 0);
963 } else if (CXXRecordDecl *RD
964 = dyn_cast_or_null<CXXRecordDecl>(
965 computeDeclContext(DeclType.Mem.Scope()))) {
966 ClsType = Context.getTagDeclType(RD);
968 Diag(DeclType.Mem.Scope().getBeginLoc(),
969 diag::err_illegal_decl_mempointer_in_nonclass)
970 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
971 << DeclType.Mem.Scope().getRange();
972 D.setInvalidType(true);
975 if (!ClsType.isNull())
976 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
977 DeclType.Loc, D.getIdentifier());
980 D.setInvalidType(true);
986 D.setInvalidType(true);
990 // See if there are any attributes on this declarator chunk.
991 if (const AttributeList *AL = DeclType.getAttrs())
992 ProcessTypeAttributeList(T, AL);
995 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
996 const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
997 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
999 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1000 // for a nonstatic member function, the function type to which a pointer
1001 // to member refers, or the top-level function type of a function typedef
1003 if (FnTy->getTypeQuals() != 0 &&
1004 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1005 ((D.getContext() != Declarator::MemberContext &&
1006 (!D.getCXXScopeSpec().isSet() ||
1007 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) ||
1008 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1009 if (D.isFunctionDeclarator())
1010 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1012 Diag(D.getIdentifierLoc(),
1013 diag::err_invalid_qualified_typedef_function_type_use);
1015 // Strip the cv-quals from the type.
1016 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1017 FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1021 // If there were any type attributes applied to the decl itself (not the
1022 // type, apply the type attribute to the type!)
1023 if (const AttributeList *Attrs = D.getAttributes())
1024 ProcessTypeAttributeList(T, Attrs);
1029 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
1030 /// exception specification. Incomplete types, or pointers to incomplete types
1031 /// other than void are not allowed.
1032 bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1033 // FIXME: This may not correctly work with the fix for core issue 437,
1034 // where a class's own type is considered complete within its body.
1036 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1037 // an incomplete type.
1038 if (T->isIncompleteType())
1039 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1040 << Range << T << /*direct*/0;
1042 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1043 // an incomplete type a pointer or reference to an incomplete type, other
1046 if (const PointerType* IT = T->getAsPointerType()) {
1047 T = IT->getPointeeType();
1049 } else if (const ReferenceType* IT = T->getAsReferenceType()) {
1050 T = IT->getPointeeType();
1055 if (T->isIncompleteType() && !T->isVoidType())
1056 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1057 << Range << T << /*indirect*/kind;
1062 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1063 /// to member to a function with an exception specification. This means that
1064 /// it is invalid to add another level of indirection.
1065 bool Sema::CheckDistantExceptionSpec(QualType T) {
1066 if (const PointerType *PT = T->getAsPointerType())
1067 T = PT->getPointeeType();
1068 else if (const MemberPointerType *PT = T->getAsMemberPointerType())
1069 T = PT->getPointeeType();
1073 const FunctionProtoType *FnT = T->getAsFunctionProtoType();
1077 return FnT->hasExceptionSpec();
1080 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1082 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1083 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1084 QualType T = MDecl->getResultType();
1085 llvm::SmallVector<QualType, 16> ArgTys;
1087 // Add the first two invisible argument types for self and _cmd.
1088 if (MDecl->isInstanceMethod()) {
1089 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1090 selfTy = Context.getPointerType(selfTy);
1091 ArgTys.push_back(selfTy);
1093 ArgTys.push_back(Context.getObjCIdType());
1094 ArgTys.push_back(Context.getObjCSelType());
1096 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1097 E = MDecl->param_end(); PI != E; ++PI) {
1098 QualType ArgTy = (*PI)->getType();
1099 assert(!ArgTy.isNull() && "Couldn't parse type?");
1100 ArgTy = adjustParameterType(ArgTy);
1101 ArgTys.push_back(ArgTy);
1103 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1104 MDecl->isVariadic(), 0);
1108 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1109 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1110 /// they point to and return true. If T1 and T2 aren't pointer types
1111 /// or pointer-to-member types, or if they are not similar at this
1112 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1113 /// qualifiers on T1 and T2 are ignored. This function will typically
1114 /// be called in a loop that successively "unwraps" pointer and
1115 /// pointer-to-member types to compare them at each level.
1116 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1117 const PointerType *T1PtrType = T1->getAsPointerType(),
1118 *T2PtrType = T2->getAsPointerType();
1119 if (T1PtrType && T2PtrType) {
1120 T1 = T1PtrType->getPointeeType();
1121 T2 = T2PtrType->getPointeeType();
1125 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
1126 *T2MPType = T2->getAsMemberPointerType();
1127 if (T1MPType && T2MPType &&
1128 Context.getCanonicalType(T1MPType->getClass()) ==
1129 Context.getCanonicalType(T2MPType->getClass())) {
1130 T1 = T1MPType->getPointeeType();
1131 T2 = T2MPType->getPointeeType();
1137 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1138 // C99 6.7.6: Type names have no identifier. This is already validated by
1140 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1142 TagDecl *OwnedTag = 0;
1143 QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
1144 if (D.isInvalidType())
1147 if (getLangOptions().CPlusPlus) {
1148 // Check that there are no default arguments (C++ only).
1149 CheckExtraCXXDefaultArguments(D);
1151 // C++0x [dcl.type]p3:
1152 // A type-specifier-seq shall not define a class or enumeration
1153 // unless it appears in the type-id of an alias-declaration
1155 if (OwnedTag && OwnedTag->isDefinition())
1156 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1157 << Context.getTypeDeclType(OwnedTag);
1160 return T.getAsOpaquePtr();
1165 //===----------------------------------------------------------------------===//
1166 // Type Attribute Processing
1167 //===----------------------------------------------------------------------===//
1169 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1170 /// specified type. The attribute contains 1 argument, the id of the address
1171 /// space for the type.
1172 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1173 const AttributeList &Attr, Sema &S){
1174 // If this type is already address space qualified, reject it.
1175 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1176 // for two or more different address spaces."
1177 if (Type.getAddressSpace()) {
1178 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1182 // Check the attribute arguments.
1183 if (Attr.getNumArgs() != 1) {
1184 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1187 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1188 llvm::APSInt addrSpace(32);
1189 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1190 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1191 << ASArgExpr->getSourceRange();
1195 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1196 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1199 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1200 /// specified type. The attribute contains 1 argument, weak or strong.
1201 static void HandleObjCGCTypeAttribute(QualType &Type,
1202 const AttributeList &Attr, Sema &S) {
1203 if (Type.getObjCGCAttr() != QualType::GCNone) {
1204 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1208 // Check the attribute arguments.
1209 if (!Attr.getParameterName()) {
1210 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1214 QualType::GCAttrTypes GCAttr;
1215 if (Attr.getNumArgs() != 0) {
1216 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1219 if (Attr.getParameterName()->isStr("weak"))
1220 GCAttr = QualType::Weak;
1221 else if (Attr.getParameterName()->isStr("strong"))
1222 GCAttr = QualType::Strong;
1224 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1225 << "objc_gc" << Attr.getParameterName();
1229 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1232 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1233 // Scan through and apply attributes to this type where it makes sense. Some
1234 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1235 // type, but others can be present in the type specifiers even though they
1236 // apply to the decl. Here we apply type attributes and ignore the rest.
1237 for (; AL; AL = AL->getNext()) {
1238 // If this is an attribute we can handle, do so now, otherwise, add it to
1239 // the LeftOverAttrs list for rechaining.
1240 switch (AL->getKind()) {
1242 case AttributeList::AT_address_space:
1243 HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1245 case AttributeList::AT_objc_gc:
1246 HandleObjCGCTypeAttribute(Result, *AL, *this);
1252 /// @brief Ensure that the type T is a complete type.
1254 /// This routine checks whether the type @p T is complete in any
1255 /// context where a complete type is required. If @p T is a complete
1256 /// type, returns false. If @p T is a class template specialization,
1257 /// this routine then attempts to perform class template
1258 /// instantiation. If instantiation fails, or if @p T is incomplete
1259 /// and cannot be completed, issues the diagnostic @p diag (giving it
1260 /// the type @p T) and returns true.
1262 /// @param Loc The location in the source that the incomplete type
1263 /// diagnostic should refer to.
1265 /// @param T The type that this routine is examining for completeness.
1267 /// @param diag The diagnostic value (e.g.,
1268 /// @c diag::err_typecheck_decl_incomplete_type) that will be used
1269 /// for the error message if @p T is incomplete.
1271 /// @param Range1 An optional range in the source code that will be a
1272 /// part of the "incomplete type" error message.
1274 /// @param Range2 An optional range in the source code that will be a
1275 /// part of the "incomplete type" error message.
1277 /// @param PrintType If non-NULL, the type that should be printed
1278 /// instead of @p T. This parameter should be used when the type that
1279 /// we're checking for incompleteness isn't the type that should be
1280 /// displayed to the user, e.g., when T is a type and PrintType is a
1283 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1284 /// @c false otherwise.
1285 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1286 SourceRange Range1, SourceRange Range2,
1287 QualType PrintType) {
1288 // FIXME: Add this assertion to help us flush out problems with
1289 // checking for dependent types and type-dependent expressions.
1291 // assert(!T->isDependentType() &&
1292 // "Can't ask whether a dependent type is complete");
1294 // If we have a complete type, we're done.
1295 if (!T->isIncompleteType())
1298 // If we have a class template specialization or a class member of a
1299 // class template specialization, try to instantiate it.
1300 if (const RecordType *Record = T->getAsRecordType()) {
1301 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1302 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1303 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1304 // Update the class template specialization's location to
1305 // refer to the point of instantiation.
1307 ClassTemplateSpec->setLocation(Loc);
1308 return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1309 /*ExplicitInstantiation=*/false);
1311 } else if (CXXRecordDecl *Rec
1312 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1313 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1314 // Find the class template specialization that surrounds this
1316 ClassTemplateSpecializationDecl *Spec = 0;
1317 for (DeclContext *Parent = Rec->getDeclContext();
1318 Parent && !Spec; Parent = Parent->getParent())
1319 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1320 assert(Spec && "Not a member of a class template specialization?");
1321 return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(),
1322 /*ExplicitInstantiation=*/false);
1327 if (PrintType.isNull())
1330 // We have an incomplete type. Produce a diagnostic.
1331 Diag(Loc, diag) << PrintType << Range1 << Range2;
1333 // If the type was a forward declaration of a class/struct/union
1335 const TagType *Tag = 0;
1336 if (const RecordType *Record = T->getAsRecordType())
1338 else if (const EnumType *Enum = T->getAsEnumType())
1341 if (Tag && !Tag->getDecl()->isInvalidDecl())
1342 Diag(Tag->getDecl()->getLocation(),
1343 Tag->isBeingDefined() ? diag::note_type_being_defined
1344 : diag::note_forward_declaration)
1345 << QualType(Tag, 0);
1350 /// \brief Retrieve a version of the type 'T' that is qualified by the
1351 /// nested-name-specifier contained in SS.
1352 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1353 if (!SS.isSet() || SS.isInvalid() || T.isNull())
1356 NestedNameSpecifier *NNS
1357 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1358 return Context.getQualifiedNameType(NNS, T);