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 // The Try functions attempt a specific way of casting. If they succeed, they
147 // return TC_Success. If their way of casting is not appropriate for the given
148 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
149 // to emit if no other way succeeds. If their way of casting is appropriate but
150 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
151 // they emit a specialized diagnostic.
152 // All diagnostics returned by these functions must expect the same three
154 // %0: Cast Type (a value from the CastType enumeration)
156 // %2: Destination Type
157 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
158 QualType DestType, bool CStyle,
160 CXXCastPath &BasePath,
162 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
163 QualType DestType, bool CStyle,
167 CXXCastPath &BasePath);
168 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
169 QualType DestType, bool CStyle,
173 CXXCastPath &BasePath);
174 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
175 CanQualType DestType, bool CStyle,
177 QualType OrigSrcType,
178 QualType OrigDestType, unsigned &msg,
180 CXXCastPath &BasePath);
181 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
183 QualType DestType,bool CStyle,
187 CXXCastPath &BasePath);
189 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
191 Sema::CheckedConversionKind CCK,
193 unsigned &msg, CastKind &Kind,
194 bool ListInitialization);
195 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
197 Sema::CheckedConversionKind CCK,
199 unsigned &msg, CastKind &Kind,
200 CXXCastPath &BasePath,
201 bool ListInitialization);
202 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
203 QualType DestType, bool CStyle,
205 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
206 QualType DestType, bool CStyle,
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) {
241 QualType DestType = DestTInfo->getType();
243 // If the type is dependent, we won't do the semantic analysis now.
245 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())
259 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
261 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
262 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
263 OpLoc, Parens.getEnd(),
266 case tok::kw_dynamic_cast: {
267 if (!TypeDependent) {
268 Op.CheckDynamicCast();
269 if (Op.SrcExpr.isInvalid())
272 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
273 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
274 &Op.BasePath, DestTInfo,
275 OpLoc, Parens.getEnd(),
278 case tok::kw_reinterpret_cast: {
279 if (!TypeDependent) {
280 Op.CheckReinterpretCast();
281 if (Op.SrcExpr.isInvalid())
283 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
285 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
286 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
287 nullptr, DestTInfo, OpLoc,
291 case tok::kw_static_cast: {
292 if (!TypeDependent) {
293 Op.CheckStaticCast();
294 if (Op.SrcExpr.isInvalid())
296 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
299 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
300 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
301 &Op.BasePath, DestTInfo,
302 OpLoc, Parens.getEnd(),
308 /// Try to diagnose a failed overloaded cast. Returns true if
309 /// diagnostics were emitted.
310 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
311 SourceRange range, Expr *src,
313 bool listInitialization) {
315 // These cast kinds don't consider user-defined conversions.
328 QualType srcType = src->getType();
329 if (!destType->isRecordType() && !srcType->isRecordType())
332 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
333 InitializationKind initKind
334 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
335 range, listInitialization)
336 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
338 : InitializationKind::CreateCast(/*type range?*/ range);
339 InitializationSequence sequence(S, entity, initKind, src);
341 assert(sequence.Failed() && "initialization succeeded on second try?");
342 switch (sequence.getFailureKind()) {
343 default: return false;
345 case InitializationSequence::FK_ConstructorOverloadFailed:
346 case InitializationSequence::FK_UserConversionOverloadFailed:
350 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
353 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
355 switch (sequence.getFailedOverloadResult()) {
356 case OR_Success: llvm_unreachable("successful failed overload");
357 case OR_No_Viable_Function:
358 if (candidates.empty())
359 msg = diag::err_ovl_no_conversion_in_cast;
361 msg = diag::err_ovl_no_viable_conversion_in_cast;
362 howManyCandidates = OCD_AllCandidates;
366 msg = diag::err_ovl_ambiguous_conversion_in_cast;
367 howManyCandidates = OCD_ViableCandidates;
371 msg = diag::err_ovl_deleted_conversion_in_cast;
372 howManyCandidates = OCD_ViableCandidates;
376 S.Diag(range.getBegin(), msg)
377 << CT << srcType << destType
378 << range << src->getSourceRange();
380 candidates.NoteCandidates(S, howManyCandidates, src);
385 /// Diagnose a failed cast.
386 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
387 SourceRange opRange, Expr *src, QualType destType,
388 bool listInitialization) {
389 if (msg == diag::err_bad_cxx_cast_generic &&
390 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
394 S.Diag(opRange.getBegin(), msg) << castType
395 << src->getType() << destType << opRange << src->getSourceRange();
397 // Detect if both types are (ptr to) class, and note any incompleteness.
398 int DifferentPtrness = 0;
399 QualType From = destType;
400 if (auto Ptr = From->getAs<PointerType>()) {
401 From = Ptr->getPointeeType();
404 QualType To = src->getType();
405 if (auto Ptr = To->getAs<PointerType>()) {
406 To = Ptr->getPointeeType();
409 if (!DifferentPtrness) {
410 auto RecFrom = From->getAs<RecordType>();
411 auto RecTo = To->getAs<RecordType>();
412 if (RecFrom && RecTo) {
413 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
414 if (!DeclFrom->isCompleteDefinition())
415 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
416 << DeclFrom->getDeclName();
417 auto DeclTo = RecTo->getAsCXXRecordDecl();
418 if (!DeclTo->isCompleteDefinition())
419 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
420 << DeclTo->getDeclName();
425 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
426 /// this removes one level of indirection from both types, provided that they're
427 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
428 /// this one doesn't care if the two pointers-to-member don't point into the
429 /// same class. This is because CastsAwayConstness doesn't care.
430 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
431 const PointerType *T1PtrType = T1->getAs<PointerType>(),
432 *T2PtrType = T2->getAs<PointerType>();
433 if (T1PtrType && T2PtrType) {
434 T1 = T1PtrType->getPointeeType();
435 T2 = T2PtrType->getPointeeType();
438 const ObjCObjectPointerType *T1ObjCPtrType =
439 T1->getAs<ObjCObjectPointerType>(),
441 T2->getAs<ObjCObjectPointerType>();
444 T1 = T1ObjCPtrType->getPointeeType();
445 T2 = T2ObjCPtrType->getPointeeType();
448 else if (T2PtrType) {
449 T1 = T1ObjCPtrType->getPointeeType();
450 T2 = T2PtrType->getPointeeType();
454 else if (T2ObjCPtrType) {
456 T2 = T2ObjCPtrType->getPointeeType();
457 T1 = T1PtrType->getPointeeType();
462 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
463 *T2MPType = T2->getAs<MemberPointerType>();
464 if (T1MPType && T2MPType) {
465 T1 = T1MPType->getPointeeType();
466 T2 = T2MPType->getPointeeType();
470 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
471 *T2BPType = T2->getAs<BlockPointerType>();
472 if (T1BPType && T2BPType) {
473 T1 = T1BPType->getPointeeType();
474 T2 = T2BPType->getPointeeType();
481 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
482 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
483 /// the cast checkers. Both arguments must denote pointer (possibly to member)
486 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
488 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
490 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
491 bool CheckCVR, bool CheckObjCLifetime,
492 QualType *TheOffendingSrcType = nullptr,
493 QualType *TheOffendingDestType = nullptr,
494 Qualifiers *CastAwayQualifiers = nullptr) {
495 // If the only checking we care about is for Objective-C lifetime qualifiers,
496 // and we're not in ObjC mode, there's nothing to check.
497 if (!CheckCVR && CheckObjCLifetime &&
498 !Self.Context.getLangOpts().ObjC1)
501 // Casting away constness is defined in C++ 5.2.11p8 with reference to
502 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
503 // the rules are non-trivial. So first we construct Tcv *...cv* as described
505 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
506 SrcType->isBlockPointerType()) &&
507 "Source type is not pointer or pointer to member.");
508 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
509 DestType->isBlockPointerType()) &&
510 "Destination type is not pointer or pointer to member.");
512 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
513 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
514 SmallVector<Qualifiers, 8> cv1, cv2;
516 // Find the qualifiers. We only care about cvr-qualifiers for the
517 // purpose of this check, because other qualifiers (address spaces,
518 // Objective-C GC, etc.) are part of the type's identity.
519 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
520 QualType PrevUnwrappedDestType = UnwrappedDestType;
521 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
522 // Determine the relevant qualifiers at this level.
523 Qualifiers SrcQuals, DestQuals;
524 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
525 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
527 Qualifiers RetainedSrcQuals, RetainedDestQuals;
529 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
530 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
532 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
533 TheOffendingDestType && CastAwayQualifiers) {
534 *TheOffendingSrcType = PrevUnwrappedSrcType;
535 *TheOffendingDestType = PrevUnwrappedDestType;
536 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
540 if (CheckObjCLifetime &&
541 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
544 cv1.push_back(RetainedSrcQuals);
545 cv2.push_back(RetainedDestQuals);
547 PrevUnwrappedSrcType = UnwrappedSrcType;
548 PrevUnwrappedDestType = UnwrappedDestType;
553 // Construct void pointers with those qualifiers (in reverse order of
554 // unwrapping, of course).
555 QualType SrcConstruct = Self.Context.VoidTy;
556 QualType DestConstruct = Self.Context.VoidTy;
557 ASTContext &Context = Self.Context;
558 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
560 i1 != cv1.rend(); ++i1, ++i2) {
562 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
564 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
567 // Test if they're compatible.
568 bool ObjCLifetimeConversion;
569 return SrcConstruct != DestConstruct &&
570 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
571 ObjCLifetimeConversion);
574 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
575 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
576 /// checked downcasts in class hierarchies.
577 void CastOperation::CheckDynamicCast() {
578 if (ValueKind == VK_RValue)
579 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
580 else if (isPlaceholder())
581 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
582 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
585 QualType OrigSrcType = SrcExpr.get()->getType();
586 QualType DestType = Self.Context.getCanonicalType(this->DestType);
588 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
589 // or "pointer to cv void".
591 QualType DestPointee;
592 const PointerType *DestPointer = DestType->getAs<PointerType>();
593 const ReferenceType *DestReference = nullptr;
595 DestPointee = DestPointer->getPointeeType();
596 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
597 DestPointee = DestReference->getPointeeType();
599 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
600 << this->DestType << DestRange;
601 SrcExpr = ExprError();
605 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
606 if (DestPointee->isVoidType()) {
607 assert(DestPointer && "Reference to void is not possible");
608 } else if (DestRecord) {
609 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
610 diag::err_bad_dynamic_cast_incomplete,
612 SrcExpr = ExprError();
616 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
617 << DestPointee.getUnqualifiedType() << DestRange;
618 SrcExpr = ExprError();
622 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
623 // complete class type, [...]. If T is an lvalue reference type, v shall be
624 // an lvalue of a complete class type, [...]. If T is an rvalue reference
625 // type, v shall be an expression having a complete class type, [...]
626 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
629 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
630 SrcPointee = SrcPointer->getPointeeType();
632 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
633 << OrigSrcType << SrcExpr.get()->getSourceRange();
634 SrcExpr = ExprError();
637 } else if (DestReference->isLValueReferenceType()) {
638 if (!SrcExpr.get()->isLValue()) {
639 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
640 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
642 SrcPointee = SrcType;
644 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
645 // to materialize the prvalue before we bind the reference to it.
646 if (SrcExpr.get()->isRValue())
647 SrcExpr = Self.CreateMaterializeTemporaryExpr(
648 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
649 SrcPointee = SrcType;
652 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
654 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
655 diag::err_bad_dynamic_cast_incomplete,
657 SrcExpr = ExprError();
661 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
662 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
663 SrcExpr = ExprError();
667 assert((DestPointer || DestReference) &&
668 "Bad destination non-ptr/ref slipped through.");
669 assert((DestRecord || DestPointee->isVoidType()) &&
670 "Bad destination pointee slipped through.");
671 assert(SrcRecord && "Bad source pointee slipped through.");
673 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
674 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
675 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
676 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
677 SrcExpr = ExprError();
681 // C++ 5.2.7p3: If the type of v is the same as the required result type,
683 if (DestRecord == SrcRecord) {
689 // Upcasts are resolved statically.
691 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
692 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
693 OpRange.getBegin(), OpRange,
695 SrcExpr = ExprError();
699 Kind = CK_DerivedToBase;
703 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
704 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
705 assert(SrcDecl && "Definition missing");
706 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
707 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
708 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
709 SrcExpr = ExprError();
712 // dynamic_cast is not available with -fno-rtti.
713 // As an exception, dynamic_cast to void* is available because it doesn't
715 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
716 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
717 SrcExpr = ExprError();
721 // Done. Everything else is run-time checks.
725 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
726 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
728 /// const char *str = "literal";
729 /// legacy_function(const_cast\<char*\>(str));
730 void CastOperation::CheckConstCast() {
731 if (ValueKind == VK_RValue)
732 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
733 else if (isPlaceholder())
734 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
735 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
738 unsigned msg = diag::err_bad_cxx_cast_generic;
739 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
741 Self.Diag(OpRange.getBegin(), msg) << CT_Const
742 << SrcExpr.get()->getType() << DestType << OpRange;
743 SrcExpr = ExprError();
747 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
748 /// or downcast between respective pointers or references.
749 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
751 SourceRange OpRange) {
752 QualType SrcType = SrcExpr->getType();
753 // When casting from pointer or reference, get pointee type; use original
755 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
756 const CXXRecordDecl *SrcRD =
757 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
759 // Examining subobjects for records is only possible if the complete and
760 // valid definition is available. Also, template instantiation is not
762 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
765 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
767 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
775 CXXBasePaths BasePaths;
777 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
778 ReinterpretKind = ReinterpretUpcast;
779 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
780 ReinterpretKind = ReinterpretDowncast;
784 bool VirtualBase = true;
785 bool NonZeroOffset = false;
786 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
789 const CXXBasePath &Path = *I;
790 CharUnits Offset = CharUnits::Zero();
791 bool IsVirtual = false;
792 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
793 IElem != EElem; ++IElem) {
794 IsVirtual = IElem->Base->isVirtual();
797 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
798 assert(BaseRD && "Base type should be a valid unqualified class type");
799 // Don't check if any base has invalid declaration or has no definition
800 // since it has no layout info.
801 const CXXRecordDecl *Class = IElem->Class,
802 *ClassDefinition = Class->getDefinition();
803 if (Class->isInvalidDecl() || !ClassDefinition ||
804 !ClassDefinition->isCompleteDefinition())
807 const ASTRecordLayout &DerivedLayout =
808 Self.Context.getASTRecordLayout(Class);
809 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
812 // Don't warn if any path is a non-virtually derived base at offset zero.
815 // Offset makes sense only for non-virtual bases.
817 NonZeroOffset = true;
819 VirtualBase = VirtualBase && IsVirtual;
822 (void) NonZeroOffset; // Silence set but not used warning.
823 assert((VirtualBase || NonZeroOffset) &&
824 "Should have returned if has non-virtual base with zero offset");
827 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
828 QualType DerivedType =
829 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
831 SourceLocation BeginLoc = OpRange.getBegin();
832 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
833 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
835 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
836 << int(ReinterpretKind)
837 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
840 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
842 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
844 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
845 void CastOperation::CheckReinterpretCast() {
846 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
847 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
849 checkNonOverloadPlaceholders();
850 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
853 unsigned msg = diag::err_bad_cxx_cast_generic;
855 TryReinterpretCast(Self, SrcExpr, DestType,
856 /*CStyle*/false, OpRange, msg, Kind);
857 if (tcr != TC_Success && msg != 0)
859 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
861 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
862 //FIXME: &f<int>; is overloaded and resolvable
863 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
864 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
865 << DestType << OpRange;
866 Self.NoteAllOverloadCandidates(SrcExpr.get());
869 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
870 DestType, /*listInitialization=*/false);
872 SrcExpr = ExprError();
873 } else if (tcr == TC_Success) {
874 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
875 checkObjCConversion(Sema::CCK_OtherCast);
876 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
881 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
882 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
883 /// implicit conversions explicit and getting rid of data loss warnings.
884 void CastOperation::CheckStaticCast() {
885 if (isPlaceholder()) {
886 checkNonOverloadPlaceholders();
887 if (SrcExpr.isInvalid())
891 // This test is outside everything else because it's the only case where
892 // a non-lvalue-reference target type does not lead to decay.
893 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
894 if (DestType->isVoidType()) {
897 if (claimPlaceholder(BuiltinType::Overload)) {
898 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
899 false, // Decay Function to ptr
901 OpRange, DestType, diag::err_bad_static_cast_overload);
902 if (SrcExpr.isInvalid())
906 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
910 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
911 !isPlaceholder(BuiltinType::Overload)) {
912 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
913 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
917 unsigned msg = diag::err_bad_cxx_cast_generic;
919 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
920 Kind, BasePath, /*ListInitialization=*/false);
921 if (tcr != TC_Success && msg != 0) {
922 if (SrcExpr.isInvalid())
924 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
925 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
926 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
927 << oe->getName() << DestType << OpRange
928 << oe->getQualifierLoc().getSourceRange();
929 Self.NoteAllOverloadCandidates(SrcExpr.get());
931 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
932 /*listInitialization=*/false);
934 SrcExpr = ExprError();
935 } else if (tcr == TC_Success) {
936 if (Kind == CK_BitCast)
938 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
939 checkObjCConversion(Sema::CCK_OtherCast);
940 } else if (Kind == CK_BitCast) {
945 /// TryStaticCast - Check if a static cast can be performed, and do so if
946 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
947 /// and casting away constness.
948 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
950 Sema::CheckedConversionKind CCK,
951 SourceRange OpRange, unsigned &msg,
952 CastKind &Kind, CXXCastPath &BasePath,
953 bool ListInitialization) {
954 // Determine whether we have the semantics of a C-style cast.
956 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
958 // The order the tests is not entirely arbitrary. There is one conversion
959 // that can be handled in two different ways. Given:
961 // struct B : public A {
965 // the cast static_cast<const B&>(a) could be seen as either a static
966 // reference downcast, or an explicit invocation of the user-defined
967 // conversion using B's conversion constructor.
968 // DR 427 specifies that the downcast is to be applied here.
970 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
971 // Done outside this function.
975 // C++ 5.2.9p5, reference downcast.
976 // See the function for details.
977 // DR 427 specifies that this is to be applied before paragraph 2.
978 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
979 OpRange, msg, Kind, BasePath);
980 if (tcr != TC_NotApplicable)
983 // C++11 [expr.static.cast]p3:
984 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
985 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
986 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
988 if (tcr != TC_NotApplicable)
991 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
992 // [...] if the declaration "T t(e);" is well-formed, [...].
993 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
994 Kind, ListInitialization);
995 if (SrcExpr.isInvalid())
997 if (tcr != TC_NotApplicable)
1000 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1001 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1002 // conversions, subject to further restrictions.
1003 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1004 // of qualification conversions impossible.
1005 // In the CStyle case, the earlier attempt to const_cast should have taken
1006 // care of reverse qualification conversions.
1008 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1010 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1011 // converted to an integral type. [...] A value of a scoped enumeration type
1012 // can also be explicitly converted to a floating-point type [...].
1013 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1014 if (Enum->getDecl()->isScoped()) {
1015 if (DestType->isBooleanType()) {
1016 Kind = CK_IntegralToBoolean;
1018 } else if (DestType->isIntegralType(Self.Context)) {
1019 Kind = CK_IntegralCast;
1021 } else if (DestType->isRealFloatingType()) {
1022 Kind = CK_IntegralToFloating;
1028 // Reverse integral promotion/conversion. All such conversions are themselves
1029 // again integral promotions or conversions and are thus already handled by
1030 // p2 (TryDirectInitialization above).
1031 // (Note: any data loss warnings should be suppressed.)
1032 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1033 // enum->enum). See also C++ 5.2.9p7.
1034 // The same goes for reverse floating point promotion/conversion and
1035 // floating-integral conversions. Again, only floating->enum is relevant.
1036 if (DestType->isEnumeralType()) {
1037 if (SrcType->isIntegralOrEnumerationType()) {
1038 Kind = CK_IntegralCast;
1040 } else if (SrcType->isRealFloatingType()) {
1041 Kind = CK_FloatingToIntegral;
1046 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1047 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1048 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1050 if (tcr != TC_NotApplicable)
1053 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1054 // conversion. C++ 5.2.9p9 has additional information.
1055 // DR54's access restrictions apply here also.
1056 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1057 OpRange, msg, Kind, BasePath);
1058 if (tcr != TC_NotApplicable)
1061 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1062 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1063 // just the usual constness stuff.
1064 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1065 QualType SrcPointee = SrcPointer->getPointeeType();
1066 if (SrcPointee->isVoidType()) {
1067 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1068 QualType DestPointee = DestPointer->getPointeeType();
1069 if (DestPointee->isIncompleteOrObjectType()) {
1070 // This is definitely the intended conversion, but it might fail due
1071 // to a qualifier violation. Note that we permit Objective-C lifetime
1072 // and GC qualifier mismatches here.
1074 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1075 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1076 DestPointeeQuals.removeObjCGCAttr();
1077 DestPointeeQuals.removeObjCLifetime();
1078 SrcPointeeQuals.removeObjCGCAttr();
1079 SrcPointeeQuals.removeObjCLifetime();
1080 if (DestPointeeQuals != SrcPointeeQuals &&
1081 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1082 msg = diag::err_bad_cxx_cast_qualifiers_away;
1090 // Microsoft permits static_cast from 'pointer-to-void' to
1091 // 'pointer-to-function'.
1092 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1093 DestPointee->isFunctionType()) {
1094 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1099 else if (DestType->isObjCObjectPointerType()) {
1100 // allow both c-style cast and static_cast of objective-c pointers as
1101 // they are pervasive.
1102 Kind = CK_CPointerToObjCPointerCast;
1105 else if (CStyle && DestType->isBlockPointerType()) {
1106 // allow c-style cast of void * to block pointers.
1107 Kind = CK_AnyPointerToBlockPointerCast;
1112 // Allow arbitray objective-c pointer conversion with static casts.
1113 if (SrcType->isObjCObjectPointerType() &&
1114 DestType->isObjCObjectPointerType()) {
1118 // Allow ns-pointer to cf-pointer conversion in either direction
1119 // with static casts.
1121 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1124 // See if it looks like the user is trying to convert between
1125 // related record types, and select a better diagnostic if so.
1126 if (auto SrcPointer = SrcType->getAs<PointerType>())
1127 if (auto DestPointer = DestType->getAs<PointerType>())
1128 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1129 DestPointer->getPointeeType()->getAs<RecordType>())
1130 msg = diag::err_bad_cxx_cast_unrelated_class;
1132 // We tried everything. Everything! Nothing works! :-(
1133 return TC_NotApplicable;
1136 /// Tests whether a conversion according to N2844 is valid.
1137 TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1138 QualType DestType, bool CStyle,
1139 CastKind &Kind, CXXCastPath &BasePath,
1141 // C++11 [expr.static.cast]p3:
1142 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1143 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1144 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1146 return TC_NotApplicable;
1148 if (!SrcExpr->isGLValue())
1149 return TC_NotApplicable;
1151 // Because we try the reference downcast before this function, from now on
1152 // this is the only cast possibility, so we issue an error if we fail now.
1153 // FIXME: Should allow casting away constness if CStyle.
1155 bool ObjCConversion;
1156 bool ObjCLifetimeConversion;
1157 QualType FromType = SrcExpr->getType();
1158 QualType ToType = R->getPointeeType();
1160 FromType = FromType.getUnqualifiedType();
1161 ToType = ToType.getUnqualifiedType();
1164 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1165 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
1166 ObjCLifetimeConversion);
1167 if (RefResult != Sema::Ref_Compatible) {
1168 if (CStyle || RefResult == Sema::Ref_Incompatible)
1169 return TC_NotApplicable;
1170 // Diagnose types which are reference-related but not compatible here since
1171 // we can provide better diagnostics. In these cases forwarding to
1172 // [expr.static.cast]p4 should never result in a well-formed cast.
1173 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1174 : diag::err_bad_rvalue_to_rvalue_cast;
1178 if (DerivedToBase) {
1179 Kind = CK_DerivedToBase;
1180 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1181 /*DetectVirtual=*/true);
1182 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1183 R->getPointeeType(), Paths))
1184 return TC_NotApplicable;
1186 Self.BuildBasePathArray(Paths, BasePath);
1193 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1195 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1196 bool CStyle, SourceRange OpRange,
1197 unsigned &msg, CastKind &Kind,
1198 CXXCastPath &BasePath) {
1199 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1200 // cast to type "reference to cv2 D", where D is a class derived from B,
1201 // if a valid standard conversion from "pointer to D" to "pointer to B"
1202 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1203 // In addition, DR54 clarifies that the base must be accessible in the
1204 // current context. Although the wording of DR54 only applies to the pointer
1205 // variant of this rule, the intent is clearly for it to apply to the this
1206 // conversion as well.
1208 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1209 if (!DestReference) {
1210 return TC_NotApplicable;
1212 bool RValueRef = DestReference->isRValueReferenceType();
1213 if (!RValueRef && !SrcExpr->isLValue()) {
1214 // We know the left side is an lvalue reference, so we can suggest a reason.
1215 msg = diag::err_bad_cxx_cast_rvalue;
1216 return TC_NotApplicable;
1219 QualType DestPointee = DestReference->getPointeeType();
1221 // FIXME: If the source is a prvalue, we should issue a warning (because the
1222 // cast always has undefined behavior), and for AST consistency, we should
1223 // materialize a temporary.
1224 return TryStaticDowncast(Self,
1225 Self.Context.getCanonicalType(SrcExpr->getType()),
1226 Self.Context.getCanonicalType(DestPointee), CStyle,
1227 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1231 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1233 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1234 bool CStyle, SourceRange OpRange,
1235 unsigned &msg, CastKind &Kind,
1236 CXXCastPath &BasePath) {
1237 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1238 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1239 // is a class derived from B, if a valid standard conversion from "pointer
1240 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1242 // In addition, DR54 clarifies that the base must be accessible in the
1245 const PointerType *DestPointer = DestType->getAs<PointerType>();
1247 return TC_NotApplicable;
1250 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1252 msg = diag::err_bad_static_cast_pointer_nonpointer;
1253 return TC_NotApplicable;
1256 return TryStaticDowncast(Self,
1257 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1258 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1259 CStyle, OpRange, SrcType, DestType, msg, Kind,
1263 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1264 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1265 /// DestType is possible and allowed.
1267 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1268 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1269 QualType OrigDestType, unsigned &msg,
1270 CastKind &Kind, CXXCastPath &BasePath) {
1271 // We can only work with complete types. But don't complain if it doesn't work
1272 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1273 !Self.isCompleteType(OpRange.getBegin(), DestType))
1274 return TC_NotApplicable;
1276 // Downcast can only happen in class hierarchies, so we need classes.
1277 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1278 return TC_NotApplicable;
1281 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1282 /*DetectVirtual=*/true);
1283 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1284 return TC_NotApplicable;
1287 // Target type does derive from source type. Now we're serious. If an error
1288 // appears now, it's not ignored.
1289 // This may not be entirely in line with the standard. Take for example:
1291 // struct B : virtual A {
1297 // (void)static_cast<const B&>(*((A*)0));
1299 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1300 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1301 // However, both GCC and Comeau reject this example, and accepting it would
1302 // mean more complex code if we're to preserve the nice error message.
1303 // FIXME: Being 100% compliant here would be nice to have.
1305 // Must preserve cv, as always, unless we're in C-style mode.
1306 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1307 msg = diag::err_bad_cxx_cast_qualifiers_away;
1311 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1312 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1313 // that it builds the paths in reverse order.
1314 // To sum up: record all paths to the base and build a nice string from
1315 // them. Use it to spice up the error message.
1316 if (!Paths.isRecordingPaths()) {
1318 Paths.setRecordingPaths(true);
1319 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1321 std::string PathDisplayStr;
1322 std::set<unsigned> DisplayedPaths;
1323 for (clang::CXXBasePath &Path : Paths) {
1324 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1325 // We haven't displayed a path to this particular base
1326 // class subobject yet.
1327 PathDisplayStr += "\n ";
1328 for (CXXBasePathElement &PE : llvm::reverse(Path))
1329 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1330 PathDisplayStr += QualType(DestType).getAsString();
1334 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1335 << QualType(SrcType).getUnqualifiedType()
1336 << QualType(DestType).getUnqualifiedType()
1337 << PathDisplayStr << OpRange;
1342 if (Paths.getDetectedVirtual() != nullptr) {
1343 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1344 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1345 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1351 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1354 diag::err_downcast_from_inaccessible_base)) {
1355 case Sema::AR_accessible:
1356 case Sema::AR_delayed: // be optimistic
1357 case Sema::AR_dependent: // be optimistic
1360 case Sema::AR_inaccessible:
1366 Self.BuildBasePathArray(Paths, BasePath);
1367 Kind = CK_BaseToDerived;
1371 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1372 /// C++ 5.2.9p9 is valid:
1374 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1375 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1376 /// where B is a base class of D [...].
1379 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1380 QualType DestType, bool CStyle,
1381 SourceRange OpRange,
1382 unsigned &msg, CastKind &Kind,
1383 CXXCastPath &BasePath) {
1384 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1386 return TC_NotApplicable;
1388 bool WasOverloadedFunction = false;
1389 DeclAccessPair FoundOverload;
1390 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1391 if (FunctionDecl *Fn
1392 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1394 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1395 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1396 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1397 WasOverloadedFunction = true;
1401 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1403 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1404 return TC_NotApplicable;
1407 // Lock down the inheritance model right now in MS ABI, whether or not the
1408 // pointee types are the same.
1409 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1410 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1411 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1414 // T == T, modulo cv
1415 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1416 DestMemPtr->getPointeeType()))
1417 return TC_NotApplicable;
1420 QualType SrcClass(SrcMemPtr->getClass(), 0);
1421 QualType DestClass(DestMemPtr->getClass(), 0);
1422 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1423 /*DetectVirtual=*/true);
1424 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1425 return TC_NotApplicable;
1427 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1428 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1430 Paths.setRecordingPaths(true);
1432 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1435 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1436 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1437 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1442 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1443 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1444 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1450 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1451 DestClass, SrcClass,
1453 diag::err_upcast_to_inaccessible_base)) {
1454 case Sema::AR_accessible:
1455 case Sema::AR_delayed:
1456 case Sema::AR_dependent:
1457 // Optimistically assume that the delayed and dependent cases
1461 case Sema::AR_inaccessible:
1467 if (WasOverloadedFunction) {
1468 // Resolve the address of the overloaded function again, this time
1469 // allowing complaints if something goes wrong.
1470 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1479 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1480 if (!SrcExpr.isUsable()) {
1486 Self.BuildBasePathArray(Paths, BasePath);
1487 Kind = CK_DerivedToBaseMemberPointer;
1491 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1494 /// An expression e can be explicitly converted to a type T using a
1495 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1497 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1498 Sema::CheckedConversionKind CCK,
1499 SourceRange OpRange, unsigned &msg,
1500 CastKind &Kind, bool ListInitialization) {
1501 if (DestType->isRecordType()) {
1502 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1503 diag::err_bad_dynamic_cast_incomplete) ||
1504 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1505 diag::err_allocation_of_abstract_type)) {
1511 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1512 InitializationKind InitKind
1513 = (CCK == Sema::CCK_CStyleCast)
1514 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1516 : (CCK == Sema::CCK_FunctionalCast)
1517 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1518 : InitializationKind::CreateCast(OpRange);
1519 Expr *SrcExprRaw = SrcExpr.get();
1520 // FIXME: Per DR242, we should check for an implicit conversion sequence
1521 // or for a constructor that could be invoked by direct-initialization
1522 // here, not for an initialization sequence.
1523 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1525 // At this point of CheckStaticCast, if the destination is a reference,
1526 // or the expression is an overload expression this has to work.
1527 // There is no other way that works.
1528 // On the other hand, if we're checking a C-style cast, we've still got
1529 // the reinterpret_cast way.
1531 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1532 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1533 return TC_NotApplicable;
1535 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1536 if (Result.isInvalid()) {
1541 if (InitSeq.isConstructorInitialization())
1542 Kind = CK_ConstructorConversion;
1550 /// TryConstCast - See if a const_cast from source to destination is allowed,
1551 /// and perform it if it is.
1552 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1553 QualType DestType, bool CStyle,
1555 DestType = Self.Context.getCanonicalType(DestType);
1556 QualType SrcType = SrcExpr.get()->getType();
1557 bool NeedToMaterializeTemporary = false;
1559 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1561 // if a pointer to T1 can be explicitly converted to the type "pointer to
1562 // T2" using a const_cast, then the following conversions can also be
1564 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1565 // type T2 using the cast const_cast<T2&>;
1566 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1567 // type T2 using the cast const_cast<T2&&>; and
1568 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1569 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1571 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1572 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1573 // is C-style, static_cast might find a way, so we simply suggest a
1574 // message and tell the parent to keep searching.
1575 msg = diag::err_bad_cxx_cast_rvalue;
1576 return TC_NotApplicable;
1579 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1580 if (!SrcType->isRecordType()) {
1581 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1582 // this is C-style, static_cast can do this.
1583 msg = diag::err_bad_cxx_cast_rvalue;
1584 return TC_NotApplicable;
1587 // Materialize the class prvalue so that the const_cast can bind a
1589 NeedToMaterializeTemporary = true;
1592 // It's not completely clear under the standard whether we can
1593 // const_cast bit-field gl-values. Doing so would not be
1594 // intrinsically complicated, but for now, we say no for
1595 // consistency with other compilers and await the word of the
1597 if (SrcExpr.get()->refersToBitField()) {
1598 msg = diag::err_bad_cxx_cast_bitfield;
1599 return TC_NotApplicable;
1602 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1603 SrcType = Self.Context.getPointerType(SrcType);
1606 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1607 // the rules for const_cast are the same as those used for pointers.
1609 if (!DestType->isPointerType() &&
1610 !DestType->isMemberPointerType() &&
1611 !DestType->isObjCObjectPointerType()) {
1612 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1613 // was a reference type, we converted it to a pointer above.
1614 // The status of rvalue references isn't entirely clear, but it looks like
1615 // conversion to them is simply invalid.
1616 // C++ 5.2.11p3: For two pointer types [...]
1618 msg = diag::err_bad_const_cast_dest;
1619 return TC_NotApplicable;
1621 if (DestType->isFunctionPointerType() ||
1622 DestType->isMemberFunctionPointerType()) {
1623 // Cannot cast direct function pointers.
1624 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1625 // T is the ultimate pointee of source and target type.
1627 msg = diag::err_bad_const_cast_dest;
1628 return TC_NotApplicable;
1630 SrcType = Self.Context.getCanonicalType(SrcType);
1632 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1633 // completely equal.
1634 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1635 // in multi-level pointers may change, but the level count must be the same,
1636 // as must be the final pointee type.
1637 while (SrcType != DestType &&
1638 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1639 Qualifiers SrcQuals, DestQuals;
1640 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1641 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1643 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1644 // the other qualifiers (e.g., address spaces) are identical.
1645 SrcQuals.removeCVRQualifiers();
1646 DestQuals.removeCVRQualifiers();
1647 if (SrcQuals != DestQuals)
1648 return TC_NotApplicable;
1651 // Since we're dealing in canonical types, the remainder must be the same.
1652 if (SrcType != DestType)
1653 return TC_NotApplicable;
1655 if (NeedToMaterializeTemporary)
1656 // This is a const_cast from a class prvalue to an rvalue reference type.
1657 // Materialize a temporary to store the result of the conversion.
1658 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1660 /*IsLValueReference*/ false);
1665 // Checks for undefined behavior in reinterpret_cast.
1666 // The cases that is checked for is:
1667 // *reinterpret_cast<T*>(&a)
1668 // reinterpret_cast<T&>(a)
1669 // where accessing 'a' as type 'T' will result in undefined behavior.
1670 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1672 SourceRange Range) {
1673 unsigned DiagID = IsDereference ?
1674 diag::warn_pointer_indirection_from_incompatible_type :
1675 diag::warn_undefined_reinterpret_cast;
1677 if (Diags.isIgnored(DiagID, Range.getBegin()))
1680 QualType SrcTy, DestTy;
1681 if (IsDereference) {
1682 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1685 SrcTy = SrcType->getPointeeType();
1686 DestTy = DestType->getPointeeType();
1688 if (!DestType->getAs<ReferenceType>()) {
1692 DestTy = DestType->getPointeeType();
1695 // Cast is compatible if the types are the same.
1696 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1699 // or one of the types is a char or void type
1700 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1701 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1704 // or one of the types is a tag type.
1705 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1709 // FIXME: Scoped enums?
1710 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1711 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1712 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1717 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1720 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1721 QualType DestType) {
1722 QualType SrcType = SrcExpr.get()->getType();
1723 if (Self.Context.hasSameType(SrcType, DestType))
1725 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1726 if (SrcPtrTy->isObjCSelType()) {
1727 QualType DT = DestType;
1728 if (isa<PointerType>(DestType))
1729 DT = DestType->getPointeeType();
1730 if (!DT.getUnqualifiedType()->isVoidType())
1731 Self.Diag(SrcExpr.get()->getExprLoc(),
1732 diag::warn_cast_pointer_from_sel)
1733 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1737 /// Diagnose casts that change the calling convention of a pointer to a function
1738 /// defined in the current TU.
1739 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1740 QualType DstType, SourceRange OpRange) {
1741 // Check if this cast would change the calling convention of a function
1743 QualType SrcType = SrcExpr.get()->getType();
1744 if (Self.Context.hasSameType(SrcType, DstType) ||
1745 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1747 const auto *SrcFTy =
1748 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1749 const auto *DstFTy =
1750 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1751 CallingConv SrcCC = SrcFTy->getCallConv();
1752 CallingConv DstCC = DstFTy->getCallConv();
1756 // We have a calling convention cast. Check if the source is a pointer to a
1757 // known, specific function that has already been defined.
1758 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1759 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1760 if (UO->getOpcode() == UO_AddrOf)
1761 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1762 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1765 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1769 // Only warn if we are casting from the default convention to a non-default
1770 // convention. This can happen when the programmer forgot to apply the calling
1771 // convention to the function declaration and then inserted this cast to
1772 // satisfy the type system.
1773 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1774 FD->isVariadic(), FD->isCXXInstanceMember());
1775 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1778 // Diagnose this cast, as it is probably bad.
1779 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1780 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1781 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1782 << SrcCCName << DstCCName << OpRange;
1784 // The checks above are cheaper than checking if the diagnostic is enabled.
1785 // However, it's worth checking if the warning is enabled before we construct
1787 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1790 // Try to suggest a fixit to change the calling convention of the function
1791 // whose address was taken. Try to use the latest macro for the convention.
1792 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1793 // to match the Windows header declarations.
1794 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
1795 Preprocessor &PP = Self.getPreprocessor();
1796 SmallVector<TokenValue, 6> AttrTokens;
1797 SmallString<64> CCAttrText;
1798 llvm::raw_svector_ostream OS(CCAttrText);
1799 if (Self.getLangOpts().MicrosoftExt) {
1800 // __stdcall or __vectorcall
1801 OS << "__" << DstCCName;
1802 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1803 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1804 ? TokenValue(II->getTokenID())
1807 // __attribute__((stdcall)) or __attribute__((vectorcall))
1808 OS << "__attribute__((" << DstCCName << "))";
1809 AttrTokens.push_back(tok::kw___attribute);
1810 AttrTokens.push_back(tok::l_paren);
1811 AttrTokens.push_back(tok::l_paren);
1812 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1813 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1814 ? TokenValue(II->getTokenID())
1816 AttrTokens.push_back(tok::r_paren);
1817 AttrTokens.push_back(tok::r_paren);
1819 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1820 if (!AttrSpelling.empty())
1821 CCAttrText = AttrSpelling;
1823 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1824 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1827 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1828 const Expr *SrcExpr, QualType DestType,
1830 QualType SrcType = SrcExpr->getType();
1832 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1833 // are not explicit design choices, but consistent with GCC's behavior.
1834 // Feel free to modify them if you've reason/evidence for an alternative.
1835 if (CStyle && SrcType->isIntegralType(Self.Context)
1836 && !SrcType->isBooleanType()
1837 && !SrcType->isEnumeralType()
1838 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1839 && Self.Context.getTypeSize(DestType) >
1840 Self.Context.getTypeSize(SrcType)) {
1841 // Separate between casts to void* and non-void* pointers.
1842 // Some APIs use (abuse) void* for something like a user context,
1843 // and often that value is an integer even if it isn't a pointer itself.
1844 // Having a separate warning flag allows users to control the warning
1845 // for their workflow.
1846 unsigned Diag = DestType->isVoidPointerType() ?
1847 diag::warn_int_to_void_pointer_cast
1848 : diag::warn_int_to_pointer_cast;
1849 Self.Diag(Loc, Diag) << SrcType << DestType;
1853 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1854 ExprResult &Result) {
1855 // We can only fix an overloaded reinterpret_cast if
1856 // - it is a template with explicit arguments that resolves to an lvalue
1857 // unambiguously, or
1858 // - it is the only function in an overload set that may have its address
1861 Expr *E = Result.get();
1862 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1864 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1866 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1871 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1872 // preserves Result.
1874 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1875 Result, /*DoFunctionPointerConversion=*/true))
1877 return Result.isUsable();
1880 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
1881 QualType DestType, bool CStyle,
1882 SourceRange OpRange,
1885 bool IsLValueCast = false;
1887 DestType = Self.Context.getCanonicalType(DestType);
1888 QualType SrcType = SrcExpr.get()->getType();
1890 // Is the source an overloaded name? (i.e. &foo)
1891 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
1892 if (SrcType == Self.Context.OverloadTy) {
1893 ExprResult FixedExpr = SrcExpr;
1894 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
1895 return TC_NotApplicable;
1897 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1898 SrcExpr = FixedExpr;
1899 SrcType = SrcExpr.get()->getType();
1902 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1903 if (!SrcExpr.get()->isGLValue()) {
1904 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1905 // similar comment in const_cast.
1906 msg = diag::err_bad_cxx_cast_rvalue;
1907 return TC_NotApplicable;
1911 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1912 /*isDereference=*/false, OpRange);
1915 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1916 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1917 // built-in & and * operators.
1919 const char *inappropriate = nullptr;
1920 switch (SrcExpr.get()->getObjectKind()) {
1924 msg = diag::err_bad_cxx_cast_bitfield;
1925 return TC_NotApplicable;
1926 // FIXME: Use a specific diagnostic for the rest of these cases.
1927 case OK_VectorComponent: inappropriate = "vector element"; break;
1928 case OK_ObjCProperty: inappropriate = "property expression"; break;
1929 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1932 if (inappropriate) {
1933 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1934 << inappropriate << DestType
1935 << OpRange << SrcExpr.get()->getSourceRange();
1936 msg = 0; SrcExpr = ExprError();
1937 return TC_NotApplicable;
1940 // This code does this transformation for the checked types.
1941 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1942 SrcType = Self.Context.getPointerType(SrcType);
1944 IsLValueCast = true;
1947 // Canonicalize source for comparison.
1948 SrcType = Self.Context.getCanonicalType(SrcType);
1950 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1951 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1952 if (DestMemPtr && SrcMemPtr) {
1953 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1954 // can be explicitly converted to an rvalue of type "pointer to member
1955 // of Y of type T2" if T1 and T2 are both function types or both object
1957 if (DestMemPtr->isMemberFunctionPointer() !=
1958 SrcMemPtr->isMemberFunctionPointer())
1959 return TC_NotApplicable;
1961 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1963 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1965 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1966 /*CheckObjCLifetime=*/CStyle)) {
1967 msg = diag::err_bad_cxx_cast_qualifiers_away;
1971 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1972 // We need to determine the inheritance model that the class will use if
1974 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1975 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1978 // Don't allow casting between member pointers of different sizes.
1979 if (Self.Context.getTypeSize(DestMemPtr) !=
1980 Self.Context.getTypeSize(SrcMemPtr)) {
1981 msg = diag::err_bad_cxx_cast_member_pointer_size;
1985 // A valid member pointer cast.
1986 assert(!IsLValueCast);
1987 Kind = CK_ReinterpretMemberPointer;
1991 // See below for the enumeral issue.
1992 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1993 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1994 // type large enough to hold it. A value of std::nullptr_t can be
1995 // converted to an integral type; the conversion has the same meaning
1996 // and validity as a conversion of (void*)0 to the integral type.
1997 if (Self.Context.getTypeSize(SrcType) >
1998 Self.Context.getTypeSize(DestType)) {
1999 msg = diag::err_bad_reinterpret_cast_small_int;
2002 Kind = CK_PointerToIntegral;
2006 // Allow reinterpret_casts between vectors of the same size and
2007 // between vectors and integers of the same size.
2008 bool destIsVector = DestType->isVectorType();
2009 bool srcIsVector = SrcType->isVectorType();
2010 if (srcIsVector || destIsVector) {
2011 // The non-vector type, if any, must have integral type. This is
2012 // the same rule that C vector casts use; note, however, that enum
2013 // types are not integral in C++.
2014 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2015 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2016 return TC_NotApplicable;
2018 // The size we want to consider is eltCount * eltSize.
2019 // That's exactly what the lax-conversion rules will check.
2020 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2025 // Otherwise, pick a reasonable diagnostic.
2027 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2028 else if (!srcIsVector)
2029 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2031 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2036 if (SrcType == DestType) {
2037 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2038 // restrictions, a cast to the same type is allowed so long as it does not
2039 // cast away constness. In C++98, the intent was not entirely clear here,
2040 // since all other paragraphs explicitly forbid casts to the same type.
2041 // C++11 clarifies this case with p2.
2043 // The only allowed types are: integral, enumeration, pointer, or
2044 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2046 TryCastResult Result = TC_NotApplicable;
2047 if (SrcType->isIntegralOrEnumerationType() ||
2048 SrcType->isAnyPointerType() ||
2049 SrcType->isMemberPointerType() ||
2050 SrcType->isBlockPointerType()) {
2051 Result = TC_Success;
2056 bool destIsPtr = DestType->isAnyPointerType() ||
2057 DestType->isBlockPointerType();
2058 bool srcIsPtr = SrcType->isAnyPointerType() ||
2059 SrcType->isBlockPointerType();
2060 if (!destIsPtr && !srcIsPtr) {
2061 // Except for std::nullptr_t->integer and lvalue->reference, which are
2062 // handled above, at least one of the two arguments must be a pointer.
2063 return TC_NotApplicable;
2066 if (DestType->isIntegralType(Self.Context)) {
2067 assert(srcIsPtr && "One type must be a pointer");
2068 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2069 // type large enough to hold it; except in Microsoft mode, where the
2070 // integral type size doesn't matter (except we don't allow bool).
2071 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2072 !DestType->isBooleanType();
2073 if ((Self.Context.getTypeSize(SrcType) >
2074 Self.Context.getTypeSize(DestType)) &&
2075 !MicrosoftException) {
2076 msg = diag::err_bad_reinterpret_cast_small_int;
2079 Kind = CK_PointerToIntegral;
2083 if (SrcType->isIntegralOrEnumerationType()) {
2084 assert(destIsPtr && "One type must be a pointer");
2085 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2087 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2088 // converted to a pointer.
2089 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2090 // necessarily converted to a null pointer value.]
2091 Kind = CK_IntegralToPointer;
2095 if (!destIsPtr || !srcIsPtr) {
2096 // With the valid non-pointer conversions out of the way, we can be even
2098 return TC_NotApplicable;
2101 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2102 // The C-style cast operator can.
2103 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2104 /*CheckObjCLifetime=*/CStyle)) {
2105 msg = diag::err_bad_cxx_cast_qualifiers_away;
2109 // Cannot convert between block pointers and Objective-C object pointers.
2110 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2111 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2112 return TC_NotApplicable;
2115 Kind = CK_LValueBitCast;
2116 } else if (DestType->isObjCObjectPointerType()) {
2117 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2118 } else if (DestType->isBlockPointerType()) {
2119 if (!SrcType->isBlockPointerType()) {
2120 Kind = CK_AnyPointerToBlockPointerCast;
2128 // Any pointer can be cast to an Objective-C pointer type with a C-style
2130 if (CStyle && DestType->isObjCObjectPointerType()) {
2134 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2136 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2138 // Not casting away constness, so the only remaining check is for compatible
2139 // pointer categories.
2141 if (SrcType->isFunctionPointerType()) {
2142 if (DestType->isFunctionPointerType()) {
2143 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2144 // a pointer to a function of a different type.
2148 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2149 // an object type or vice versa is conditionally-supported.
2150 // Compilers support it in C++03 too, though, because it's necessary for
2151 // casting the return value of dlsym() and GetProcAddress().
2152 // FIXME: Conditionally-supported behavior should be configurable in the
2153 // TargetInfo or similar.
2154 Self.Diag(OpRange.getBegin(),
2155 Self.getLangOpts().CPlusPlus11 ?
2156 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2161 if (DestType->isFunctionPointerType()) {
2163 Self.Diag(OpRange.getBegin(),
2164 Self.getLangOpts().CPlusPlus11 ?
2165 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2170 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2171 // a pointer to an object of different type.
2172 // Void pointers are not specified, but supported by every compiler out there.
2173 // So we finish by allowing everything that remains - it's got to be two
2178 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2179 bool ListInitialization) {
2180 // Handle placeholders.
2181 if (isPlaceholder()) {
2182 // C-style casts can resolve __unknown_any types.
2183 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2184 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2185 SrcExpr.get(), Kind,
2186 ValueKind, BasePath);
2190 checkNonOverloadPlaceholders();
2191 if (SrcExpr.isInvalid())
2195 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2196 // This test is outside everything else because it's the only case where
2197 // a non-lvalue-reference target type does not lead to decay.
2198 if (DestType->isVoidType()) {
2201 if (claimPlaceholder(BuiltinType::Overload)) {
2202 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2203 SrcExpr, /* Decay Function to ptr */ false,
2204 /* Complain */ true, DestRange, DestType,
2205 diag::err_bad_cstyle_cast_overload);
2206 if (SrcExpr.isInvalid())
2210 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2214 // If the type is dependent, we won't do any other semantic analysis now.
2215 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2216 SrcExpr.get()->isValueDependent()) {
2217 assert(Kind == CK_Dependent);
2221 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2222 !isPlaceholder(BuiltinType::Overload)) {
2223 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2224 if (SrcExpr.isInvalid())
2228 // AltiVec vector initialization with a single literal.
2229 if (const VectorType *vecTy = DestType->getAs<VectorType>())
2230 if (vecTy->getVectorKind() == VectorType::AltiVecVector
2231 && (SrcExpr.get()->getType()->isIntegerType()
2232 || SrcExpr.get()->getType()->isFloatingType())) {
2233 Kind = CK_VectorSplat;
2234 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2238 // C++ [expr.cast]p5: The conversions performed by
2241 // - a static_cast followed by a const_cast,
2242 // - a reinterpret_cast, or
2243 // - a reinterpret_cast followed by a const_cast,
2244 // can be performed using the cast notation of explicit type conversion.
2245 // [...] If a conversion can be interpreted in more than one of the ways
2246 // listed above, the interpretation that appears first in the list is used,
2247 // even if a cast resulting from that interpretation is ill-formed.
2248 // In plain language, this means trying a const_cast ...
2249 unsigned msg = diag::err_bad_cxx_cast_generic;
2250 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2251 /*CStyle*/true, msg);
2252 if (SrcExpr.isInvalid())
2254 if (tcr == TC_Success)
2257 Sema::CheckedConversionKind CCK
2258 = FunctionalStyle? Sema::CCK_FunctionalCast
2259 : Sema::CCK_CStyleCast;
2260 if (tcr == TC_NotApplicable) {
2261 // ... or if that is not possible, a static_cast, ignoring const, ...
2262 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2263 msg, Kind, BasePath, ListInitialization);
2264 if (SrcExpr.isInvalid())
2267 if (tcr == TC_NotApplicable) {
2268 // ... and finally a reinterpret_cast, ignoring const.
2269 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2270 OpRange, msg, Kind);
2271 if (SrcExpr.isInvalid())
2276 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2278 checkObjCConversion(CCK);
2280 if (tcr != TC_Success && msg != 0) {
2281 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2282 DeclAccessPair Found;
2283 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2288 // If DestType is a function type (not to be confused with the function
2289 // pointer type), it will be possible to resolve the function address,
2290 // but the type cast should be considered as failure.
2291 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2292 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2293 << OE->getName() << DestType << OpRange
2294 << OE->getQualifierLoc().getSourceRange();
2295 Self.NoteAllOverloadCandidates(SrcExpr.get());
2298 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2299 OpRange, SrcExpr.get(), DestType, ListInitialization);
2301 } else if (Kind == CK_BitCast) {
2305 // Clear out SrcExpr if there was a fatal error.
2306 if (tcr != TC_Success)
2307 SrcExpr = ExprError();
2310 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2311 /// non-matching type. Such as enum function call to int, int call to
2312 /// pointer; etc. Cast to 'void' is an exception.
2313 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2314 QualType DestType) {
2315 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2316 SrcExpr.get()->getExprLoc()))
2319 if (!isa<CallExpr>(SrcExpr.get()))
2322 QualType SrcType = SrcExpr.get()->getType();
2323 if (DestType.getUnqualifiedType()->isVoidType())
2325 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2326 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2328 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2329 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2330 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2332 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2334 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2336 if (SrcType->isComplexType() && DestType->isComplexType())
2338 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2341 Self.Diag(SrcExpr.get()->getExprLoc(),
2342 diag::warn_bad_function_cast)
2343 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2346 /// Check the semantics of a C-style cast operation, in C.
2347 void CastOperation::CheckCStyleCast() {
2348 assert(!Self.getLangOpts().CPlusPlus);
2350 // C-style casts can resolve __unknown_any types.
2351 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2352 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2353 SrcExpr.get(), Kind,
2354 ValueKind, BasePath);
2358 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2359 // type needs to be scalar.
2360 if (DestType->isVoidType()) {
2361 // We don't necessarily do lvalue-to-rvalue conversions on this.
2362 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2363 if (SrcExpr.isInvalid())
2366 // Cast to void allows any expr type.
2371 // Overloads are allowed with C extensions, so we need to support them.
2372 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2374 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2375 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2376 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2379 assert(SrcExpr.isUsable());
2381 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2382 if (SrcExpr.isInvalid())
2384 QualType SrcType = SrcExpr.get()->getType();
2386 assert(!SrcType->isPlaceholderType());
2388 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2389 // address space B is illegal.
2390 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2391 SrcType->isPointerType()) {
2392 const PointerType *DestPtr = DestType->getAs<PointerType>();
2393 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
2394 Self.Diag(OpRange.getBegin(),
2395 diag::err_typecheck_incompatible_address_space)
2396 << SrcType << DestType << Sema::AA_Casting
2397 << SrcExpr.get()->getSourceRange();
2398 SrcExpr = ExprError();
2403 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2404 diag::err_typecheck_cast_to_incomplete)) {
2405 SrcExpr = ExprError();
2409 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2410 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2412 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2413 // GCC struct/union extension: allow cast to self.
2414 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2415 << DestType << SrcExpr.get()->getSourceRange();
2420 // GCC's cast to union extension.
2421 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2422 RecordDecl *RD = DestRecordTy->getDecl();
2423 RecordDecl::field_iterator Field, FieldEnd;
2424 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2425 Field != FieldEnd; ++Field) {
2426 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2427 !Field->isUnnamedBitfield()) {
2428 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2429 << SrcExpr.get()->getSourceRange();
2433 if (Field == FieldEnd) {
2434 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2435 << SrcType << SrcExpr.get()->getSourceRange();
2436 SrcExpr = ExprError();
2443 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2444 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2445 llvm::APSInt CastInt;
2446 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2448 Kind = CK_ZeroToOCLEvent;
2451 Self.Diag(OpRange.getBegin(),
2452 diag::err_opencl_cast_non_zero_to_event_t)
2453 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2454 SrcExpr = ExprError();
2459 // Reject any other conversions to non-scalar types.
2460 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2461 << DestType << SrcExpr.get()->getSourceRange();
2462 SrcExpr = ExprError();
2466 // The type we're casting to is known to be a scalar or vector.
2468 // Require the operand to be a scalar or vector.
2469 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2470 Self.Diag(SrcExpr.get()->getExprLoc(),
2471 diag::err_typecheck_expect_scalar_operand)
2472 << SrcType << SrcExpr.get()->getSourceRange();
2473 SrcExpr = ExprError();
2477 if (DestType->isExtVectorType()) {
2478 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2482 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2483 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2484 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2485 Kind = CK_VectorSplat;
2486 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2487 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2488 SrcExpr = ExprError();
2493 if (SrcType->isVectorType()) {
2494 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2495 SrcExpr = ExprError();
2499 // The source and target types are both scalars, i.e.
2500 // - arithmetic types (fundamental, enum, and complex)
2501 // - all kinds of pointers
2502 // Note that member pointers were filtered out with C++, above.
2504 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2505 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2506 SrcExpr = ExprError();
2510 // If either type is a pointer, the other type has to be either an
2511 // integer or a pointer.
2512 if (!DestType->isArithmeticType()) {
2513 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2514 Self.Diag(SrcExpr.get()->getExprLoc(),
2515 diag::err_cast_pointer_from_non_pointer_int)
2516 << SrcType << SrcExpr.get()->getSourceRange();
2517 SrcExpr = ExprError();
2520 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2522 } else if (!SrcType->isArithmeticType()) {
2523 if (!DestType->isIntegralType(Self.Context) &&
2524 DestType->isArithmeticType()) {
2525 Self.Diag(SrcExpr.get()->getLocStart(),
2526 diag::err_cast_pointer_to_non_pointer_int)
2527 << DestType << SrcExpr.get()->getSourceRange();
2528 SrcExpr = ExprError();
2533 if (Self.getLangOpts().OpenCL &&
2534 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
2535 if (DestType->isHalfType()) {
2536 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2537 << DestType << SrcExpr.get()->getSourceRange();
2538 SrcExpr = ExprError();
2543 // ARC imposes extra restrictions on casts.
2544 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2545 checkObjCConversion(Sema::CCK_CStyleCast);
2546 if (SrcExpr.isInvalid())
2549 const PointerType *CastPtr = DestType->getAs<PointerType>();
2550 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
2551 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2552 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2553 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2554 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2555 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2556 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2557 Self.Diag(SrcExpr.get()->getLocStart(),
2558 diag::err_typecheck_incompatible_ownership)
2559 << SrcType << DestType << Sema::AA_Casting
2560 << SrcExpr.get()->getSourceRange();
2565 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2566 Self.Diag(SrcExpr.get()->getLocStart(),
2567 diag::err_arc_convesion_of_weak_unavailable)
2568 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2569 SrcExpr = ExprError();
2574 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2575 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2576 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2577 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2578 if (SrcExpr.isInvalid())
2581 if (Kind == CK_BitCast)
2585 QualType TheOffendingSrcType, TheOffendingDestType;
2586 Qualifiers CastAwayQualifiers;
2587 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
2588 CastsAwayConstness(Self, SrcType, DestType, true, false,
2589 &TheOffendingSrcType, &TheOffendingDestType,
2590 &CastAwayQualifiers)) {
2591 int qualifiers = -1;
2592 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2594 } else if (CastAwayQualifiers.hasConst()) {
2596 } else if (CastAwayQualifiers.hasVolatile()) {
2599 // This is a variant of int **x; const int **y = (const int **)x;
2600 if (qualifiers == -1)
2601 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
2602 SrcType << DestType;
2604 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
2605 TheOffendingSrcType << TheOffendingDestType << qualifiers;
2609 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2610 TypeSourceInfo *CastTypeInfo,
2611 SourceLocation RPLoc,
2613 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2614 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2615 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2617 if (getLangOpts().CPlusPlus) {
2618 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2619 isa<InitListExpr>(CastExpr));
2621 Op.CheckCStyleCast();
2624 if (Op.SrcExpr.isInvalid())
2627 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2628 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
2629 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2632 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2634 SourceLocation LPLoc,
2636 SourceLocation RPLoc) {
2637 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2638 CastOperation Op(*this, Type, CastExpr);
2639 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2640 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2642 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2643 if (Op.SrcExpr.isInvalid())
2646 auto *SubExpr = Op.SrcExpr.get();
2647 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2648 SubExpr = BindExpr->getSubExpr();
2649 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
2650 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
2652 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2653 Op.ValueKind, CastTypeInfo, Op.Kind,
2654 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));