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/Basic/TargetInfo.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Sema/Initialization.h"
27 #include "llvm/ADT/SmallVector.h"
29 using namespace clang;
34 TC_NotApplicable, ///< The cast method is not applicable.
35 TC_Success, ///< The cast method is appropriate and successful.
36 TC_Failed ///< The cast method is appropriate, but failed. A
37 ///< diagnostic has been emitted.
41 CT_Const, ///< const_cast
42 CT_Static, ///< static_cast
43 CT_Reinterpret, ///< reinterpret_cast
44 CT_Dynamic, ///< dynamic_cast
45 CT_CStyle, ///< (Type)expr
46 CT_Functional ///< Type(expr)
50 struct CastOperation {
51 CastOperation(Sema &S, QualType destType, ExprResult src)
52 : Self(S), SrcExpr(src), DestType(destType),
53 ResultType(destType.getNonLValueExprType(S.Context)),
54 ValueKind(Expr::getValueKindForType(destType)),
55 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
57 if (const BuiltinType *placeholder =
58 src.get()->getType()->getAsPlaceholderType()) {
59 PlaceholderKind = placeholder->getKind();
61 PlaceholderKind = (BuiltinType::Kind) 0;
69 ExprValueKind ValueKind;
71 BuiltinType::Kind PlaceholderKind;
73 bool IsARCUnbridgedCast;
76 SourceRange DestRange;
78 // Top-level semantics-checking routines.
79 void CheckConstCast();
80 void CheckReinterpretCast();
81 void CheckStaticCast();
82 void CheckDynamicCast();
83 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
84 void CheckCStyleCast();
86 /// Complete an apparently-successful cast operation that yields
87 /// the given expression.
88 ExprResult complete(CastExpr *castExpr) {
89 // If this is an unbridged cast, wrap the result in an implicit
90 // cast that yields the unbridged-cast placeholder type.
91 if (IsARCUnbridgedCast) {
92 castExpr = ImplicitCastExpr::Create(Self.Context,
93 Self.Context.ARCUnbridgedCastTy,
94 CK_Dependent, castExpr, nullptr,
95 castExpr->getValueKind());
100 // Internal convenience methods.
102 /// Try to handle the given placeholder expression kind. Return
103 /// true if the source expression has the appropriate placeholder
104 /// kind. A placeholder can only be claimed once.
105 bool claimPlaceholder(BuiltinType::Kind K) {
106 if (PlaceholderKind != K) return false;
108 PlaceholderKind = (BuiltinType::Kind) 0;
112 bool isPlaceholder() const {
113 return PlaceholderKind != 0;
115 bool isPlaceholder(BuiltinType::Kind K) const {
116 return PlaceholderKind == K;
119 void checkCastAlign() {
120 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
123 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
124 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
126 Expr *src = SrcExpr.get();
127 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
129 IsARCUnbridgedCast = true;
133 /// Check for and handle non-overload placeholder expressions.
134 void checkNonOverloadPlaceholders() {
135 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
138 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
139 if (SrcExpr.isInvalid())
141 PlaceholderKind = (BuiltinType::Kind) 0;
146 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
149 // The Try functions attempt a specific way of casting. If they succeed, they
150 // return TC_Success. If their way of casting is not appropriate for the given
151 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
152 // to emit if no other way succeeds. If their way of casting is appropriate but
153 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
154 // they emit a specialized diagnostic.
155 // All diagnostics returned by these functions must expect the same three
157 // %0: Cast Type (a value from the CastType enumeration)
159 // %2: Destination Type
160 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
161 QualType DestType, bool CStyle,
163 CXXCastPath &BasePath,
165 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
166 QualType DestType, bool CStyle,
170 CXXCastPath &BasePath);
171 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
172 QualType DestType, bool CStyle,
176 CXXCastPath &BasePath);
177 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
178 CanQualType DestType, bool CStyle,
180 QualType OrigSrcType,
181 QualType OrigDestType, unsigned &msg,
183 CXXCastPath &BasePath);
184 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
186 QualType DestType,bool CStyle,
190 CXXCastPath &BasePath);
192 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
194 Sema::CheckedConversionKind CCK,
196 unsigned &msg, CastKind &Kind,
197 bool ListInitialization);
198 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
200 Sema::CheckedConversionKind CCK,
202 unsigned &msg, CastKind &Kind,
203 CXXCastPath &BasePath,
204 bool ListInitialization);
205 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
206 QualType DestType, bool CStyle,
208 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
209 QualType DestType, bool CStyle,
215 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
217 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
218 SourceLocation LAngleBracketLoc, Declarator &D,
219 SourceLocation RAngleBracketLoc,
220 SourceLocation LParenLoc, Expr *E,
221 SourceLocation RParenLoc) {
223 assert(!D.isInvalidType());
225 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
226 if (D.isInvalidType())
229 if (getLangOpts().CPlusPlus) {
230 // Check that there are no default arguments (C++ only).
231 CheckExtraCXXDefaultArguments(D);
234 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
235 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
236 SourceRange(LParenLoc, RParenLoc));
240 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
241 TypeSourceInfo *DestTInfo, Expr *E,
242 SourceRange AngleBrackets, SourceRange Parens) {
244 QualType DestType = DestTInfo->getType();
246 // If the type is dependent, we won't do the semantic analysis now.
248 DestType->isDependentType() || Ex.get()->isTypeDependent();
250 CastOperation Op(*this, DestType, E);
251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252 Op.DestRange = AngleBrackets;
255 default: llvm_unreachable("Unknown C++ cast!");
257 case tok::kw_const_cast:
258 if (!TypeDependent) {
260 if (Op.SrcExpr.isInvalid())
262 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
264 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
265 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
266 OpLoc, Parens.getEnd(),
269 case tok::kw_dynamic_cast: {
270 if (!TypeDependent) {
271 Op.CheckDynamicCast();
272 if (Op.SrcExpr.isInvalid())
275 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
276 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
277 &Op.BasePath, DestTInfo,
278 OpLoc, Parens.getEnd(),
281 case tok::kw_reinterpret_cast: {
282 if (!TypeDependent) {
283 Op.CheckReinterpretCast();
284 if (Op.SrcExpr.isInvalid())
286 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
288 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
289 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
290 nullptr, DestTInfo, OpLoc,
294 case tok::kw_static_cast: {
295 if (!TypeDependent) {
296 Op.CheckStaticCast();
297 if (Op.SrcExpr.isInvalid())
299 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
302 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
303 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
304 &Op.BasePath, DestTInfo,
305 OpLoc, Parens.getEnd(),
311 /// Try to diagnose a failed overloaded cast. Returns true if
312 /// diagnostics were emitted.
313 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
314 SourceRange range, Expr *src,
316 bool listInitialization) {
318 // These cast kinds don't consider user-defined conversions.
331 QualType srcType = src->getType();
332 if (!destType->isRecordType() && !srcType->isRecordType())
335 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
336 InitializationKind initKind
337 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
338 range, listInitialization)
339 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
341 : InitializationKind::CreateCast(/*type range?*/ range);
342 InitializationSequence sequence(S, entity, initKind, src);
344 assert(sequence.Failed() && "initialization succeeded on second try?");
345 switch (sequence.getFailureKind()) {
346 default: return false;
348 case InitializationSequence::FK_ConstructorOverloadFailed:
349 case InitializationSequence::FK_UserConversionOverloadFailed:
353 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
356 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
358 switch (sequence.getFailedOverloadResult()) {
359 case OR_Success: llvm_unreachable("successful failed overload");
360 case OR_No_Viable_Function:
361 if (candidates.empty())
362 msg = diag::err_ovl_no_conversion_in_cast;
364 msg = diag::err_ovl_no_viable_conversion_in_cast;
365 howManyCandidates = OCD_AllCandidates;
369 msg = diag::err_ovl_ambiguous_conversion_in_cast;
370 howManyCandidates = OCD_ViableCandidates;
374 msg = diag::err_ovl_deleted_conversion_in_cast;
375 howManyCandidates = OCD_ViableCandidates;
379 S.Diag(range.getBegin(), msg)
380 << CT << srcType << destType
381 << range << src->getSourceRange();
383 candidates.NoteCandidates(S, howManyCandidates, src);
388 /// Diagnose a failed cast.
389 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
390 SourceRange opRange, Expr *src, QualType destType,
391 bool listInitialization) {
392 if (msg == diag::err_bad_cxx_cast_generic &&
393 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
397 S.Diag(opRange.getBegin(), msg) << castType
398 << src->getType() << destType << opRange << src->getSourceRange();
400 // Detect if both types are (ptr to) class, and note any incompleteness.
401 int DifferentPtrness = 0;
402 QualType From = destType;
403 if (auto Ptr = From->getAs<PointerType>()) {
404 From = Ptr->getPointeeType();
407 QualType To = src->getType();
408 if (auto Ptr = To->getAs<PointerType>()) {
409 To = Ptr->getPointeeType();
412 if (!DifferentPtrness) {
413 auto RecFrom = From->getAs<RecordType>();
414 auto RecTo = To->getAs<RecordType>();
415 if (RecFrom && RecTo) {
416 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
417 if (!DeclFrom->isCompleteDefinition())
418 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
419 << DeclFrom->getDeclName();
420 auto DeclTo = RecTo->getAsCXXRecordDecl();
421 if (!DeclTo->isCompleteDefinition())
422 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
423 << DeclTo->getDeclName();
428 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
429 /// this removes one level of indirection from both types, provided that they're
430 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
431 /// this one doesn't care if the two pointers-to-member don't point into the
432 /// same class. This is because CastsAwayConstness doesn't care.
433 /// And additionally, it handles C++ references. If both the types are
434 /// references, then their pointee types are returned,
435 /// else if only one of them is reference, it's pointee type is returned,
436 /// and the other type is returned as-is.
437 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
438 const PointerType *T1PtrType = T1->getAs<PointerType>(),
439 *T2PtrType = T2->getAs<PointerType>();
440 if (T1PtrType && T2PtrType) {
441 T1 = T1PtrType->getPointeeType();
442 T2 = T2PtrType->getPointeeType();
445 const ObjCObjectPointerType *T1ObjCPtrType =
446 T1->getAs<ObjCObjectPointerType>(),
448 T2->getAs<ObjCObjectPointerType>();
451 T1 = T1ObjCPtrType->getPointeeType();
452 T2 = T2ObjCPtrType->getPointeeType();
455 else if (T2PtrType) {
456 T1 = T1ObjCPtrType->getPointeeType();
457 T2 = T2PtrType->getPointeeType();
461 else if (T2ObjCPtrType) {
463 T2 = T2ObjCPtrType->getPointeeType();
464 T1 = T1PtrType->getPointeeType();
469 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
470 *T2MPType = T2->getAs<MemberPointerType>();
471 if (T1MPType && T2MPType) {
472 T1 = T1MPType->getPointeeType();
473 T2 = T2MPType->getPointeeType();
477 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
478 *T2BPType = T2->getAs<BlockPointerType>();
479 if (T1BPType && T2BPType) {
480 T1 = T1BPType->getPointeeType();
481 T2 = T2BPType->getPointeeType();
485 const LValueReferenceType *T1RefType = T1->getAs<LValueReferenceType>(),
486 *T2RefType = T2->getAs<LValueReferenceType>();
487 if (T1RefType && T2RefType) {
488 T1 = T1RefType->getPointeeType();
489 T2 = T2RefType->getPointeeType();
494 T1 = T1RefType->getPointeeType();
501 T2 = T2RefType->getPointeeType();
508 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
509 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
510 /// the cast checkers. Both arguments must denote pointer (possibly to member)
513 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
515 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
517 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
518 bool CheckCVR, bool CheckObjCLifetime,
519 QualType *TheOffendingSrcType = nullptr,
520 QualType *TheOffendingDestType = nullptr,
521 Qualifiers *CastAwayQualifiers = nullptr) {
522 // If the only checking we care about is for Objective-C lifetime qualifiers,
523 // and we're not in ObjC mode, there's nothing to check.
524 if (!CheckCVR && CheckObjCLifetime &&
525 !Self.Context.getLangOpts().ObjC1)
528 // Casting away constness is defined in C++ 5.2.11p8 with reference to
529 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
530 // the rules are non-trivial. So first we construct Tcv *...cv* as described
532 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
533 SrcType->isBlockPointerType() ||
534 DestType->isLValueReferenceType()) &&
535 "Source type is not pointer or pointer to member.");
536 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
537 DestType->isBlockPointerType() ||
538 DestType->isLValueReferenceType()) &&
539 "Destination type is not pointer or pointer to member, or reference.");
541 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
542 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
543 SmallVector<Qualifiers, 8> cv1, cv2;
545 // Find the qualifiers. We only care about cvr-qualifiers for the
546 // purpose of this check, because other qualifiers (address spaces,
547 // Objective-C GC, etc.) are part of the type's identity.
548 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
549 QualType PrevUnwrappedDestType = UnwrappedDestType;
550 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
551 // Determine the relevant qualifiers at this level.
552 Qualifiers SrcQuals, DestQuals;
553 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
554 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
556 // We do not meaningfully track object const-ness of Objective-C object
557 // types. Remove const from the source type if either the source or
558 // the destination is an Objective-C object type.
559 if (UnwrappedSrcType->isObjCObjectType() ||
560 UnwrappedDestType->isObjCObjectType())
561 SrcQuals.removeConst();
563 Qualifiers RetainedSrcQuals, RetainedDestQuals;
565 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
566 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
568 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
569 TheOffendingDestType && CastAwayQualifiers) {
570 *TheOffendingSrcType = PrevUnwrappedSrcType;
571 *TheOffendingDestType = PrevUnwrappedDestType;
572 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
576 if (CheckObjCLifetime &&
577 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
580 cv1.push_back(RetainedSrcQuals);
581 cv2.push_back(RetainedDestQuals);
583 PrevUnwrappedSrcType = UnwrappedSrcType;
584 PrevUnwrappedDestType = UnwrappedDestType;
589 // Construct void pointers with those qualifiers (in reverse order of
590 // unwrapping, of course).
591 QualType SrcConstruct = Self.Context.VoidTy;
592 QualType DestConstruct = Self.Context.VoidTy;
593 ASTContext &Context = Self.Context;
594 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
596 i1 != cv1.rend(); ++i1, ++i2) {
598 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
600 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
603 // Test if they're compatible.
604 bool ObjCLifetimeConversion;
605 return SrcConstruct != DestConstruct &&
606 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
607 ObjCLifetimeConversion);
610 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
611 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
612 /// checked downcasts in class hierarchies.
613 void CastOperation::CheckDynamicCast() {
614 if (ValueKind == VK_RValue)
615 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
616 else if (isPlaceholder())
617 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
618 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
621 QualType OrigSrcType = SrcExpr.get()->getType();
622 QualType DestType = Self.Context.getCanonicalType(this->DestType);
624 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
625 // or "pointer to cv void".
627 QualType DestPointee;
628 const PointerType *DestPointer = DestType->getAs<PointerType>();
629 const ReferenceType *DestReference = nullptr;
631 DestPointee = DestPointer->getPointeeType();
632 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
633 DestPointee = DestReference->getPointeeType();
635 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
636 << this->DestType << DestRange;
637 SrcExpr = ExprError();
641 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
642 if (DestPointee->isVoidType()) {
643 assert(DestPointer && "Reference to void is not possible");
644 } else if (DestRecord) {
645 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
646 diag::err_bad_dynamic_cast_incomplete,
648 SrcExpr = ExprError();
652 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
653 << DestPointee.getUnqualifiedType() << DestRange;
654 SrcExpr = ExprError();
658 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
659 // complete class type, [...]. If T is an lvalue reference type, v shall be
660 // an lvalue of a complete class type, [...]. If T is an rvalue reference
661 // type, v shall be an expression having a complete class type, [...]
662 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
665 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
666 SrcPointee = SrcPointer->getPointeeType();
668 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
669 << OrigSrcType << SrcExpr.get()->getSourceRange();
670 SrcExpr = ExprError();
673 } else if (DestReference->isLValueReferenceType()) {
674 if (!SrcExpr.get()->isLValue()) {
675 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
676 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
678 SrcPointee = SrcType;
680 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
681 // to materialize the prvalue before we bind the reference to it.
682 if (SrcExpr.get()->isRValue())
683 SrcExpr = Self.CreateMaterializeTemporaryExpr(
684 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
685 SrcPointee = SrcType;
688 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
690 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
691 diag::err_bad_dynamic_cast_incomplete,
693 SrcExpr = ExprError();
697 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
698 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
699 SrcExpr = ExprError();
703 assert((DestPointer || DestReference) &&
704 "Bad destination non-ptr/ref slipped through.");
705 assert((DestRecord || DestPointee->isVoidType()) &&
706 "Bad destination pointee slipped through.");
707 assert(SrcRecord && "Bad source pointee slipped through.");
709 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
710 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
711 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
712 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
713 SrcExpr = ExprError();
717 // C++ 5.2.7p3: If the type of v is the same as the required result type,
719 if (DestRecord == SrcRecord) {
725 // Upcasts are resolved statically.
727 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
728 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
729 OpRange.getBegin(), OpRange,
731 SrcExpr = ExprError();
735 Kind = CK_DerivedToBase;
739 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
740 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
741 assert(SrcDecl && "Definition missing");
742 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
743 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
744 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
745 SrcExpr = ExprError();
748 // dynamic_cast is not available with -fno-rtti.
749 // As an exception, dynamic_cast to void* is available because it doesn't
751 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
752 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
753 SrcExpr = ExprError();
757 // Done. Everything else is run-time checks.
761 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
762 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
764 /// const char *str = "literal";
765 /// legacy_function(const_cast\<char*\>(str));
766 void CastOperation::CheckConstCast() {
767 if (ValueKind == VK_RValue)
768 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
769 else if (isPlaceholder())
770 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
771 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
774 unsigned msg = diag::err_bad_cxx_cast_generic;
775 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
777 Self.Diag(OpRange.getBegin(), msg) << CT_Const
778 << SrcExpr.get()->getType() << DestType << OpRange;
779 SrcExpr = ExprError();
783 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
784 /// or downcast between respective pointers or references.
785 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
787 SourceRange OpRange) {
788 QualType SrcType = SrcExpr->getType();
789 // When casting from pointer or reference, get pointee type; use original
791 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
792 const CXXRecordDecl *SrcRD =
793 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
795 // Examining subobjects for records is only possible if the complete and
796 // valid definition is available. Also, template instantiation is not
798 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
801 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
803 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
811 CXXBasePaths BasePaths;
813 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
814 ReinterpretKind = ReinterpretUpcast;
815 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
816 ReinterpretKind = ReinterpretDowncast;
820 bool VirtualBase = true;
821 bool NonZeroOffset = false;
822 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
825 const CXXBasePath &Path = *I;
826 CharUnits Offset = CharUnits::Zero();
827 bool IsVirtual = false;
828 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
829 IElem != EElem; ++IElem) {
830 IsVirtual = IElem->Base->isVirtual();
833 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
834 assert(BaseRD && "Base type should be a valid unqualified class type");
835 // Don't check if any base has invalid declaration or has no definition
836 // since it has no layout info.
837 const CXXRecordDecl *Class = IElem->Class,
838 *ClassDefinition = Class->getDefinition();
839 if (Class->isInvalidDecl() || !ClassDefinition ||
840 !ClassDefinition->isCompleteDefinition())
843 const ASTRecordLayout &DerivedLayout =
844 Self.Context.getASTRecordLayout(Class);
845 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
848 // Don't warn if any path is a non-virtually derived base at offset zero.
851 // Offset makes sense only for non-virtual bases.
853 NonZeroOffset = true;
855 VirtualBase = VirtualBase && IsVirtual;
858 (void) NonZeroOffset; // Silence set but not used warning.
859 assert((VirtualBase || NonZeroOffset) &&
860 "Should have returned if has non-virtual base with zero offset");
863 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
864 QualType DerivedType =
865 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
867 SourceLocation BeginLoc = OpRange.getBegin();
868 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
869 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
871 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
872 << int(ReinterpretKind)
873 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
876 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
878 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
880 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
881 void CastOperation::CheckReinterpretCast() {
882 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
883 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
885 checkNonOverloadPlaceholders();
886 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
889 unsigned msg = diag::err_bad_cxx_cast_generic;
891 TryReinterpretCast(Self, SrcExpr, DestType,
892 /*CStyle*/false, OpRange, msg, Kind);
893 if (tcr != TC_Success && msg != 0)
895 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
897 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
898 //FIXME: &f<int>; is overloaded and resolvable
899 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
900 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
901 << DestType << OpRange;
902 Self.NoteAllOverloadCandidates(SrcExpr.get());
905 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
906 DestType, /*listInitialization=*/false);
908 SrcExpr = ExprError();
909 } else if (tcr == TC_Success) {
910 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
911 checkObjCConversion(Sema::CCK_OtherCast);
912 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
917 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
918 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
919 /// implicit conversions explicit and getting rid of data loss warnings.
920 void CastOperation::CheckStaticCast() {
921 if (isPlaceholder()) {
922 checkNonOverloadPlaceholders();
923 if (SrcExpr.isInvalid())
927 // This test is outside everything else because it's the only case where
928 // a non-lvalue-reference target type does not lead to decay.
929 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
930 if (DestType->isVoidType()) {
933 if (claimPlaceholder(BuiltinType::Overload)) {
934 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
935 false, // Decay Function to ptr
937 OpRange, DestType, diag::err_bad_static_cast_overload);
938 if (SrcExpr.isInvalid())
942 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
946 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
947 !isPlaceholder(BuiltinType::Overload)) {
948 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
949 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
953 unsigned msg = diag::err_bad_cxx_cast_generic;
955 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
956 Kind, BasePath, /*ListInitialization=*/false);
957 if (tcr != TC_Success && msg != 0) {
958 if (SrcExpr.isInvalid())
960 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
961 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
962 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
963 << oe->getName() << DestType << OpRange
964 << oe->getQualifierLoc().getSourceRange();
965 Self.NoteAllOverloadCandidates(SrcExpr.get());
967 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
968 /*listInitialization=*/false);
970 SrcExpr = ExprError();
971 } else if (tcr == TC_Success) {
972 if (Kind == CK_BitCast)
974 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
975 checkObjCConversion(Sema::CCK_OtherCast);
976 } else if (Kind == CK_BitCast) {
981 /// TryStaticCast - Check if a static cast can be performed, and do so if
982 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
983 /// and casting away constness.
984 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
986 Sema::CheckedConversionKind CCK,
987 SourceRange OpRange, unsigned &msg,
988 CastKind &Kind, CXXCastPath &BasePath,
989 bool ListInitialization) {
990 // Determine whether we have the semantics of a C-style cast.
992 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
994 // The order the tests is not entirely arbitrary. There is one conversion
995 // that can be handled in two different ways. Given:
997 // struct B : public A {
1000 // const A &a = B();
1001 // the cast static_cast<const B&>(a) could be seen as either a static
1002 // reference downcast, or an explicit invocation of the user-defined
1003 // conversion using B's conversion constructor.
1004 // DR 427 specifies that the downcast is to be applied here.
1006 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1007 // Done outside this function.
1011 // C++ 5.2.9p5, reference downcast.
1012 // See the function for details.
1013 // DR 427 specifies that this is to be applied before paragraph 2.
1014 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1015 OpRange, msg, Kind, BasePath);
1016 if (tcr != TC_NotApplicable)
1019 // C++11 [expr.static.cast]p3:
1020 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1021 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1022 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
1024 if (tcr != TC_NotApplicable)
1027 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1028 // [...] if the declaration "T t(e);" is well-formed, [...].
1029 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1030 Kind, ListInitialization);
1031 if (SrcExpr.isInvalid())
1033 if (tcr != TC_NotApplicable)
1036 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1037 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1038 // conversions, subject to further restrictions.
1039 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1040 // of qualification conversions impossible.
1041 // In the CStyle case, the earlier attempt to const_cast should have taken
1042 // care of reverse qualification conversions.
1044 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1046 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1047 // converted to an integral type. [...] A value of a scoped enumeration type
1048 // can also be explicitly converted to a floating-point type [...].
1049 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1050 if (Enum->getDecl()->isScoped()) {
1051 if (DestType->isBooleanType()) {
1052 Kind = CK_IntegralToBoolean;
1054 } else if (DestType->isIntegralType(Self.Context)) {
1055 Kind = CK_IntegralCast;
1057 } else if (DestType->isRealFloatingType()) {
1058 Kind = CK_IntegralToFloating;
1064 // Reverse integral promotion/conversion. All such conversions are themselves
1065 // again integral promotions or conversions and are thus already handled by
1066 // p2 (TryDirectInitialization above).
1067 // (Note: any data loss warnings should be suppressed.)
1068 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1069 // enum->enum). See also C++ 5.2.9p7.
1070 // The same goes for reverse floating point promotion/conversion and
1071 // floating-integral conversions. Again, only floating->enum is relevant.
1072 if (DestType->isEnumeralType()) {
1073 if (SrcType->isIntegralOrEnumerationType()) {
1074 Kind = CK_IntegralCast;
1076 } else if (SrcType->isRealFloatingType()) {
1077 Kind = CK_FloatingToIntegral;
1082 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1083 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1084 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1086 if (tcr != TC_NotApplicable)
1089 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1090 // conversion. C++ 5.2.9p9 has additional information.
1091 // DR54's access restrictions apply here also.
1092 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1093 OpRange, msg, Kind, BasePath);
1094 if (tcr != TC_NotApplicable)
1097 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1098 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1099 // just the usual constness stuff.
1100 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1101 QualType SrcPointee = SrcPointer->getPointeeType();
1102 if (SrcPointee->isVoidType()) {
1103 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1104 QualType DestPointee = DestPointer->getPointeeType();
1105 if (DestPointee->isIncompleteOrObjectType()) {
1106 // This is definitely the intended conversion, but it might fail due
1107 // to a qualifier violation. Note that we permit Objective-C lifetime
1108 // and GC qualifier mismatches here.
1110 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1111 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1112 DestPointeeQuals.removeObjCGCAttr();
1113 DestPointeeQuals.removeObjCLifetime();
1114 SrcPointeeQuals.removeObjCGCAttr();
1115 SrcPointeeQuals.removeObjCLifetime();
1116 if (DestPointeeQuals != SrcPointeeQuals &&
1117 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1118 msg = diag::err_bad_cxx_cast_qualifiers_away;
1126 // Microsoft permits static_cast from 'pointer-to-void' to
1127 // 'pointer-to-function'.
1128 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1129 DestPointee->isFunctionType()) {
1130 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1135 else if (DestType->isObjCObjectPointerType()) {
1136 // allow both c-style cast and static_cast of objective-c pointers as
1137 // they are pervasive.
1138 Kind = CK_CPointerToObjCPointerCast;
1141 else if (CStyle && DestType->isBlockPointerType()) {
1142 // allow c-style cast of void * to block pointers.
1143 Kind = CK_AnyPointerToBlockPointerCast;
1148 // Allow arbitray objective-c pointer conversion with static casts.
1149 if (SrcType->isObjCObjectPointerType() &&
1150 DestType->isObjCObjectPointerType()) {
1154 // Allow ns-pointer to cf-pointer conversion in either direction
1155 // with static casts.
1157 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1160 // See if it looks like the user is trying to convert between
1161 // related record types, and select a better diagnostic if so.
1162 if (auto SrcPointer = SrcType->getAs<PointerType>())
1163 if (auto DestPointer = DestType->getAs<PointerType>())
1164 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1165 DestPointer->getPointeeType()->getAs<RecordType>())
1166 msg = diag::err_bad_cxx_cast_unrelated_class;
1168 // We tried everything. Everything! Nothing works! :-(
1169 return TC_NotApplicable;
1172 /// Tests whether a conversion according to N2844 is valid.
1173 TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1174 QualType DestType, bool CStyle,
1175 CastKind &Kind, CXXCastPath &BasePath,
1177 // C++11 [expr.static.cast]p3:
1178 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1179 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1180 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1182 return TC_NotApplicable;
1184 if (!SrcExpr->isGLValue())
1185 return TC_NotApplicable;
1187 // Because we try the reference downcast before this function, from now on
1188 // this is the only cast possibility, so we issue an error if we fail now.
1189 // FIXME: Should allow casting away constness if CStyle.
1191 bool ObjCConversion;
1192 bool ObjCLifetimeConversion;
1193 QualType FromType = SrcExpr->getType();
1194 QualType ToType = R->getPointeeType();
1196 FromType = FromType.getUnqualifiedType();
1197 ToType = ToType.getUnqualifiedType();
1200 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1201 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
1202 ObjCLifetimeConversion);
1203 if (RefResult != Sema::Ref_Compatible) {
1204 if (CStyle || RefResult == Sema::Ref_Incompatible)
1205 return TC_NotApplicable;
1206 // Diagnose types which are reference-related but not compatible here since
1207 // we can provide better diagnostics. In these cases forwarding to
1208 // [expr.static.cast]p4 should never result in a well-formed cast.
1209 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1210 : diag::err_bad_rvalue_to_rvalue_cast;
1214 if (DerivedToBase) {
1215 Kind = CK_DerivedToBase;
1216 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1217 /*DetectVirtual=*/true);
1218 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1219 R->getPointeeType(), Paths))
1220 return TC_NotApplicable;
1222 Self.BuildBasePathArray(Paths, BasePath);
1229 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1231 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1232 bool CStyle, SourceRange OpRange,
1233 unsigned &msg, CastKind &Kind,
1234 CXXCastPath &BasePath) {
1235 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1236 // cast to type "reference to cv2 D", where D is a class derived from B,
1237 // if a valid standard conversion from "pointer to D" to "pointer to B"
1238 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1239 // In addition, DR54 clarifies that the base must be accessible in the
1240 // current context. Although the wording of DR54 only applies to the pointer
1241 // variant of this rule, the intent is clearly for it to apply to the this
1242 // conversion as well.
1244 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1245 if (!DestReference) {
1246 return TC_NotApplicable;
1248 bool RValueRef = DestReference->isRValueReferenceType();
1249 if (!RValueRef && !SrcExpr->isLValue()) {
1250 // We know the left side is an lvalue reference, so we can suggest a reason.
1251 msg = diag::err_bad_cxx_cast_rvalue;
1252 return TC_NotApplicable;
1255 QualType DestPointee = DestReference->getPointeeType();
1257 // FIXME: If the source is a prvalue, we should issue a warning (because the
1258 // cast always has undefined behavior), and for AST consistency, we should
1259 // materialize a temporary.
1260 return TryStaticDowncast(Self,
1261 Self.Context.getCanonicalType(SrcExpr->getType()),
1262 Self.Context.getCanonicalType(DestPointee), CStyle,
1263 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1267 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1269 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1270 bool CStyle, SourceRange OpRange,
1271 unsigned &msg, CastKind &Kind,
1272 CXXCastPath &BasePath) {
1273 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1274 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1275 // is a class derived from B, if a valid standard conversion from "pointer
1276 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1278 // In addition, DR54 clarifies that the base must be accessible in the
1281 const PointerType *DestPointer = DestType->getAs<PointerType>();
1283 return TC_NotApplicable;
1286 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1288 msg = diag::err_bad_static_cast_pointer_nonpointer;
1289 return TC_NotApplicable;
1292 return TryStaticDowncast(Self,
1293 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1294 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1295 CStyle, OpRange, SrcType, DestType, msg, Kind,
1299 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1300 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1301 /// DestType is possible and allowed.
1303 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1304 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1305 QualType OrigDestType, unsigned &msg,
1306 CastKind &Kind, CXXCastPath &BasePath) {
1307 // We can only work with complete types. But don't complain if it doesn't work
1308 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1309 !Self.isCompleteType(OpRange.getBegin(), DestType))
1310 return TC_NotApplicable;
1312 // Downcast can only happen in class hierarchies, so we need classes.
1313 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1314 return TC_NotApplicable;
1317 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1318 /*DetectVirtual=*/true);
1319 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1320 return TC_NotApplicable;
1323 // Target type does derive from source type. Now we're serious. If an error
1324 // appears now, it's not ignored.
1325 // This may not be entirely in line with the standard. Take for example:
1327 // struct B : virtual A {
1333 // (void)static_cast<const B&>(*((A*)0));
1335 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1336 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1337 // However, both GCC and Comeau reject this example, and accepting it would
1338 // mean more complex code if we're to preserve the nice error message.
1339 // FIXME: Being 100% compliant here would be nice to have.
1341 // Must preserve cv, as always, unless we're in C-style mode.
1342 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1343 msg = diag::err_bad_cxx_cast_qualifiers_away;
1347 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1348 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1349 // that it builds the paths in reverse order.
1350 // To sum up: record all paths to the base and build a nice string from
1351 // them. Use it to spice up the error message.
1352 if (!Paths.isRecordingPaths()) {
1354 Paths.setRecordingPaths(true);
1355 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1357 std::string PathDisplayStr;
1358 std::set<unsigned> DisplayedPaths;
1359 for (clang::CXXBasePath &Path : Paths) {
1360 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1361 // We haven't displayed a path to this particular base
1362 // class subobject yet.
1363 PathDisplayStr += "\n ";
1364 for (CXXBasePathElement &PE : llvm::reverse(Path))
1365 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1366 PathDisplayStr += QualType(DestType).getAsString();
1370 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1371 << QualType(SrcType).getUnqualifiedType()
1372 << QualType(DestType).getUnqualifiedType()
1373 << PathDisplayStr << OpRange;
1378 if (Paths.getDetectedVirtual() != nullptr) {
1379 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1380 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1381 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1387 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1390 diag::err_downcast_from_inaccessible_base)) {
1391 case Sema::AR_accessible:
1392 case Sema::AR_delayed: // be optimistic
1393 case Sema::AR_dependent: // be optimistic
1396 case Sema::AR_inaccessible:
1402 Self.BuildBasePathArray(Paths, BasePath);
1403 Kind = CK_BaseToDerived;
1407 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1408 /// C++ 5.2.9p9 is valid:
1410 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1411 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1412 /// where B is a base class of D [...].
1415 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1416 QualType DestType, bool CStyle,
1417 SourceRange OpRange,
1418 unsigned &msg, CastKind &Kind,
1419 CXXCastPath &BasePath) {
1420 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1422 return TC_NotApplicable;
1424 bool WasOverloadedFunction = false;
1425 DeclAccessPair FoundOverload;
1426 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1427 if (FunctionDecl *Fn
1428 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1430 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1431 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1432 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1433 WasOverloadedFunction = true;
1437 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1439 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1440 return TC_NotApplicable;
1443 // Lock down the inheritance model right now in MS ABI, whether or not the
1444 // pointee types are the same.
1445 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1446 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1447 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1450 // T == T, modulo cv
1451 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1452 DestMemPtr->getPointeeType()))
1453 return TC_NotApplicable;
1456 QualType SrcClass(SrcMemPtr->getClass(), 0);
1457 QualType DestClass(DestMemPtr->getClass(), 0);
1458 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1459 /*DetectVirtual=*/true);
1460 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1461 return TC_NotApplicable;
1463 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1464 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1466 Paths.setRecordingPaths(true);
1468 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1471 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1472 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1473 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1478 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1479 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1480 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1486 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1487 DestClass, SrcClass,
1489 diag::err_upcast_to_inaccessible_base)) {
1490 case Sema::AR_accessible:
1491 case Sema::AR_delayed:
1492 case Sema::AR_dependent:
1493 // Optimistically assume that the delayed and dependent cases
1497 case Sema::AR_inaccessible:
1503 if (WasOverloadedFunction) {
1504 // Resolve the address of the overloaded function again, this time
1505 // allowing complaints if something goes wrong.
1506 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1515 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1516 if (!SrcExpr.isUsable()) {
1522 Self.BuildBasePathArray(Paths, BasePath);
1523 Kind = CK_DerivedToBaseMemberPointer;
1527 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1530 /// An expression e can be explicitly converted to a type T using a
1531 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1533 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1534 Sema::CheckedConversionKind CCK,
1535 SourceRange OpRange, unsigned &msg,
1536 CastKind &Kind, bool ListInitialization) {
1537 if (DestType->isRecordType()) {
1538 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1539 diag::err_bad_dynamic_cast_incomplete) ||
1540 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1541 diag::err_allocation_of_abstract_type)) {
1547 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1548 InitializationKind InitKind
1549 = (CCK == Sema::CCK_CStyleCast)
1550 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1552 : (CCK == Sema::CCK_FunctionalCast)
1553 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1554 : InitializationKind::CreateCast(OpRange);
1555 Expr *SrcExprRaw = SrcExpr.get();
1556 // FIXME: Per DR242, we should check for an implicit conversion sequence
1557 // or for a constructor that could be invoked by direct-initialization
1558 // here, not for an initialization sequence.
1559 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1561 // At this point of CheckStaticCast, if the destination is a reference,
1562 // or the expression is an overload expression this has to work.
1563 // There is no other way that works.
1564 // On the other hand, if we're checking a C-style cast, we've still got
1565 // the reinterpret_cast way.
1567 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1568 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1569 return TC_NotApplicable;
1571 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1572 if (Result.isInvalid()) {
1577 if (InitSeq.isConstructorInitialization())
1578 Kind = CK_ConstructorConversion;
1586 /// TryConstCast - See if a const_cast from source to destination is allowed,
1587 /// and perform it if it is.
1588 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1589 QualType DestType, bool CStyle,
1591 DestType = Self.Context.getCanonicalType(DestType);
1592 QualType SrcType = SrcExpr.get()->getType();
1593 bool NeedToMaterializeTemporary = false;
1595 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1597 // if a pointer to T1 can be explicitly converted to the type "pointer to
1598 // T2" using a const_cast, then the following conversions can also be
1600 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1601 // type T2 using the cast const_cast<T2&>;
1602 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1603 // type T2 using the cast const_cast<T2&&>; and
1604 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1605 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1607 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1608 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1609 // is C-style, static_cast might find a way, so we simply suggest a
1610 // message and tell the parent to keep searching.
1611 msg = diag::err_bad_cxx_cast_rvalue;
1612 return TC_NotApplicable;
1615 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1616 if (!SrcType->isRecordType()) {
1617 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1618 // this is C-style, static_cast can do this.
1619 msg = diag::err_bad_cxx_cast_rvalue;
1620 return TC_NotApplicable;
1623 // Materialize the class prvalue so that the const_cast can bind a
1625 NeedToMaterializeTemporary = true;
1628 // It's not completely clear under the standard whether we can
1629 // const_cast bit-field gl-values. Doing so would not be
1630 // intrinsically complicated, but for now, we say no for
1631 // consistency with other compilers and await the word of the
1633 if (SrcExpr.get()->refersToBitField()) {
1634 msg = diag::err_bad_cxx_cast_bitfield;
1635 return TC_NotApplicable;
1638 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1639 SrcType = Self.Context.getPointerType(SrcType);
1642 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1643 // the rules for const_cast are the same as those used for pointers.
1645 if (!DestType->isPointerType() &&
1646 !DestType->isMemberPointerType() &&
1647 !DestType->isObjCObjectPointerType()) {
1648 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1649 // was a reference type, we converted it to a pointer above.
1650 // The status of rvalue references isn't entirely clear, but it looks like
1651 // conversion to them is simply invalid.
1652 // C++ 5.2.11p3: For two pointer types [...]
1654 msg = diag::err_bad_const_cast_dest;
1655 return TC_NotApplicable;
1657 if (DestType->isFunctionPointerType() ||
1658 DestType->isMemberFunctionPointerType()) {
1659 // Cannot cast direct function pointers.
1660 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1661 // T is the ultimate pointee of source and target type.
1663 msg = diag::err_bad_const_cast_dest;
1664 return TC_NotApplicable;
1666 SrcType = Self.Context.getCanonicalType(SrcType);
1668 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1669 // completely equal.
1670 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1671 // in multi-level pointers may change, but the level count must be the same,
1672 // as must be the final pointee type.
1673 while (SrcType != DestType &&
1674 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1675 Qualifiers SrcQuals, DestQuals;
1676 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1677 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1679 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1680 // the other qualifiers (e.g., address spaces) are identical.
1681 SrcQuals.removeCVRQualifiers();
1682 DestQuals.removeCVRQualifiers();
1683 if (SrcQuals != DestQuals)
1684 return TC_NotApplicable;
1687 // Since we're dealing in canonical types, the remainder must be the same.
1688 if (SrcType != DestType)
1689 return TC_NotApplicable;
1691 if (NeedToMaterializeTemporary)
1692 // This is a const_cast from a class prvalue to an rvalue reference type.
1693 // Materialize a temporary to store the result of the conversion.
1694 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1696 /*IsLValueReference*/ false);
1701 // Checks for undefined behavior in reinterpret_cast.
1702 // The cases that is checked for is:
1703 // *reinterpret_cast<T*>(&a)
1704 // reinterpret_cast<T&>(a)
1705 // where accessing 'a' as type 'T' will result in undefined behavior.
1706 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1708 SourceRange Range) {
1709 unsigned DiagID = IsDereference ?
1710 diag::warn_pointer_indirection_from_incompatible_type :
1711 diag::warn_undefined_reinterpret_cast;
1713 if (Diags.isIgnored(DiagID, Range.getBegin()))
1716 QualType SrcTy, DestTy;
1717 if (IsDereference) {
1718 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1721 SrcTy = SrcType->getPointeeType();
1722 DestTy = DestType->getPointeeType();
1724 if (!DestType->getAs<ReferenceType>()) {
1728 DestTy = DestType->getPointeeType();
1731 // Cast is compatible if the types are the same.
1732 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1735 // or one of the types is a char or void type
1736 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1737 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1740 // or one of the types is a tag type.
1741 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1745 // FIXME: Scoped enums?
1746 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1747 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1748 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1753 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1756 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1757 QualType DestType) {
1758 QualType SrcType = SrcExpr.get()->getType();
1759 if (Self.Context.hasSameType(SrcType, DestType))
1761 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1762 if (SrcPtrTy->isObjCSelType()) {
1763 QualType DT = DestType;
1764 if (isa<PointerType>(DestType))
1765 DT = DestType->getPointeeType();
1766 if (!DT.getUnqualifiedType()->isVoidType())
1767 Self.Diag(SrcExpr.get()->getExprLoc(),
1768 diag::warn_cast_pointer_from_sel)
1769 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1773 /// Diagnose casts that change the calling convention of a pointer to a function
1774 /// defined in the current TU.
1775 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1776 QualType DstType, SourceRange OpRange) {
1777 // Check if this cast would change the calling convention of a function
1779 QualType SrcType = SrcExpr.get()->getType();
1780 if (Self.Context.hasSameType(SrcType, DstType) ||
1781 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1783 const auto *SrcFTy =
1784 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1785 const auto *DstFTy =
1786 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1787 CallingConv SrcCC = SrcFTy->getCallConv();
1788 CallingConv DstCC = DstFTy->getCallConv();
1792 // We have a calling convention cast. Check if the source is a pointer to a
1793 // known, specific function that has already been defined.
1794 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1795 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1796 if (UO->getOpcode() == UO_AddrOf)
1797 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1798 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1801 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1805 // Only warn if we are casting from the default convention to a non-default
1806 // convention. This can happen when the programmer forgot to apply the calling
1807 // convention to the function declaration and then inserted this cast to
1808 // satisfy the type system.
1809 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1810 FD->isVariadic(), FD->isCXXInstanceMember());
1811 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1814 // Diagnose this cast, as it is probably bad.
1815 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1816 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1817 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1818 << SrcCCName << DstCCName << OpRange;
1820 // The checks above are cheaper than checking if the diagnostic is enabled.
1821 // However, it's worth checking if the warning is enabled before we construct
1823 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1826 // Try to suggest a fixit to change the calling convention of the function
1827 // whose address was taken. Try to use the latest macro for the convention.
1828 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1829 // to match the Windows header declarations.
1830 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
1831 Preprocessor &PP = Self.getPreprocessor();
1832 SmallVector<TokenValue, 6> AttrTokens;
1833 SmallString<64> CCAttrText;
1834 llvm::raw_svector_ostream OS(CCAttrText);
1835 if (Self.getLangOpts().MicrosoftExt) {
1836 // __stdcall or __vectorcall
1837 OS << "__" << DstCCName;
1838 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1839 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1840 ? TokenValue(II->getTokenID())
1843 // __attribute__((stdcall)) or __attribute__((vectorcall))
1844 OS << "__attribute__((" << DstCCName << "))";
1845 AttrTokens.push_back(tok::kw___attribute);
1846 AttrTokens.push_back(tok::l_paren);
1847 AttrTokens.push_back(tok::l_paren);
1848 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1849 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1850 ? TokenValue(II->getTokenID())
1852 AttrTokens.push_back(tok::r_paren);
1853 AttrTokens.push_back(tok::r_paren);
1855 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1856 if (!AttrSpelling.empty())
1857 CCAttrText = AttrSpelling;
1859 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1860 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1863 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1864 const Expr *SrcExpr, QualType DestType,
1866 QualType SrcType = SrcExpr->getType();
1868 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1869 // are not explicit design choices, but consistent with GCC's behavior.
1870 // Feel free to modify them if you've reason/evidence for an alternative.
1871 if (CStyle && SrcType->isIntegralType(Self.Context)
1872 && !SrcType->isBooleanType()
1873 && !SrcType->isEnumeralType()
1874 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1875 && Self.Context.getTypeSize(DestType) >
1876 Self.Context.getTypeSize(SrcType)) {
1877 // Separate between casts to void* and non-void* pointers.
1878 // Some APIs use (abuse) void* for something like a user context,
1879 // and often that value is an integer even if it isn't a pointer itself.
1880 // Having a separate warning flag allows users to control the warning
1881 // for their workflow.
1882 unsigned Diag = DestType->isVoidPointerType() ?
1883 diag::warn_int_to_void_pointer_cast
1884 : diag::warn_int_to_pointer_cast;
1885 Self.Diag(Loc, Diag) << SrcType << DestType;
1889 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1890 ExprResult &Result) {
1891 // We can only fix an overloaded reinterpret_cast if
1892 // - it is a template with explicit arguments that resolves to an lvalue
1893 // unambiguously, or
1894 // - it is the only function in an overload set that may have its address
1897 Expr *E = Result.get();
1898 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1900 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1902 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1907 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1908 // preserves Result.
1910 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1911 Result, /*DoFunctionPointerConversion=*/true))
1913 return Result.isUsable();
1916 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1917 QualType DestType, bool CStyle,
1918 SourceRange OpRange,
1921 bool IsLValueCast = false;
1923 DestType = Self.Context.getCanonicalType(DestType);
1924 QualType SrcType = SrcExpr.get()->getType();
1926 // Is the source an overloaded name? (i.e. &foo)
1927 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
1928 if (SrcType == Self.Context.OverloadTy) {
1929 ExprResult FixedExpr = SrcExpr;
1930 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
1931 return TC_NotApplicable;
1933 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1934 SrcExpr = FixedExpr;
1935 SrcType = SrcExpr.get()->getType();
1938 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1939 if (!SrcExpr.get()->isGLValue()) {
1940 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1941 // similar comment in const_cast.
1942 msg = diag::err_bad_cxx_cast_rvalue;
1943 return TC_NotApplicable;
1947 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1948 /*isDereference=*/false, OpRange);
1951 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1952 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1953 // built-in & and * operators.
1955 const char *inappropriate = nullptr;
1956 switch (SrcExpr.get()->getObjectKind()) {
1960 msg = diag::err_bad_cxx_cast_bitfield;
1961 return TC_NotApplicable;
1962 // FIXME: Use a specific diagnostic for the rest of these cases.
1963 case OK_VectorComponent: inappropriate = "vector element"; break;
1964 case OK_ObjCProperty: inappropriate = "property expression"; break;
1965 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1968 if (inappropriate) {
1969 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1970 << inappropriate << DestType
1971 << OpRange << SrcExpr.get()->getSourceRange();
1972 msg = 0; SrcExpr = ExprError();
1973 return TC_NotApplicable;
1976 // This code does this transformation for the checked types.
1977 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1978 SrcType = Self.Context.getPointerType(SrcType);
1980 IsLValueCast = true;
1983 // Canonicalize source for comparison.
1984 SrcType = Self.Context.getCanonicalType(SrcType);
1986 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1987 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1988 if (DestMemPtr && SrcMemPtr) {
1989 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1990 // can be explicitly converted to an rvalue of type "pointer to member
1991 // of Y of type T2" if T1 and T2 are both function types or both object
1993 if (DestMemPtr->isMemberFunctionPointer() !=
1994 SrcMemPtr->isMemberFunctionPointer())
1995 return TC_NotApplicable;
1997 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1999 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2001 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2002 /*CheckObjCLifetime=*/CStyle)) {
2003 msg = diag::err_bad_cxx_cast_qualifiers_away;
2007 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2008 // We need to determine the inheritance model that the class will use if
2010 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2011 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2014 // Don't allow casting between member pointers of different sizes.
2015 if (Self.Context.getTypeSize(DestMemPtr) !=
2016 Self.Context.getTypeSize(SrcMemPtr)) {
2017 msg = diag::err_bad_cxx_cast_member_pointer_size;
2021 // A valid member pointer cast.
2022 assert(!IsLValueCast);
2023 Kind = CK_ReinterpretMemberPointer;
2027 // See below for the enumeral issue.
2028 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2029 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2030 // type large enough to hold it. A value of std::nullptr_t can be
2031 // converted to an integral type; the conversion has the same meaning
2032 // and validity as a conversion of (void*)0 to the integral type.
2033 if (Self.Context.getTypeSize(SrcType) >
2034 Self.Context.getTypeSize(DestType)) {
2035 msg = diag::err_bad_reinterpret_cast_small_int;
2038 Kind = CK_PointerToIntegral;
2042 // Allow reinterpret_casts between vectors of the same size and
2043 // between vectors and integers of the same size.
2044 bool destIsVector = DestType->isVectorType();
2045 bool srcIsVector = SrcType->isVectorType();
2046 if (srcIsVector || destIsVector) {
2047 // The non-vector type, if any, must have integral type. This is
2048 // the same rule that C vector casts use; note, however, that enum
2049 // types are not integral in C++.
2050 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2051 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2052 return TC_NotApplicable;
2054 // The size we want to consider is eltCount * eltSize.
2055 // That's exactly what the lax-conversion rules will check.
2056 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2061 // Otherwise, pick a reasonable diagnostic.
2063 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2064 else if (!srcIsVector)
2065 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2067 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2072 if (SrcType == DestType) {
2073 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2074 // restrictions, a cast to the same type is allowed so long as it does not
2075 // cast away constness. In C++98, the intent was not entirely clear here,
2076 // since all other paragraphs explicitly forbid casts to the same type.
2077 // C++11 clarifies this case with p2.
2079 // The only allowed types are: integral, enumeration, pointer, or
2080 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2082 TryCastResult Result = TC_NotApplicable;
2083 if (SrcType->isIntegralOrEnumerationType() ||
2084 SrcType->isAnyPointerType() ||
2085 SrcType->isMemberPointerType() ||
2086 SrcType->isBlockPointerType()) {
2087 Result = TC_Success;
2092 bool destIsPtr = DestType->isAnyPointerType() ||
2093 DestType->isBlockPointerType();
2094 bool srcIsPtr = SrcType->isAnyPointerType() ||
2095 SrcType->isBlockPointerType();
2096 if (!destIsPtr && !srcIsPtr) {
2097 // Except for std::nullptr_t->integer and lvalue->reference, which are
2098 // handled above, at least one of the two arguments must be a pointer.
2099 return TC_NotApplicable;
2102 if (DestType->isIntegralType(Self.Context)) {
2103 assert(srcIsPtr && "One type must be a pointer");
2104 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2105 // type large enough to hold it; except in Microsoft mode, where the
2106 // integral type size doesn't matter (except we don't allow bool).
2107 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2108 !DestType->isBooleanType();
2109 if ((Self.Context.getTypeSize(SrcType) >
2110 Self.Context.getTypeSize(DestType)) &&
2111 !MicrosoftException) {
2112 msg = diag::err_bad_reinterpret_cast_small_int;
2115 Kind = CK_PointerToIntegral;
2119 if (SrcType->isIntegralOrEnumerationType()) {
2120 assert(destIsPtr && "One type must be a pointer");
2121 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2123 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2124 // converted to a pointer.
2125 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2126 // necessarily converted to a null pointer value.]
2127 Kind = CK_IntegralToPointer;
2131 if (!destIsPtr || !srcIsPtr) {
2132 // With the valid non-pointer conversions out of the way, we can be even
2134 return TC_NotApplicable;
2137 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2138 // The C-style cast operator can.
2139 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2140 /*CheckObjCLifetime=*/CStyle)) {
2141 msg = diag::err_bad_cxx_cast_qualifiers_away;
2145 // Cannot convert between block pointers and Objective-C object pointers.
2146 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2147 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2148 return TC_NotApplicable;
2151 Kind = CK_LValueBitCast;
2152 } else if (DestType->isObjCObjectPointerType()) {
2153 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2154 } else if (DestType->isBlockPointerType()) {
2155 if (!SrcType->isBlockPointerType()) {
2156 Kind = CK_AnyPointerToBlockPointerCast;
2164 // Any pointer can be cast to an Objective-C pointer type with a C-style
2166 if (CStyle && DestType->isObjCObjectPointerType()) {
2170 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2172 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2174 // Not casting away constness, so the only remaining check is for compatible
2175 // pointer categories.
2177 if (SrcType->isFunctionPointerType()) {
2178 if (DestType->isFunctionPointerType()) {
2179 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2180 // a pointer to a function of a different type.
2184 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2185 // an object type or vice versa is conditionally-supported.
2186 // Compilers support it in C++03 too, though, because it's necessary for
2187 // casting the return value of dlsym() and GetProcAddress().
2188 // FIXME: Conditionally-supported behavior should be configurable in the
2189 // TargetInfo or similar.
2190 Self.Diag(OpRange.getBegin(),
2191 Self.getLangOpts().CPlusPlus11 ?
2192 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2197 if (DestType->isFunctionPointerType()) {
2199 Self.Diag(OpRange.getBegin(),
2200 Self.getLangOpts().CPlusPlus11 ?
2201 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2206 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2207 // a pointer to an object of different type.
2208 // Void pointers are not specified, but supported by every compiler out there.
2209 // So we finish by allowing everything that remains - it's got to be two
2214 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2215 bool ListInitialization) {
2216 assert(Self.getLangOpts().CPlusPlus);
2218 // Handle placeholders.
2219 if (isPlaceholder()) {
2220 // C-style casts can resolve __unknown_any types.
2221 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2222 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2223 SrcExpr.get(), Kind,
2224 ValueKind, BasePath);
2228 checkNonOverloadPlaceholders();
2229 if (SrcExpr.isInvalid())
2233 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2234 // This test is outside everything else because it's the only case where
2235 // a non-lvalue-reference target type does not lead to decay.
2236 if (DestType->isVoidType()) {
2239 if (claimPlaceholder(BuiltinType::Overload)) {
2240 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2241 SrcExpr, /* Decay Function to ptr */ false,
2242 /* Complain */ true, DestRange, DestType,
2243 diag::err_bad_cstyle_cast_overload);
2244 if (SrcExpr.isInvalid())
2248 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2252 // If the type is dependent, we won't do any other semantic analysis now.
2253 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2254 SrcExpr.get()->isValueDependent()) {
2255 assert(Kind == CK_Dependent);
2259 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2260 !isPlaceholder(BuiltinType::Overload)) {
2261 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2262 if (SrcExpr.isInvalid())
2266 // AltiVec vector initialization with a single literal.
2267 if (const VectorType *vecTy = DestType->getAs<VectorType>())
2268 if (vecTy->getVectorKind() == VectorType::AltiVecVector
2269 && (SrcExpr.get()->getType()->isIntegerType()
2270 || SrcExpr.get()->getType()->isFloatingType())) {
2271 Kind = CK_VectorSplat;
2272 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2276 // C++ [expr.cast]p5: The conversions performed by
2279 // - a static_cast followed by a const_cast,
2280 // - a reinterpret_cast, or
2281 // - a reinterpret_cast followed by a const_cast,
2282 // can be performed using the cast notation of explicit type conversion.
2283 // [...] If a conversion can be interpreted in more than one of the ways
2284 // listed above, the interpretation that appears first in the list is used,
2285 // even if a cast resulting from that interpretation is ill-formed.
2286 // In plain language, this means trying a const_cast ...
2287 unsigned msg = diag::err_bad_cxx_cast_generic;
2288 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2289 /*CStyle*/true, msg);
2290 if (SrcExpr.isInvalid())
2292 if (tcr == TC_Success)
2295 Sema::CheckedConversionKind CCK
2296 = FunctionalStyle? Sema::CCK_FunctionalCast
2297 : Sema::CCK_CStyleCast;
2298 if (tcr == TC_NotApplicable) {
2299 // ... or if that is not possible, a static_cast, ignoring const, ...
2300 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2301 msg, Kind, BasePath, ListInitialization);
2302 if (SrcExpr.isInvalid())
2305 if (tcr == TC_NotApplicable) {
2306 // ... and finally a reinterpret_cast, ignoring const.
2307 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2308 OpRange, msg, Kind);
2309 if (SrcExpr.isInvalid())
2314 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2316 checkObjCConversion(CCK);
2318 if (tcr != TC_Success && msg != 0) {
2319 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2320 DeclAccessPair Found;
2321 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2326 // If DestType is a function type (not to be confused with the function
2327 // pointer type), it will be possible to resolve the function address,
2328 // but the type cast should be considered as failure.
2329 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2330 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2331 << OE->getName() << DestType << OpRange
2332 << OE->getQualifierLoc().getSourceRange();
2333 Self.NoteAllOverloadCandidates(SrcExpr.get());
2336 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2337 OpRange, SrcExpr.get(), DestType, ListInitialization);
2339 } else if (Kind == CK_BitCast) {
2343 // Clear out SrcExpr if there was a fatal error.
2344 if (tcr != TC_Success)
2345 SrcExpr = ExprError();
2348 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2349 /// non-matching type. Such as enum function call to int, int call to
2350 /// pointer; etc. Cast to 'void' is an exception.
2351 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2352 QualType DestType) {
2353 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2354 SrcExpr.get()->getExprLoc()))
2357 if (!isa<CallExpr>(SrcExpr.get()))
2360 QualType SrcType = SrcExpr.get()->getType();
2361 if (DestType.getUnqualifiedType()->isVoidType())
2363 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2364 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2366 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2367 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2368 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2370 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2372 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2374 if (SrcType->isComplexType() && DestType->isComplexType())
2376 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2379 Self.Diag(SrcExpr.get()->getExprLoc(),
2380 diag::warn_bad_function_cast)
2381 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2384 /// Check the semantics of a C-style cast operation, in C.
2385 void CastOperation::CheckCStyleCast() {
2386 assert(!Self.getLangOpts().CPlusPlus);
2388 // C-style casts can resolve __unknown_any types.
2389 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2390 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2391 SrcExpr.get(), Kind,
2392 ValueKind, BasePath);
2396 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2397 // type needs to be scalar.
2398 if (DestType->isVoidType()) {
2399 // We don't necessarily do lvalue-to-rvalue conversions on this.
2400 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2401 if (SrcExpr.isInvalid())
2404 // Cast to void allows any expr type.
2409 // Overloads are allowed with C extensions, so we need to support them.
2410 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2412 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2413 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2414 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2417 assert(SrcExpr.isUsable());
2419 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2420 if (SrcExpr.isInvalid())
2422 QualType SrcType = SrcExpr.get()->getType();
2424 assert(!SrcType->isPlaceholderType());
2426 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2427 // address space B is illegal.
2428 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2429 SrcType->isPointerType()) {
2430 const PointerType *DestPtr = DestType->getAs<PointerType>();
2431 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
2432 Self.Diag(OpRange.getBegin(),
2433 diag::err_typecheck_incompatible_address_space)
2434 << SrcType << DestType << Sema::AA_Casting
2435 << SrcExpr.get()->getSourceRange();
2436 SrcExpr = ExprError();
2441 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2442 diag::err_typecheck_cast_to_incomplete)) {
2443 SrcExpr = ExprError();
2447 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2448 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2450 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2451 // GCC struct/union extension: allow cast to self.
2452 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2453 << DestType << SrcExpr.get()->getSourceRange();
2458 // GCC's cast to union extension.
2459 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2460 RecordDecl *RD = DestRecordTy->getDecl();
2461 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2462 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2463 << SrcExpr.get()->getSourceRange();
2467 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2468 << SrcType << SrcExpr.get()->getSourceRange();
2469 SrcExpr = ExprError();
2474 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2475 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2476 llvm::APSInt CastInt;
2477 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2479 Kind = CK_ZeroToOCLEvent;
2482 Self.Diag(OpRange.getBegin(),
2483 diag::err_opencl_cast_non_zero_to_event_t)
2484 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2485 SrcExpr = ExprError();
2490 // Reject any other conversions to non-scalar types.
2491 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2492 << DestType << SrcExpr.get()->getSourceRange();
2493 SrcExpr = ExprError();
2497 // The type we're casting to is known to be a scalar or vector.
2499 // Require the operand to be a scalar or vector.
2500 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2501 Self.Diag(SrcExpr.get()->getExprLoc(),
2502 diag::err_typecheck_expect_scalar_operand)
2503 << SrcType << SrcExpr.get()->getSourceRange();
2504 SrcExpr = ExprError();
2508 if (DestType->isExtVectorType()) {
2509 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2513 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2514 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2515 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2516 Kind = CK_VectorSplat;
2517 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2518 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2519 SrcExpr = ExprError();
2524 if (SrcType->isVectorType()) {
2525 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2526 SrcExpr = ExprError();
2530 // The source and target types are both scalars, i.e.
2531 // - arithmetic types (fundamental, enum, and complex)
2532 // - all kinds of pointers
2533 // Note that member pointers were filtered out with C++, above.
2535 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2536 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2537 SrcExpr = ExprError();
2541 // If either type is a pointer, the other type has to be either an
2542 // integer or a pointer.
2543 if (!DestType->isArithmeticType()) {
2544 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2545 Self.Diag(SrcExpr.get()->getExprLoc(),
2546 diag::err_cast_pointer_from_non_pointer_int)
2547 << SrcType << SrcExpr.get()->getSourceRange();
2548 SrcExpr = ExprError();
2551 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2553 } else if (!SrcType->isArithmeticType()) {
2554 if (!DestType->isIntegralType(Self.Context) &&
2555 DestType->isArithmeticType()) {
2556 Self.Diag(SrcExpr.get()->getLocStart(),
2557 diag::err_cast_pointer_to_non_pointer_int)
2558 << DestType << SrcExpr.get()->getSourceRange();
2559 SrcExpr = ExprError();
2564 if (Self.getLangOpts().OpenCL &&
2565 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
2566 if (DestType->isHalfType()) {
2567 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2568 << DestType << SrcExpr.get()->getSourceRange();
2569 SrcExpr = ExprError();
2574 // ARC imposes extra restrictions on casts.
2575 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2576 checkObjCConversion(Sema::CCK_CStyleCast);
2577 if (SrcExpr.isInvalid())
2580 const PointerType *CastPtr = DestType->getAs<PointerType>();
2581 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
2582 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2583 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2584 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2585 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2586 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2587 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2588 Self.Diag(SrcExpr.get()->getLocStart(),
2589 diag::err_typecheck_incompatible_ownership)
2590 << SrcType << DestType << Sema::AA_Casting
2591 << SrcExpr.get()->getSourceRange();
2596 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2597 Self.Diag(SrcExpr.get()->getLocStart(),
2598 diag::err_arc_convesion_of_weak_unavailable)
2599 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2600 SrcExpr = ExprError();
2605 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2606 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2607 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2608 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2609 if (SrcExpr.isInvalid())
2612 if (Kind == CK_BitCast)
2616 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2617 /// const, volatile or both.
2618 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2619 QualType DestType) {
2620 if (SrcExpr.isInvalid())
2623 QualType SrcType = SrcExpr.get()->getType();
2624 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2625 DestType->isLValueReferenceType()))
2628 QualType TheOffendingSrcType, TheOffendingDestType;
2629 Qualifiers CastAwayQualifiers;
2630 if (!CastsAwayConstness(Self, SrcType, DestType, true, false,
2631 &TheOffendingSrcType, &TheOffendingDestType,
2632 &CastAwayQualifiers))
2635 int qualifiers = -1;
2636 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2638 } else if (CastAwayQualifiers.hasConst()) {
2640 } else if (CastAwayQualifiers.hasVolatile()) {
2643 // This is a variant of int **x; const int **y = (const int **)x;
2644 if (qualifiers == -1)
2645 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
2646 << SrcType << DestType;
2648 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
2649 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
2652 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2653 TypeSourceInfo *CastTypeInfo,
2654 SourceLocation RPLoc,
2656 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2657 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2658 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2660 if (getLangOpts().CPlusPlus) {
2661 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2662 isa<InitListExpr>(CastExpr));
2664 Op.CheckCStyleCast();
2667 if (Op.SrcExpr.isInvalid())
2671 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2673 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2674 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
2675 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2678 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2680 SourceLocation LPLoc,
2682 SourceLocation RPLoc) {
2683 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2684 CastOperation Op(*this, Type, CastExpr);
2685 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2686 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2688 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2689 if (Op.SrcExpr.isInvalid())
2692 auto *SubExpr = Op.SrcExpr.get();
2693 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2694 SubExpr = BindExpr->getSubExpr();
2695 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
2696 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
2698 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2699 Op.ValueKind, CastTypeInfo, Op.Kind,
2700 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));