1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
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 semantic analysis for cast expressions, including
11 // 1) C-style casts like '(int) x'
12 // 2) C++ functional casts like 'int(x)'
13 // 3) C++ named casts like 'static_cast<int>(x)'
15 //===----------------------------------------------------------------------===//
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Sema/Initialization.h"
25 #include "llvm/ADT/SmallVector.h"
27 using namespace clang;
32 TC_NotApplicable, ///< The cast method is not applicable.
33 TC_Success, ///< The cast method is appropriate and successful.
34 TC_Failed ///< The cast method is appropriate, but failed. A
35 ///< diagnostic has been emitted.
39 CT_Const, ///< const_cast
40 CT_Static, ///< static_cast
41 CT_Reinterpret, ///< reinterpret_cast
42 CT_Dynamic, ///< dynamic_cast
43 CT_CStyle, ///< (Type)expr
44 CT_Functional ///< Type(expr)
48 struct CastOperation {
49 CastOperation(Sema &S, QualType destType, ExprResult src)
50 : Self(S), SrcExpr(src), DestType(destType),
51 ResultType(destType.getNonLValueExprType(S.Context)),
52 ValueKind(Expr::getValueKindForType(destType)),
53 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
55 if (const BuiltinType *placeholder =
56 src.get()->getType()->getAsPlaceholderType()) {
57 PlaceholderKind = placeholder->getKind();
59 PlaceholderKind = (BuiltinType::Kind) 0;
67 ExprValueKind ValueKind;
69 BuiltinType::Kind PlaceholderKind;
71 bool IsARCUnbridgedCast;
74 SourceRange DestRange;
76 // Top-level semantics-checking routines.
77 void CheckConstCast();
78 void CheckReinterpretCast();
79 void CheckStaticCast();
80 void CheckDynamicCast();
81 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
82 void CheckCStyleCast();
84 /// Complete an apparently-successful cast operation that yields
85 /// the given expression.
86 ExprResult complete(CastExpr *castExpr) {
87 // If this is an unbridged cast, wrap the result in an implicit
88 // cast that yields the unbridged-cast placeholder type.
89 if (IsARCUnbridgedCast) {
90 castExpr = ImplicitCastExpr::Create(Self.Context,
91 Self.Context.ARCUnbridgedCastTy,
92 CK_Dependent, castExpr, 0,
93 castExpr->getValueKind());
95 return Self.Owned(castExpr);
98 // Internal convenience methods.
100 /// Try to handle the given placeholder expression kind. Return
101 /// true if the source expression has the appropriate placeholder
102 /// kind. A placeholder can only be claimed once.
103 bool claimPlaceholder(BuiltinType::Kind K) {
104 if (PlaceholderKind != K) return false;
106 PlaceholderKind = (BuiltinType::Kind) 0;
110 bool isPlaceholder() const {
111 return PlaceholderKind != 0;
113 bool isPlaceholder(BuiltinType::Kind K) const {
114 return PlaceholderKind == K;
117 void checkCastAlign() {
118 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
121 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
122 assert(Self.getLangOpts().ObjCAutoRefCount);
124 Expr *src = SrcExpr.get();
125 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127 IsARCUnbridgedCast = true;
131 /// Check for and handle non-overload placeholder expressions.
132 void checkNonOverloadPlaceholders() {
133 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
136 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
137 if (SrcExpr.isInvalid())
139 PlaceholderKind = (BuiltinType::Kind) 0;
144 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145 bool CheckCVR, bool CheckObjCLifetime);
147 // The Try functions attempt a specific way of casting. If they succeed, they
148 // return TC_Success. If their way of casting is not appropriate for the given
149 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
150 // to emit if no other way succeeds. If their way of casting is appropriate but
151 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
152 // they emit a specialized diagnostic.
153 // All diagnostics returned by these functions must expect the same three
155 // %0: Cast Type (a value from the CastType enumeration)
157 // %2: Destination Type
158 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
159 QualType DestType, bool CStyle,
161 CXXCastPath &BasePath,
163 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
164 QualType DestType, bool CStyle,
165 const SourceRange &OpRange,
168 CXXCastPath &BasePath);
169 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170 QualType DestType, bool CStyle,
171 const SourceRange &OpRange,
174 CXXCastPath &BasePath);
175 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176 CanQualType DestType, bool CStyle,
177 const SourceRange &OpRange,
178 QualType OrigSrcType,
179 QualType OrigDestType, unsigned &msg,
181 CXXCastPath &BasePath);
182 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
184 QualType DestType,bool CStyle,
185 const SourceRange &OpRange,
188 CXXCastPath &BasePath);
190 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
192 Sema::CheckedConversionKind CCK,
193 const SourceRange &OpRange,
194 unsigned &msg, CastKind &Kind,
195 bool ListInitialization);
196 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
198 Sema::CheckedConversionKind CCK,
199 const SourceRange &OpRange,
200 unsigned &msg, CastKind &Kind,
201 CXXCastPath &BasePath,
202 bool ListInitialization);
203 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
204 bool CStyle, unsigned &msg);
205 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
206 QualType DestType, bool CStyle,
207 const SourceRange &OpRange,
212 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
214 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
215 SourceLocation LAngleBracketLoc, Declarator &D,
216 SourceLocation RAngleBracketLoc,
217 SourceLocation LParenLoc, Expr *E,
218 SourceLocation RParenLoc) {
220 assert(!D.isInvalidType());
222 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
223 if (D.isInvalidType())
226 if (getLangOpts().CPlusPlus) {
227 // Check that there are no default arguments (C++ only).
228 CheckExtraCXXDefaultArguments(D);
231 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
232 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
233 SourceRange(LParenLoc, RParenLoc));
237 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
238 TypeSourceInfo *DestTInfo, Expr *E,
239 SourceRange AngleBrackets, SourceRange Parens) {
240 ExprResult Ex = Owned(E);
241 QualType DestType = DestTInfo->getType();
243 // If the type is dependent, we won't do the semantic analysis now.
244 // FIXME: should we check this in a more fine-grained manner?
245 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
247 CastOperation Op(*this, DestType, E);
248 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
249 Op.DestRange = AngleBrackets;
252 default: llvm_unreachable("Unknown C++ cast!");
254 case tok::kw_const_cast:
255 if (!TypeDependent) {
257 if (Op.SrcExpr.isInvalid())
260 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
261 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
262 OpLoc, Parens.getEnd(),
265 case tok::kw_dynamic_cast: {
266 if (!TypeDependent) {
267 Op.CheckDynamicCast();
268 if (Op.SrcExpr.isInvalid())
271 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
272 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
273 &Op.BasePath, DestTInfo,
274 OpLoc, Parens.getEnd(),
277 case tok::kw_reinterpret_cast: {
278 if (!TypeDependent) {
279 Op.CheckReinterpretCast();
280 if (Op.SrcExpr.isInvalid())
283 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
284 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
289 case tok::kw_static_cast: {
290 if (!TypeDependent) {
291 Op.CheckStaticCast();
292 if (Op.SrcExpr.isInvalid())
296 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
297 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
298 &Op.BasePath, DestTInfo,
299 OpLoc, Parens.getEnd(),
305 /// Try to diagnose a failed overloaded cast. Returns true if
306 /// diagnostics were emitted.
307 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
308 SourceRange range, Expr *src,
310 bool listInitialization) {
312 // These cast kinds don't consider user-defined conversions.
325 QualType srcType = src->getType();
326 if (!destType->isRecordType() && !srcType->isRecordType())
329 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
330 InitializationKind initKind
331 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
332 range, listInitialization)
333 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
335 : InitializationKind::CreateCast(/*type range?*/ range);
336 InitializationSequence sequence(S, entity, initKind, src);
338 assert(sequence.Failed() && "initialization succeeded on second try?");
339 switch (sequence.getFailureKind()) {
340 default: return false;
342 case InitializationSequence::FK_ConstructorOverloadFailed:
343 case InitializationSequence::FK_UserConversionOverloadFailed:
347 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
350 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
352 switch (sequence.getFailedOverloadResult()) {
353 case OR_Success: llvm_unreachable("successful failed overload");
354 case OR_No_Viable_Function:
355 if (candidates.empty())
356 msg = diag::err_ovl_no_conversion_in_cast;
358 msg = diag::err_ovl_no_viable_conversion_in_cast;
359 howManyCandidates = OCD_AllCandidates;
363 msg = diag::err_ovl_ambiguous_conversion_in_cast;
364 howManyCandidates = OCD_ViableCandidates;
368 msg = diag::err_ovl_deleted_conversion_in_cast;
369 howManyCandidates = OCD_ViableCandidates;
373 S.Diag(range.getBegin(), msg)
374 << CT << srcType << destType
375 << range << src->getSourceRange();
377 candidates.NoteCandidates(S, howManyCandidates, src);
382 /// Diagnose a failed cast.
383 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
384 SourceRange opRange, Expr *src, QualType destType,
385 bool listInitialization) {
386 if (src->getType() == S.Context.BoundMemberTy) {
387 (void) S.CheckPlaceholderExpr(src); // will always fail
391 if (msg == diag::err_bad_cxx_cast_generic &&
392 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
396 S.Diag(opRange.getBegin(), msg) << castType
397 << src->getType() << destType << opRange << src->getSourceRange();
400 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
401 /// this removes one level of indirection from both types, provided that they're
402 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
403 /// this one doesn't care if the two pointers-to-member don't point into the
404 /// same class. This is because CastsAwayConstness doesn't care.
405 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
406 const PointerType *T1PtrType = T1->getAs<PointerType>(),
407 *T2PtrType = T2->getAs<PointerType>();
408 if (T1PtrType && T2PtrType) {
409 T1 = T1PtrType->getPointeeType();
410 T2 = T2PtrType->getPointeeType();
413 const ObjCObjectPointerType *T1ObjCPtrType =
414 T1->getAs<ObjCObjectPointerType>(),
416 T2->getAs<ObjCObjectPointerType>();
419 T1 = T1ObjCPtrType->getPointeeType();
420 T2 = T2ObjCPtrType->getPointeeType();
423 else if (T2PtrType) {
424 T1 = T1ObjCPtrType->getPointeeType();
425 T2 = T2PtrType->getPointeeType();
429 else if (T2ObjCPtrType) {
431 T2 = T2ObjCPtrType->getPointeeType();
432 T1 = T1PtrType->getPointeeType();
437 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
438 *T2MPType = T2->getAs<MemberPointerType>();
439 if (T1MPType && T2MPType) {
440 T1 = T1MPType->getPointeeType();
441 T2 = T2MPType->getPointeeType();
445 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
446 *T2BPType = T2->getAs<BlockPointerType>();
447 if (T1BPType && T2BPType) {
448 T1 = T1BPType->getPointeeType();
449 T2 = T2BPType->getPointeeType();
456 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
457 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
458 /// the cast checkers. Both arguments must denote pointer (possibly to member)
461 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
463 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
465 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
466 bool CheckCVR, bool CheckObjCLifetime) {
467 // If the only checking we care about is for Objective-C lifetime qualifiers,
468 // and we're not in ARC mode, there's nothing to check.
469 if (!CheckCVR && CheckObjCLifetime &&
470 !Self.Context.getLangOpts().ObjCAutoRefCount)
473 // Casting away constness is defined in C++ 5.2.11p8 with reference to
474 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
475 // the rules are non-trivial. So first we construct Tcv *...cv* as described
477 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
478 SrcType->isBlockPointerType()) &&
479 "Source type is not pointer or pointer to member.");
480 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
481 DestType->isBlockPointerType()) &&
482 "Destination type is not pointer or pointer to member.");
484 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
485 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
486 SmallVector<Qualifiers, 8> cv1, cv2;
488 // Find the qualifiers. We only care about cvr-qualifiers for the
489 // purpose of this check, because other qualifiers (address spaces,
490 // Objective-C GC, etc.) are part of the type's identity.
491 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
492 // Determine the relevant qualifiers at this level.
493 Qualifiers SrcQuals, DestQuals;
494 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
495 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
497 Qualifiers RetainedSrcQuals, RetainedDestQuals;
499 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
500 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
503 if (CheckObjCLifetime &&
504 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
507 cv1.push_back(RetainedSrcQuals);
508 cv2.push_back(RetainedDestQuals);
513 // Construct void pointers with those qualifiers (in reverse order of
514 // unwrapping, of course).
515 QualType SrcConstruct = Self.Context.VoidTy;
516 QualType DestConstruct = Self.Context.VoidTy;
517 ASTContext &Context = Self.Context;
518 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
520 i1 != cv1.rend(); ++i1, ++i2) {
522 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
524 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
527 // Test if they're compatible.
528 bool ObjCLifetimeConversion;
529 return SrcConstruct != DestConstruct &&
530 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
531 ObjCLifetimeConversion);
534 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
535 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
536 /// checked downcasts in class hierarchies.
537 void CastOperation::CheckDynamicCast() {
538 if (ValueKind == VK_RValue)
539 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
540 else if (isPlaceholder())
541 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
542 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
545 QualType OrigSrcType = SrcExpr.get()->getType();
546 QualType DestType = Self.Context.getCanonicalType(this->DestType);
548 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
549 // or "pointer to cv void".
551 QualType DestPointee;
552 const PointerType *DestPointer = DestType->getAs<PointerType>();
553 const ReferenceType *DestReference = 0;
555 DestPointee = DestPointer->getPointeeType();
556 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
557 DestPointee = DestReference->getPointeeType();
559 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
560 << this->DestType << DestRange;
564 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
565 if (DestPointee->isVoidType()) {
566 assert(DestPointer && "Reference to void is not possible");
567 } else if (DestRecord) {
568 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
569 diag::err_bad_dynamic_cast_incomplete,
573 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
574 << DestPointee.getUnqualifiedType() << DestRange;
578 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
579 // complete class type, [...]. If T is an lvalue reference type, v shall be
580 // an lvalue of a complete class type, [...]. If T is an rvalue reference
581 // type, v shall be an expression having a complete class type, [...]
582 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
585 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
586 SrcPointee = SrcPointer->getPointeeType();
588 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
589 << OrigSrcType << SrcExpr.get()->getSourceRange();
592 } else if (DestReference->isLValueReferenceType()) {
593 if (!SrcExpr.get()->isLValue()) {
594 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
595 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
597 SrcPointee = SrcType;
599 SrcPointee = SrcType;
602 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
604 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
605 diag::err_bad_dynamic_cast_incomplete,
609 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
610 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
614 assert((DestPointer || DestReference) &&
615 "Bad destination non-ptr/ref slipped through.");
616 assert((DestRecord || DestPointee->isVoidType()) &&
617 "Bad destination pointee slipped through.");
618 assert(SrcRecord && "Bad source pointee slipped through.");
620 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
621 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
622 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
623 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
627 // C++ 5.2.7p3: If the type of v is the same as the required result type,
629 if (DestRecord == SrcRecord) {
635 // Upcasts are resolved statically.
636 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
637 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
638 OpRange.getBegin(), OpRange,
642 Kind = CK_DerivedToBase;
644 // If we are casting to or through a virtual base class, we need a
646 if (Self.BasePathInvolvesVirtualBase(BasePath))
647 Self.MarkVTableUsed(OpRange.getBegin(),
648 cast<CXXRecordDecl>(SrcRecord->getDecl()));
652 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
653 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
654 assert(SrcDecl && "Definition missing");
655 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
656 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
657 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
659 Self.MarkVTableUsed(OpRange.getBegin(),
660 cast<CXXRecordDecl>(SrcRecord->getDecl()));
662 // Done. Everything else is run-time checks.
666 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
667 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
669 /// const char *str = "literal";
670 /// legacy_function(const_cast\<char*\>(str));
671 void CastOperation::CheckConstCast() {
672 if (ValueKind == VK_RValue)
673 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
674 else if (isPlaceholder())
675 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
676 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
679 unsigned msg = diag::err_bad_cxx_cast_generic;
680 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
682 Self.Diag(OpRange.getBegin(), msg) << CT_Const
683 << SrcExpr.get()->getType() << DestType << OpRange;
686 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
687 /// or downcast between respective pointers or references.
688 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
690 SourceRange OpRange) {
691 QualType SrcType = SrcExpr->getType();
692 // When casting from pointer or reference, get pointee type; use original
694 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
695 const CXXRecordDecl *SrcRD =
696 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
698 // Examining subobjects for records is only possible if the complete and
699 // valid definition is available. Also, template instantiation is not
701 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
704 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
706 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
714 CXXBasePaths BasePaths;
716 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
717 ReinterpretKind = ReinterpretUpcast;
718 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
719 ReinterpretKind = ReinterpretDowncast;
723 bool VirtualBase = true;
724 bool NonZeroOffset = false;
725 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
728 const CXXBasePath &Path = *I;
729 CharUnits Offset = CharUnits::Zero();
730 bool IsVirtual = false;
731 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
732 IElem != EElem; ++IElem) {
733 IsVirtual = IElem->Base->isVirtual();
736 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
737 assert(BaseRD && "Base type should be a valid unqualified class type");
738 // Don't check if any base has invalid declaration or has no definition
739 // since it has no layout info.
740 const CXXRecordDecl *Class = IElem->Class,
741 *ClassDefinition = Class->getDefinition();
742 if (Class->isInvalidDecl() || !ClassDefinition ||
743 !ClassDefinition->isCompleteDefinition())
746 const ASTRecordLayout &DerivedLayout =
747 Self.Context.getASTRecordLayout(Class);
748 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
751 // Don't warn if any path is a non-virtually derived base at offset zero.
754 // Offset makes sense only for non-virtual bases.
756 NonZeroOffset = true;
758 VirtualBase = VirtualBase && IsVirtual;
761 assert((VirtualBase || NonZeroOffset) &&
762 "Should have returned if has non-virtual base with zero offset");
765 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
766 QualType DerivedType =
767 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
769 SourceLocation BeginLoc = OpRange.getBegin();
770 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
771 << DerivedType << BaseType << !VirtualBase << ReinterpretKind
773 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
775 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
778 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
780 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
782 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
783 void CastOperation::CheckReinterpretCast() {
784 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
785 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
787 checkNonOverloadPlaceholders();
788 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
791 unsigned msg = diag::err_bad_cxx_cast_generic;
793 TryReinterpretCast(Self, SrcExpr, DestType,
794 /*CStyle*/false, OpRange, msg, Kind);
795 if (tcr != TC_Success && msg != 0)
797 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
799 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
800 //FIXME: &f<int>; is overloaded and resolvable
801 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
802 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
803 << DestType << OpRange;
804 Self.NoteAllOverloadCandidates(SrcExpr.get());
807 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
808 DestType, /*listInitialization=*/false);
810 } else if (tcr == TC_Success) {
811 if (Self.getLangOpts().ObjCAutoRefCount)
812 checkObjCARCConversion(Sema::CCK_OtherCast);
813 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
818 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
819 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
820 /// implicit conversions explicit and getting rid of data loss warnings.
821 void CastOperation::CheckStaticCast() {
822 if (isPlaceholder()) {
823 checkNonOverloadPlaceholders();
824 if (SrcExpr.isInvalid())
828 // This test is outside everything else because it's the only case where
829 // a non-lvalue-reference target type does not lead to decay.
830 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
831 if (DestType->isVoidType()) {
834 if (claimPlaceholder(BuiltinType::Overload)) {
835 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
836 false, // Decay Function to ptr
838 OpRange, DestType, diag::err_bad_static_cast_overload);
839 if (SrcExpr.isInvalid())
843 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
847 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
848 !isPlaceholder(BuiltinType::Overload)) {
849 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
850 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
854 unsigned msg = diag::err_bad_cxx_cast_generic;
856 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
857 Kind, BasePath, /*ListInitialization=*/false);
858 if (tcr != TC_Success && msg != 0) {
859 if (SrcExpr.isInvalid())
861 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
862 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
863 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
864 << oe->getName() << DestType << OpRange
865 << oe->getQualifierLoc().getSourceRange();
866 Self.NoteAllOverloadCandidates(SrcExpr.get());
868 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
869 /*listInitialization=*/false);
871 } else if (tcr == TC_Success) {
872 if (Kind == CK_BitCast)
874 if (Self.getLangOpts().ObjCAutoRefCount)
875 checkObjCARCConversion(Sema::CCK_OtherCast);
876 } else if (Kind == CK_BitCast) {
881 /// TryStaticCast - Check if a static cast can be performed, and do so if
882 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
883 /// and casting away constness.
884 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
886 Sema::CheckedConversionKind CCK,
887 const SourceRange &OpRange, unsigned &msg,
888 CastKind &Kind, CXXCastPath &BasePath,
889 bool ListInitialization) {
890 // Determine whether we have the semantics of a C-style cast.
892 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
894 // The order the tests is not entirely arbitrary. There is one conversion
895 // that can be handled in two different ways. Given:
897 // struct B : public A {
901 // the cast static_cast<const B&>(a) could be seen as either a static
902 // reference downcast, or an explicit invocation of the user-defined
903 // conversion using B's conversion constructor.
904 // DR 427 specifies that the downcast is to be applied here.
906 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
907 // Done outside this function.
911 // C++ 5.2.9p5, reference downcast.
912 // See the function for details.
913 // DR 427 specifies that this is to be applied before paragraph 2.
914 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
915 OpRange, msg, Kind, BasePath);
916 if (tcr != TC_NotApplicable)
919 // C++0x [expr.static.cast]p3:
920 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
921 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
922 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
924 if (tcr != TC_NotApplicable)
927 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
928 // [...] if the declaration "T t(e);" is well-formed, [...].
929 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
930 Kind, ListInitialization);
931 if (SrcExpr.isInvalid())
933 if (tcr != TC_NotApplicable)
936 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
937 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
938 // conversions, subject to further restrictions.
939 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
940 // of qualification conversions impossible.
941 // In the CStyle case, the earlier attempt to const_cast should have taken
942 // care of reverse qualification conversions.
944 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
946 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
947 // converted to an integral type. [...] A value of a scoped enumeration type
948 // can also be explicitly converted to a floating-point type [...].
949 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
950 if (Enum->getDecl()->isScoped()) {
951 if (DestType->isBooleanType()) {
952 Kind = CK_IntegralToBoolean;
954 } else if (DestType->isIntegralType(Self.Context)) {
955 Kind = CK_IntegralCast;
957 } else if (DestType->isRealFloatingType()) {
958 Kind = CK_IntegralToFloating;
964 // Reverse integral promotion/conversion. All such conversions are themselves
965 // again integral promotions or conversions and are thus already handled by
966 // p2 (TryDirectInitialization above).
967 // (Note: any data loss warnings should be suppressed.)
968 // The exception is the reverse of enum->integer, i.e. integer->enum (and
969 // enum->enum). See also C++ 5.2.9p7.
970 // The same goes for reverse floating point promotion/conversion and
971 // floating-integral conversions. Again, only floating->enum is relevant.
972 if (DestType->isEnumeralType()) {
973 if (SrcType->isIntegralOrEnumerationType()) {
974 Kind = CK_IntegralCast;
976 } else if (SrcType->isRealFloatingType()) {
977 Kind = CK_FloatingToIntegral;
982 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
983 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
984 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
986 if (tcr != TC_NotApplicable)
989 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
990 // conversion. C++ 5.2.9p9 has additional information.
991 // DR54's access restrictions apply here also.
992 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
993 OpRange, msg, Kind, BasePath);
994 if (tcr != TC_NotApplicable)
997 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
998 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
999 // just the usual constness stuff.
1000 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1001 QualType SrcPointee = SrcPointer->getPointeeType();
1002 if (SrcPointee->isVoidType()) {
1003 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1004 QualType DestPointee = DestPointer->getPointeeType();
1005 if (DestPointee->isIncompleteOrObjectType()) {
1006 // This is definitely the intended conversion, but it might fail due
1007 // to a qualifier violation. Note that we permit Objective-C lifetime
1008 // and GC qualifier mismatches here.
1010 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1011 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1012 DestPointeeQuals.removeObjCGCAttr();
1013 DestPointeeQuals.removeObjCLifetime();
1014 SrcPointeeQuals.removeObjCGCAttr();
1015 SrcPointeeQuals.removeObjCLifetime();
1016 if (DestPointeeQuals != SrcPointeeQuals &&
1017 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1018 msg = diag::err_bad_cxx_cast_qualifiers_away;
1026 else if (DestType->isObjCObjectPointerType()) {
1027 // allow both c-style cast and static_cast of objective-c pointers as
1028 // they are pervasive.
1029 Kind = CK_CPointerToObjCPointerCast;
1032 else if (CStyle && DestType->isBlockPointerType()) {
1033 // allow c-style cast of void * to block pointers.
1034 Kind = CK_AnyPointerToBlockPointerCast;
1039 // Allow arbitray objective-c pointer conversion with static casts.
1040 if (SrcType->isObjCObjectPointerType() &&
1041 DestType->isObjCObjectPointerType()) {
1046 // We tried everything. Everything! Nothing works! :-(
1047 return TC_NotApplicable;
1050 /// Tests whether a conversion according to N2844 is valid.
1052 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1053 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1055 // C++0x [expr.static.cast]p3:
1056 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1057 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1058 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1060 return TC_NotApplicable;
1062 if (!SrcExpr->isGLValue())
1063 return TC_NotApplicable;
1065 // Because we try the reference downcast before this function, from now on
1066 // this is the only cast possibility, so we issue an error if we fail now.
1067 // FIXME: Should allow casting away constness if CStyle.
1069 bool ObjCConversion;
1070 bool ObjCLifetimeConversion;
1071 QualType FromType = SrcExpr->getType();
1072 QualType ToType = R->getPointeeType();
1074 FromType = FromType.getUnqualifiedType();
1075 ToType = ToType.getUnqualifiedType();
1078 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
1080 DerivedToBase, ObjCConversion,
1081 ObjCLifetimeConversion)
1082 < Sema::Ref_Compatible_With_Added_Qualification) {
1083 msg = diag::err_bad_lvalue_to_rvalue_cast;
1087 if (DerivedToBase) {
1088 Kind = CK_DerivedToBase;
1089 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1090 /*DetectVirtual=*/true);
1091 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1092 return TC_NotApplicable;
1094 Self.BuildBasePathArray(Paths, BasePath);
1101 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1103 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1104 bool CStyle, const SourceRange &OpRange,
1105 unsigned &msg, CastKind &Kind,
1106 CXXCastPath &BasePath) {
1107 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1108 // cast to type "reference to cv2 D", where D is a class derived from B,
1109 // if a valid standard conversion from "pointer to D" to "pointer to B"
1110 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1111 // In addition, DR54 clarifies that the base must be accessible in the
1112 // current context. Although the wording of DR54 only applies to the pointer
1113 // variant of this rule, the intent is clearly for it to apply to the this
1114 // conversion as well.
1116 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1117 if (!DestReference) {
1118 return TC_NotApplicable;
1120 bool RValueRef = DestReference->isRValueReferenceType();
1121 if (!RValueRef && !SrcExpr->isLValue()) {
1122 // We know the left side is an lvalue reference, so we can suggest a reason.
1123 msg = diag::err_bad_cxx_cast_rvalue;
1124 return TC_NotApplicable;
1127 QualType DestPointee = DestReference->getPointeeType();
1129 return TryStaticDowncast(Self,
1130 Self.Context.getCanonicalType(SrcExpr->getType()),
1131 Self.Context.getCanonicalType(DestPointee), CStyle,
1132 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1136 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1138 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1139 bool CStyle, const SourceRange &OpRange,
1140 unsigned &msg, CastKind &Kind,
1141 CXXCastPath &BasePath) {
1142 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1143 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1144 // is a class derived from B, if a valid standard conversion from "pointer
1145 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1147 // In addition, DR54 clarifies that the base must be accessible in the
1150 const PointerType *DestPointer = DestType->getAs<PointerType>();
1152 return TC_NotApplicable;
1155 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1157 msg = diag::err_bad_static_cast_pointer_nonpointer;
1158 return TC_NotApplicable;
1161 return TryStaticDowncast(Self,
1162 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1163 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1164 CStyle, OpRange, SrcType, DestType, msg, Kind,
1168 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1169 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1170 /// DestType is possible and allowed.
1172 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1173 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
1174 QualType OrigDestType, unsigned &msg,
1175 CastKind &Kind, CXXCastPath &BasePath) {
1176 // We can only work with complete types. But don't complain if it doesn't work
1177 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1178 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
1179 return TC_NotApplicable;
1181 // Downcast can only happen in class hierarchies, so we need classes.
1182 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1183 return TC_NotApplicable;
1186 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1187 /*DetectVirtual=*/true);
1188 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1189 return TC_NotApplicable;
1192 // Target type does derive from source type. Now we're serious. If an error
1193 // appears now, it's not ignored.
1194 // This may not be entirely in line with the standard. Take for example:
1196 // struct B : virtual A {
1202 // (void)static_cast<const B&>(*((A*)0));
1204 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1205 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1206 // However, both GCC and Comeau reject this example, and accepting it would
1207 // mean more complex code if we're to preserve the nice error message.
1208 // FIXME: Being 100% compliant here would be nice to have.
1210 // Must preserve cv, as always, unless we're in C-style mode.
1211 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1212 msg = diag::err_bad_cxx_cast_qualifiers_away;
1216 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1217 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1218 // that it builds the paths in reverse order.
1219 // To sum up: record all paths to the base and build a nice string from
1220 // them. Use it to spice up the error message.
1221 if (!Paths.isRecordingPaths()) {
1223 Paths.setRecordingPaths(true);
1224 Self.IsDerivedFrom(DestType, SrcType, Paths);
1226 std::string PathDisplayStr;
1227 std::set<unsigned> DisplayedPaths;
1228 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
1230 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1231 // We haven't displayed a path to this particular base
1232 // class subobject yet.
1233 PathDisplayStr += "\n ";
1234 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1237 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
1238 PathDisplayStr += QualType(DestType).getAsString();
1242 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1243 << QualType(SrcType).getUnqualifiedType()
1244 << QualType(DestType).getUnqualifiedType()
1245 << PathDisplayStr << OpRange;
1250 if (Paths.getDetectedVirtual() != 0) {
1251 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1252 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1253 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1259 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1262 diag::err_downcast_from_inaccessible_base)) {
1263 case Sema::AR_accessible:
1264 case Sema::AR_delayed: // be optimistic
1265 case Sema::AR_dependent: // be optimistic
1268 case Sema::AR_inaccessible:
1274 Self.BuildBasePathArray(Paths, BasePath);
1275 Kind = CK_BaseToDerived;
1279 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1280 /// C++ 5.2.9p9 is valid:
1282 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1283 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1284 /// where B is a base class of D [...].
1287 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1288 QualType DestType, bool CStyle,
1289 const SourceRange &OpRange,
1290 unsigned &msg, CastKind &Kind,
1291 CXXCastPath &BasePath) {
1292 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1294 return TC_NotApplicable;
1296 bool WasOverloadedFunction = false;
1297 DeclAccessPair FoundOverload;
1298 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1299 if (FunctionDecl *Fn
1300 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1302 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1303 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1304 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1305 WasOverloadedFunction = true;
1309 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1311 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1312 return TC_NotApplicable;
1315 // T == T, modulo cv
1316 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1317 DestMemPtr->getPointeeType()))
1318 return TC_NotApplicable;
1321 QualType SrcClass(SrcMemPtr->getClass(), 0);
1322 QualType DestClass(DestMemPtr->getClass(), 0);
1323 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1324 /*DetectVirtual=*/true);
1325 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1326 return TC_NotApplicable;
1329 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1330 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1332 Paths.setRecordingPaths(true);
1333 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1336 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1337 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1338 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1343 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1344 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1345 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1351 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1352 DestClass, SrcClass,
1354 diag::err_upcast_to_inaccessible_base)) {
1355 case Sema::AR_accessible:
1356 case Sema::AR_delayed:
1357 case Sema::AR_dependent:
1358 // Optimistically assume that the delayed and dependent cases
1362 case Sema::AR_inaccessible:
1368 if (WasOverloadedFunction) {
1369 // Resolve the address of the overloaded function again, this time
1370 // allowing complaints if something goes wrong.
1371 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1380 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1381 if (!SrcExpr.isUsable()) {
1387 Self.BuildBasePathArray(Paths, BasePath);
1388 Kind = CK_DerivedToBaseMemberPointer;
1392 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1395 /// An expression e can be explicitly converted to a type T using a
1396 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1398 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1399 Sema::CheckedConversionKind CCK,
1400 const SourceRange &OpRange, unsigned &msg,
1401 CastKind &Kind, bool ListInitialization) {
1402 if (DestType->isRecordType()) {
1403 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1404 diag::err_bad_dynamic_cast_incomplete) ||
1405 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1406 diag::err_allocation_of_abstract_type)) {
1412 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1413 InitializationKind InitKind
1414 = (CCK == Sema::CCK_CStyleCast)
1415 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1417 : (CCK == Sema::CCK_FunctionalCast)
1418 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1419 : InitializationKind::CreateCast(OpRange);
1420 Expr *SrcExprRaw = SrcExpr.get();
1421 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1423 // At this point of CheckStaticCast, if the destination is a reference,
1424 // or the expression is an overload expression this has to work.
1425 // There is no other way that works.
1426 // On the other hand, if we're checking a C-style cast, we've still got
1427 // the reinterpret_cast way.
1429 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1430 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1431 return TC_NotApplicable;
1433 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1434 if (Result.isInvalid()) {
1439 if (InitSeq.isConstructorInitialization())
1440 Kind = CK_ConstructorConversion;
1448 /// TryConstCast - See if a const_cast from source to destination is allowed,
1449 /// and perform it if it is.
1450 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1451 bool CStyle, unsigned &msg) {
1452 DestType = Self.Context.getCanonicalType(DestType);
1453 QualType SrcType = SrcExpr->getType();
1454 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1455 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr->isLValue()) {
1456 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1457 // is C-style, static_cast might find a way, so we simply suggest a
1458 // message and tell the parent to keep searching.
1459 msg = diag::err_bad_cxx_cast_rvalue;
1460 return TC_NotApplicable;
1463 // It's not completely clear under the standard whether we can
1464 // const_cast bit-field gl-values. Doing so would not be
1465 // intrinsically complicated, but for now, we say no for
1466 // consistency with other compilers and await the word of the
1468 if (SrcExpr->refersToBitField()) {
1469 msg = diag::err_bad_cxx_cast_bitfield;
1470 return TC_NotApplicable;
1473 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1474 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1475 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1476 SrcType = Self.Context.getPointerType(SrcType);
1479 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1480 // the rules for const_cast are the same as those used for pointers.
1482 if (!DestType->isPointerType() &&
1483 !DestType->isMemberPointerType() &&
1484 !DestType->isObjCObjectPointerType()) {
1485 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1486 // was a reference type, we converted it to a pointer above.
1487 // The status of rvalue references isn't entirely clear, but it looks like
1488 // conversion to them is simply invalid.
1489 // C++ 5.2.11p3: For two pointer types [...]
1491 msg = diag::err_bad_const_cast_dest;
1492 return TC_NotApplicable;
1494 if (DestType->isFunctionPointerType() ||
1495 DestType->isMemberFunctionPointerType()) {
1496 // Cannot cast direct function pointers.
1497 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1498 // T is the ultimate pointee of source and target type.
1500 msg = diag::err_bad_const_cast_dest;
1501 return TC_NotApplicable;
1503 SrcType = Self.Context.getCanonicalType(SrcType);
1505 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1506 // completely equal.
1507 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1508 // in multi-level pointers may change, but the level count must be the same,
1509 // as must be the final pointee type.
1510 while (SrcType != DestType &&
1511 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1512 Qualifiers SrcQuals, DestQuals;
1513 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1514 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1516 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1517 // the other qualifiers (e.g., address spaces) are identical.
1518 SrcQuals.removeCVRQualifiers();
1519 DestQuals.removeCVRQualifiers();
1520 if (SrcQuals != DestQuals)
1521 return TC_NotApplicable;
1524 // Since we're dealing in canonical types, the remainder must be the same.
1525 if (SrcType != DestType)
1526 return TC_NotApplicable;
1531 // Checks for undefined behavior in reinterpret_cast.
1532 // The cases that is checked for is:
1533 // *reinterpret_cast<T*>(&a)
1534 // reinterpret_cast<T&>(a)
1535 // where accessing 'a' as type 'T' will result in undefined behavior.
1536 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1538 SourceRange Range) {
1539 unsigned DiagID = IsDereference ?
1540 diag::warn_pointer_indirection_from_incompatible_type :
1541 diag::warn_undefined_reinterpret_cast;
1543 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
1544 DiagnosticsEngine::Ignored) {
1548 QualType SrcTy, DestTy;
1549 if (IsDereference) {
1550 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1553 SrcTy = SrcType->getPointeeType();
1554 DestTy = DestType->getPointeeType();
1556 if (!DestType->getAs<ReferenceType>()) {
1560 DestTy = DestType->getPointeeType();
1563 // Cast is compatible if the types are the same.
1564 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1567 // or one of the types is a char or void type
1568 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1569 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1572 // or one of the types is a tag type.
1573 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1577 // FIXME: Scoped enums?
1578 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1579 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1580 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1585 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1588 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1589 QualType DestType) {
1590 QualType SrcType = SrcExpr.get()->getType();
1591 if (Self.Context.hasSameType(SrcType, DestType))
1593 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1594 if (SrcPtrTy->isObjCSelType()) {
1595 QualType DT = DestType;
1596 if (isa<PointerType>(DestType))
1597 DT = DestType->getPointeeType();
1598 if (!DT.getUnqualifiedType()->isVoidType())
1599 Self.Diag(SrcExpr.get()->getExprLoc(),
1600 diag::warn_cast_pointer_from_sel)
1601 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1605 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1606 const Expr *SrcExpr, QualType DestType,
1608 QualType SrcType = SrcExpr->getType();
1610 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1611 // are not explicit design choices, but consistent with GCC's behavior.
1612 // Feel free to modify them if you've reason/evidence for an alternative.
1613 if (CStyle && SrcType->isIntegralType(Self.Context)
1614 && !SrcType->isBooleanType()
1615 && !SrcType->isEnumeralType()
1616 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1617 && Self.Context.getTypeSize(DestType) > Self.Context.getTypeSize(SrcType))
1618 Self.Diag(Loc, diag::warn_int_to_pointer_cast) << SrcType << DestType;
1621 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1622 QualType DestType, bool CStyle,
1623 const SourceRange &OpRange,
1626 bool IsLValueCast = false;
1628 DestType = Self.Context.getCanonicalType(DestType);
1629 QualType SrcType = SrcExpr.get()->getType();
1631 // Is the source an overloaded name? (i.e. &foo)
1632 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1633 if (SrcType == Self.Context.OverloadTy) {
1634 // ... unless foo<int> resolves to an lvalue unambiguously.
1635 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1637 ExprResult SingleFunctionExpr = SrcExpr;
1638 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1640 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1641 ) && SingleFunctionExpr.isUsable()) {
1642 SrcExpr = SingleFunctionExpr;
1643 SrcType = SrcExpr.get()->getType();
1645 return TC_NotApplicable;
1649 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1650 if (!SrcExpr.get()->isGLValue()) {
1651 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1652 // similar comment in const_cast.
1653 msg = diag::err_bad_cxx_cast_rvalue;
1654 return TC_NotApplicable;
1658 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1659 /*isDereference=*/false, OpRange);
1662 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1663 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1664 // built-in & and * operators.
1666 const char *inappropriate = 0;
1667 switch (SrcExpr.get()->getObjectKind()) {
1670 case OK_BitField: inappropriate = "bit-field"; break;
1671 case OK_VectorComponent: inappropriate = "vector element"; break;
1672 case OK_ObjCProperty: inappropriate = "property expression"; break;
1673 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1676 if (inappropriate) {
1677 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1678 << inappropriate << DestType
1679 << OpRange << SrcExpr.get()->getSourceRange();
1680 msg = 0; SrcExpr = ExprError();
1681 return TC_NotApplicable;
1684 // This code does this transformation for the checked types.
1685 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1686 SrcType = Self.Context.getPointerType(SrcType);
1688 IsLValueCast = true;
1691 // Canonicalize source for comparison.
1692 SrcType = Self.Context.getCanonicalType(SrcType);
1694 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1695 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1696 if (DestMemPtr && SrcMemPtr) {
1697 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1698 // can be explicitly converted to an rvalue of type "pointer to member
1699 // of Y of type T2" if T1 and T2 are both function types or both object
1701 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1702 SrcMemPtr->getPointeeType()->isFunctionType())
1703 return TC_NotApplicable;
1705 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1707 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1709 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1710 /*CheckObjCLifetime=*/CStyle)) {
1711 msg = diag::err_bad_cxx_cast_qualifiers_away;
1715 // Don't allow casting between member pointers of different sizes.
1716 if (Self.Context.getTypeSize(DestMemPtr) !=
1717 Self.Context.getTypeSize(SrcMemPtr)) {
1718 msg = diag::err_bad_cxx_cast_member_pointer_size;
1722 // A valid member pointer cast.
1723 assert(!IsLValueCast);
1724 Kind = CK_ReinterpretMemberPointer;
1728 // See below for the enumeral issue.
1729 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1730 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1731 // type large enough to hold it. A value of std::nullptr_t can be
1732 // converted to an integral type; the conversion has the same meaning
1733 // and validity as a conversion of (void*)0 to the integral type.
1734 if (Self.Context.getTypeSize(SrcType) >
1735 Self.Context.getTypeSize(DestType)) {
1736 msg = diag::err_bad_reinterpret_cast_small_int;
1739 Kind = CK_PointerToIntegral;
1743 bool destIsVector = DestType->isVectorType();
1744 bool srcIsVector = SrcType->isVectorType();
1745 if (srcIsVector || destIsVector) {
1746 // FIXME: Should this also apply to floating point types?
1747 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1748 bool destIsScalar = DestType->isIntegralType(Self.Context);
1750 // Check if this is a cast between a vector and something else.
1751 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1752 !(srcIsVector && destIsVector))
1753 return TC_NotApplicable;
1755 // If both types have the same size, we can successfully cast.
1756 if (Self.Context.getTypeSize(SrcType)
1757 == Self.Context.getTypeSize(DestType)) {
1763 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1764 else if (srcIsScalar)
1765 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1767 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1772 if (SrcType == DestType) {
1773 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1774 // restrictions, a cast to the same type is allowed so long as it does not
1775 // cast away constness. In C++98, the intent was not entirely clear here,
1776 // since all other paragraphs explicitly forbid casts to the same type.
1777 // C++11 clarifies this case with p2.
1779 // The only allowed types are: integral, enumeration, pointer, or
1780 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1782 TryCastResult Result = TC_NotApplicable;
1783 if (SrcType->isIntegralOrEnumerationType() ||
1784 SrcType->isAnyPointerType() ||
1785 SrcType->isMemberPointerType() ||
1786 SrcType->isBlockPointerType()) {
1787 Result = TC_Success;
1792 bool destIsPtr = DestType->isAnyPointerType() ||
1793 DestType->isBlockPointerType();
1794 bool srcIsPtr = SrcType->isAnyPointerType() ||
1795 SrcType->isBlockPointerType();
1796 if (!destIsPtr && !srcIsPtr) {
1797 // Except for std::nullptr_t->integer and lvalue->reference, which are
1798 // handled above, at least one of the two arguments must be a pointer.
1799 return TC_NotApplicable;
1802 if (DestType->isIntegralType(Self.Context)) {
1803 assert(srcIsPtr && "One type must be a pointer");
1804 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1805 // type large enough to hold it; except in Microsoft mode, where the
1806 // integral type size doesn't matter.
1807 if ((Self.Context.getTypeSize(SrcType) >
1808 Self.Context.getTypeSize(DestType)) &&
1809 !Self.getLangOpts().MicrosoftExt) {
1810 msg = diag::err_bad_reinterpret_cast_small_int;
1813 Kind = CK_PointerToIntegral;
1817 if (SrcType->isIntegralOrEnumerationType()) {
1818 assert(destIsPtr && "One type must be a pointer");
1819 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1821 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1822 // converted to a pointer.
1823 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1824 // necessarily converted to a null pointer value.]
1825 Kind = CK_IntegralToPointer;
1829 if (!destIsPtr || !srcIsPtr) {
1830 // With the valid non-pointer conversions out of the way, we can be even
1832 return TC_NotApplicable;
1835 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1836 // The C-style cast operator can.
1837 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1838 /*CheckObjCLifetime=*/CStyle)) {
1839 msg = diag::err_bad_cxx_cast_qualifiers_away;
1843 // Cannot convert between block pointers and Objective-C object pointers.
1844 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1845 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1846 return TC_NotApplicable;
1849 Kind = CK_LValueBitCast;
1850 } else if (DestType->isObjCObjectPointerType()) {
1851 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
1852 } else if (DestType->isBlockPointerType()) {
1853 if (!SrcType->isBlockPointerType()) {
1854 Kind = CK_AnyPointerToBlockPointerCast;
1862 // Any pointer can be cast to an Objective-C pointer type with a C-style
1864 if (CStyle && DestType->isObjCObjectPointerType()) {
1868 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1870 // Not casting away constness, so the only remaining check is for compatible
1871 // pointer categories.
1873 if (SrcType->isFunctionPointerType()) {
1874 if (DestType->isFunctionPointerType()) {
1875 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1876 // a pointer to a function of a different type.
1880 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1881 // an object type or vice versa is conditionally-supported.
1882 // Compilers support it in C++03 too, though, because it's necessary for
1883 // casting the return value of dlsym() and GetProcAddress().
1884 // FIXME: Conditionally-supported behavior should be configurable in the
1885 // TargetInfo or similar.
1886 Self.Diag(OpRange.getBegin(),
1887 Self.getLangOpts().CPlusPlus11 ?
1888 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1893 if (DestType->isFunctionPointerType()) {
1895 Self.Diag(OpRange.getBegin(),
1896 Self.getLangOpts().CPlusPlus11 ?
1897 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1902 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1903 // a pointer to an object of different type.
1904 // Void pointers are not specified, but supported by every compiler out there.
1905 // So we finish by allowing everything that remains - it's got to be two
1910 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1911 bool ListInitialization) {
1912 // Handle placeholders.
1913 if (isPlaceholder()) {
1914 // C-style casts can resolve __unknown_any types.
1915 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1916 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1917 SrcExpr.get(), Kind,
1918 ValueKind, BasePath);
1922 checkNonOverloadPlaceholders();
1923 if (SrcExpr.isInvalid())
1927 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1928 // This test is outside everything else because it's the only case where
1929 // a non-lvalue-reference target type does not lead to decay.
1930 if (DestType->isVoidType()) {
1933 if (claimPlaceholder(BuiltinType::Overload)) {
1934 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1935 SrcExpr, /* Decay Function to ptr */ false,
1936 /* Complain */ true, DestRange, DestType,
1937 diag::err_bad_cstyle_cast_overload);
1938 if (SrcExpr.isInvalid())
1942 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1943 if (SrcExpr.isInvalid())
1949 // If the type is dependent, we won't do any other semantic analysis now.
1950 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1951 assert(Kind == CK_Dependent);
1955 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1956 !isPlaceholder(BuiltinType::Overload)) {
1957 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1958 if (SrcExpr.isInvalid())
1962 // AltiVec vector initialization with a single literal.
1963 if (const VectorType *vecTy = DestType->getAs<VectorType>())
1964 if (vecTy->getVectorKind() == VectorType::AltiVecVector
1965 && (SrcExpr.get()->getType()->isIntegerType()
1966 || SrcExpr.get()->getType()->isFloatingType())) {
1967 Kind = CK_VectorSplat;
1971 // C++ [expr.cast]p5: The conversions performed by
1974 // - a static_cast followed by a const_cast,
1975 // - a reinterpret_cast, or
1976 // - a reinterpret_cast followed by a const_cast,
1977 // can be performed using the cast notation of explicit type conversion.
1978 // [...] If a conversion can be interpreted in more than one of the ways
1979 // listed above, the interpretation that appears first in the list is used,
1980 // even if a cast resulting from that interpretation is ill-formed.
1981 // In plain language, this means trying a const_cast ...
1982 unsigned msg = diag::err_bad_cxx_cast_generic;
1983 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1984 /*CStyle*/true, msg);
1985 if (tcr == TC_Success)
1988 Sema::CheckedConversionKind CCK
1989 = FunctionalStyle? Sema::CCK_FunctionalCast
1990 : Sema::CCK_CStyleCast;
1991 if (tcr == TC_NotApplicable) {
1992 // ... or if that is not possible, a static_cast, ignoring const, ...
1993 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1994 msg, Kind, BasePath, ListInitialization);
1995 if (SrcExpr.isInvalid())
1998 if (tcr == TC_NotApplicable) {
1999 // ... and finally a reinterpret_cast, ignoring const.
2000 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2001 OpRange, msg, Kind);
2002 if (SrcExpr.isInvalid())
2007 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
2008 checkObjCARCConversion(CCK);
2010 if (tcr != TC_Success && msg != 0) {
2011 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2012 DeclAccessPair Found;
2013 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2018 assert(!Fn && "cast failed but able to resolve overload expression!!");
2022 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2023 OpRange, SrcExpr.get(), DestType, ListInitialization);
2025 } else if (Kind == CK_BitCast) {
2029 // Clear out SrcExpr if there was a fatal error.
2030 if (tcr != TC_Success)
2031 SrcExpr = ExprError();
2034 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2035 /// non-matching type. Such as enum function call to int, int call to
2036 /// pointer; etc. Cast to 'void' is an exception.
2037 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2038 QualType DestType) {
2039 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2040 SrcExpr.get()->getExprLoc())
2041 == DiagnosticsEngine::Ignored)
2044 if (!isa<CallExpr>(SrcExpr.get()))
2047 QualType SrcType = SrcExpr.get()->getType();
2048 if (DestType.getUnqualifiedType()->isVoidType())
2050 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2051 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2053 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2054 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2055 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2057 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2059 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2061 if (SrcType->isComplexType() && DestType->isComplexType())
2063 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2066 Self.Diag(SrcExpr.get()->getExprLoc(),
2067 diag::warn_bad_function_cast)
2068 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2071 /// Check the semantics of a C-style cast operation, in C.
2072 void CastOperation::CheckCStyleCast() {
2073 assert(!Self.getLangOpts().CPlusPlus);
2075 // C-style casts can resolve __unknown_any types.
2076 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2077 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2078 SrcExpr.get(), Kind,
2079 ValueKind, BasePath);
2083 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2084 // type needs to be scalar.
2085 if (DestType->isVoidType()) {
2086 // We don't necessarily do lvalue-to-rvalue conversions on this.
2087 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2088 if (SrcExpr.isInvalid())
2091 // Cast to void allows any expr type.
2096 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2097 if (SrcExpr.isInvalid())
2099 QualType SrcType = SrcExpr.get()->getType();
2101 assert(!SrcType->isPlaceholderType());
2103 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2104 diag::err_typecheck_cast_to_incomplete)) {
2105 SrcExpr = ExprError();
2109 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2110 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2112 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2113 // GCC struct/union extension: allow cast to self.
2114 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2115 << DestType << SrcExpr.get()->getSourceRange();
2120 // GCC's cast to union extension.
2121 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2122 RecordDecl *RD = DestRecordTy->getDecl();
2123 RecordDecl::field_iterator Field, FieldEnd;
2124 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2125 Field != FieldEnd; ++Field) {
2126 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2127 !Field->isUnnamedBitfield()) {
2128 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2129 << SrcExpr.get()->getSourceRange();
2133 if (Field == FieldEnd) {
2134 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2135 << SrcType << SrcExpr.get()->getSourceRange();
2136 SrcExpr = ExprError();
2143 // Reject any other conversions to non-scalar types.
2144 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2145 << DestType << SrcExpr.get()->getSourceRange();
2146 SrcExpr = ExprError();
2150 // The type we're casting to is known to be a scalar or vector.
2152 // Require the operand to be a scalar or vector.
2153 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2154 Self.Diag(SrcExpr.get()->getExprLoc(),
2155 diag::err_typecheck_expect_scalar_operand)
2156 << SrcType << SrcExpr.get()->getSourceRange();
2157 SrcExpr = ExprError();
2161 if (DestType->isExtVectorType()) {
2162 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2166 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2167 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2168 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2169 Kind = CK_VectorSplat;
2170 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2171 SrcExpr = ExprError();
2176 if (SrcType->isVectorType()) {
2177 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2178 SrcExpr = ExprError();
2182 // The source and target types are both scalars, i.e.
2183 // - arithmetic types (fundamental, enum, and complex)
2184 // - all kinds of pointers
2185 // Note that member pointers were filtered out with C++, above.
2187 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2188 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2189 SrcExpr = ExprError();
2193 // If either type is a pointer, the other type has to be either an
2194 // integer or a pointer.
2195 if (!DestType->isArithmeticType()) {
2196 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2197 Self.Diag(SrcExpr.get()->getExprLoc(),
2198 diag::err_cast_pointer_from_non_pointer_int)
2199 << SrcType << SrcExpr.get()->getSourceRange();
2200 SrcExpr = ExprError();
2203 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2205 } else if (!SrcType->isArithmeticType()) {
2206 if (!DestType->isIntegralType(Self.Context) &&
2207 DestType->isArithmeticType()) {
2208 Self.Diag(SrcExpr.get()->getLocStart(),
2209 diag::err_cast_pointer_to_non_pointer_int)
2210 << DestType << SrcExpr.get()->getSourceRange();
2211 SrcExpr = ExprError();
2216 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2217 if (DestType->isHalfType()) {
2218 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2219 << DestType << SrcExpr.get()->getSourceRange();
2220 SrcExpr = ExprError();
2225 // ARC imposes extra restrictions on casts.
2226 if (Self.getLangOpts().ObjCAutoRefCount) {
2227 checkObjCARCConversion(Sema::CCK_CStyleCast);
2228 if (SrcExpr.isInvalid())
2231 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2232 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2233 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2234 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2235 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2236 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2237 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2238 Self.Diag(SrcExpr.get()->getLocStart(),
2239 diag::err_typecheck_incompatible_ownership)
2240 << SrcType << DestType << Sema::AA_Casting
2241 << SrcExpr.get()->getSourceRange();
2246 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2247 Self.Diag(SrcExpr.get()->getLocStart(),
2248 diag::err_arc_convesion_of_weak_unavailable)
2249 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2250 SrcExpr = ExprError();
2254 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2255 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2256 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2257 if (SrcExpr.isInvalid())
2260 if (Kind == CK_BitCast)
2264 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2265 TypeSourceInfo *CastTypeInfo,
2266 SourceLocation RPLoc,
2268 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2269 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2270 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2272 if (getLangOpts().CPlusPlus) {
2273 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2274 isa<InitListExpr>(CastExpr));
2276 Op.CheckCStyleCast();
2279 if (Op.SrcExpr.isInvalid())
2282 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2283 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2284 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2287 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2288 SourceLocation LPLoc,
2290 SourceLocation RPLoc) {
2291 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2292 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2293 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2294 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2296 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2297 if (Op.SrcExpr.isInvalid())
2300 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2301 ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
2303 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2304 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2305 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));