1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for cast expressions, including
10 // 1) C-style casts like '(int) x'
11 // 2) C++ functional casts like 'int(x)'
12 // 3) C++ named casts like 'static_cast<int>(x)'
14 //===----------------------------------------------------------------------===//
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/SemaInternal.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
30 using namespace clang
;
35 TC_NotApplicable
, ///< The cast method is not applicable.
36 TC_Success
, ///< The cast method is appropriate and successful.
37 TC_Extension
, ///< The cast method is appropriate and accepted as a
38 ///< language extension.
39 TC_Failed
///< The cast method is appropriate, but failed. A
40 ///< diagnostic has been emitted.
43 static bool isValidCast(TryCastResult TCR
) {
44 return TCR
== TC_Success
|| TCR
== TC_Extension
;
48 CT_Const
, ///< const_cast
49 CT_Static
, ///< static_cast
50 CT_Reinterpret
, ///< reinterpret_cast
51 CT_Dynamic
, ///< dynamic_cast
52 CT_CStyle
, ///< (Type)expr
53 CT_Functional
, ///< Type(expr)
54 CT_Addrspace
///< addrspace_cast
58 struct CastOperation
{
59 CastOperation(Sema
&S
, QualType destType
, ExprResult src
)
60 : Self(S
), SrcExpr(src
), DestType(destType
),
61 ResultType(destType
.getNonLValueExprType(S
.Context
)),
62 ValueKind(Expr::getValueKindForType(destType
)),
63 Kind(CK_Dependent
), IsARCUnbridgedCast(false) {
65 // C++ [expr.type]/8.2.2:
66 // If a pr-value initially has the type cv-T, where T is a
67 // cv-unqualified non-class, non-array type, the type of the
68 // expression is adjusted to T prior to any further analysis.
70 // Preceding an expression by a parenthesized type name converts the
71 // value of the expression to the unqualified, non-atomic version of
73 if (!S
.Context
.getLangOpts().ObjC
&& !DestType
->isRecordType() &&
74 !DestType
->isArrayType()) {
75 DestType
= DestType
.getAtomicUnqualifiedType();
78 if (const BuiltinType
*placeholder
=
79 src
.get()->getType()->getAsPlaceholderType()) {
80 PlaceholderKind
= placeholder
->getKind();
82 PlaceholderKind
= (BuiltinType::Kind
) 0;
90 ExprValueKind ValueKind
;
92 BuiltinType::Kind PlaceholderKind
;
94 bool IsARCUnbridgedCast
;
97 SourceRange DestRange
;
99 // Top-level semantics-checking routines.
100 void CheckConstCast();
101 void CheckReinterpretCast();
102 void CheckStaticCast();
103 void CheckDynamicCast();
104 void CheckCXXCStyleCast(bool FunctionalCast
, bool ListInitialization
);
105 void CheckCStyleCast();
106 void CheckBuiltinBitCast();
107 void CheckAddrspaceCast();
109 void updatePartOfExplicitCastFlags(CastExpr
*CE
) {
110 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
111 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
112 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
113 for (; auto *ICE
= dyn_cast
<ImplicitCastExpr
>(CE
->getSubExpr()); CE
= ICE
)
114 ICE
->setIsPartOfExplicitCast(true);
117 /// Complete an apparently-successful cast operation that yields
118 /// the given expression.
119 ExprResult
complete(CastExpr
*castExpr
) {
120 // If this is an unbridged cast, wrap the result in an implicit
121 // cast that yields the unbridged-cast placeholder type.
122 if (IsARCUnbridgedCast
) {
123 castExpr
= ImplicitCastExpr::Create(
124 Self
.Context
, Self
.Context
.ARCUnbridgedCastTy
, CK_Dependent
,
125 castExpr
, nullptr, castExpr
->getValueKind(),
126 Self
.CurFPFeatureOverrides());
128 updatePartOfExplicitCastFlags(castExpr
);
132 // Internal convenience methods.
134 /// Try to handle the given placeholder expression kind. Return
135 /// true if the source expression has the appropriate placeholder
136 /// kind. A placeholder can only be claimed once.
137 bool claimPlaceholder(BuiltinType::Kind K
) {
138 if (PlaceholderKind
!= K
) return false;
140 PlaceholderKind
= (BuiltinType::Kind
) 0;
144 bool isPlaceholder() const {
145 return PlaceholderKind
!= 0;
147 bool isPlaceholder(BuiltinType::Kind K
) const {
148 return PlaceholderKind
== K
;
151 // Language specific cast restrictions for address spaces.
152 void checkAddressSpaceCast(QualType SrcType
, QualType DestType
);
154 void checkCastAlign() {
155 Self
.CheckCastAlign(SrcExpr
.get(), DestType
, OpRange
);
158 void checkObjCConversion(Sema::CheckedConversionKind CCK
) {
159 assert(Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
161 Expr
*src
= SrcExpr
.get();
162 if (Self
.CheckObjCConversion(OpRange
, DestType
, src
, CCK
) ==
164 IsARCUnbridgedCast
= true;
168 /// Check for and handle non-overload placeholder expressions.
169 void checkNonOverloadPlaceholders() {
170 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload
))
173 SrcExpr
= Self
.CheckPlaceholderExpr(SrcExpr
.get());
174 if (SrcExpr
.isInvalid())
176 PlaceholderKind
= (BuiltinType::Kind
) 0;
180 void CheckNoDeref(Sema
&S
, const QualType FromType
, const QualType ToType
,
181 SourceLocation OpLoc
) {
182 if (const auto *PtrType
= dyn_cast
<PointerType
>(FromType
)) {
183 if (PtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
184 if (const auto *DestType
= dyn_cast
<PointerType
>(ToType
)) {
185 if (!DestType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
186 S
.Diag(OpLoc
, diag::warn_noderef_to_dereferenceable_pointer
);
193 struct CheckNoDerefRAII
{
194 CheckNoDerefRAII(CastOperation
&Op
) : Op(Op
) {}
195 ~CheckNoDerefRAII() {
196 if (!Op
.SrcExpr
.isInvalid())
197 CheckNoDeref(Op
.Self
, Op
.SrcExpr
.get()->getType(), Op
.ResultType
,
198 Op
.OpRange
.getBegin());
205 static void DiagnoseCastQual(Sema
&Self
, const ExprResult
&SrcExpr
,
208 // The Try functions attempt a specific way of casting. If they succeed, they
209 // return TC_Success. If their way of casting is not appropriate for the given
210 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
211 // to emit if no other way succeeds. If their way of casting is appropriate but
212 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
213 // they emit a specialized diagnostic.
214 // All diagnostics returned by these functions must expect the same three
216 // %0: Cast Type (a value from the CastType enumeration)
218 // %2: Destination Type
219 static TryCastResult
TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
,
220 QualType DestType
, bool CStyle
,
222 CXXCastPath
&BasePath
,
224 static TryCastResult
TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
,
225 QualType DestType
, bool CStyle
,
229 CXXCastPath
&BasePath
);
230 static TryCastResult
TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
,
231 QualType DestType
, bool CStyle
,
235 CXXCastPath
&BasePath
);
236 static TryCastResult
TryStaticDowncast(Sema
&Self
, CanQualType SrcType
,
237 CanQualType DestType
, bool CStyle
,
239 QualType OrigSrcType
,
240 QualType OrigDestType
, unsigned &msg
,
242 CXXCastPath
&BasePath
);
243 static TryCastResult
TryStaticMemberPointerUpcast(Sema
&Self
, ExprResult
&SrcExpr
,
245 QualType DestType
,bool CStyle
,
249 CXXCastPath
&BasePath
);
251 static TryCastResult
TryStaticImplicitCast(Sema
&Self
, ExprResult
&SrcExpr
,
253 Sema::CheckedConversionKind CCK
,
255 unsigned &msg
, CastKind
&Kind
,
256 bool ListInitialization
);
257 static TryCastResult
TryStaticCast(Sema
&Self
, ExprResult
&SrcExpr
,
259 Sema::CheckedConversionKind CCK
,
261 unsigned &msg
, CastKind
&Kind
,
262 CXXCastPath
&BasePath
,
263 bool ListInitialization
);
264 static TryCastResult
TryConstCast(Sema
&Self
, ExprResult
&SrcExpr
,
265 QualType DestType
, bool CStyle
,
267 static TryCastResult
TryReinterpretCast(Sema
&Self
, ExprResult
&SrcExpr
,
268 QualType DestType
, bool CStyle
,
269 SourceRange OpRange
, unsigned &msg
,
271 static TryCastResult
TryAddressSpaceCast(Sema
&Self
, ExprResult
&SrcExpr
,
272 QualType DestType
, bool CStyle
,
273 unsigned &msg
, CastKind
&Kind
);
275 /// ActOnCXXNamedCast - Parse
276 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
278 Sema::ActOnCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
279 SourceLocation LAngleBracketLoc
, Declarator
&D
,
280 SourceLocation RAngleBracketLoc
,
281 SourceLocation LParenLoc
, Expr
*E
,
282 SourceLocation RParenLoc
) {
284 assert(!D
.isInvalidType());
286 TypeSourceInfo
*TInfo
= GetTypeForDeclaratorCast(D
, E
->getType());
287 if (D
.isInvalidType())
290 if (getLangOpts().CPlusPlus
) {
291 // Check that there are no default arguments (C++ only).
292 CheckExtraCXXDefaultArguments(D
);
295 return BuildCXXNamedCast(OpLoc
, Kind
, TInfo
, E
,
296 SourceRange(LAngleBracketLoc
, RAngleBracketLoc
),
297 SourceRange(LParenLoc
, RParenLoc
));
301 Sema::BuildCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
302 TypeSourceInfo
*DestTInfo
, Expr
*E
,
303 SourceRange AngleBrackets
, SourceRange Parens
) {
305 QualType DestType
= DestTInfo
->getType();
307 // If the type is dependent, we won't do the semantic analysis now.
309 DestType
->isDependentType() || Ex
.get()->isTypeDependent();
311 CastOperation
Op(*this, DestType
, E
);
312 Op
.OpRange
= SourceRange(OpLoc
, Parens
.getEnd());
313 Op
.DestRange
= AngleBrackets
;
316 default: llvm_unreachable("Unknown C++ cast!");
318 case tok::kw_addrspace_cast
:
319 if (!TypeDependent
) {
320 Op
.CheckAddrspaceCast();
321 if (Op
.SrcExpr
.isInvalid())
324 return Op
.complete(CXXAddrspaceCastExpr::Create(
325 Context
, Op
.ResultType
, Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
326 DestTInfo
, OpLoc
, Parens
.getEnd(), AngleBrackets
));
328 case tok::kw_const_cast
:
329 if (!TypeDependent
) {
331 if (Op
.SrcExpr
.isInvalid())
333 DiscardMisalignedMemberAddress(DestType
.getTypePtr(), E
);
335 return Op
.complete(CXXConstCastExpr::Create(Context
, Op
.ResultType
,
336 Op
.ValueKind
, Op
.SrcExpr
.get(), DestTInfo
,
337 OpLoc
, Parens
.getEnd(),
340 case tok::kw_dynamic_cast
: {
341 // dynamic_cast is not supported in C++ for OpenCL.
342 if (getLangOpts().OpenCLCPlusPlus
) {
343 return ExprError(Diag(OpLoc
, diag::err_openclcxx_not_supported
)
347 if (!TypeDependent
) {
348 Op
.CheckDynamicCast();
349 if (Op
.SrcExpr
.isInvalid())
352 return Op
.complete(CXXDynamicCastExpr::Create(Context
, Op
.ResultType
,
353 Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
354 &Op
.BasePath
, DestTInfo
,
355 OpLoc
, Parens
.getEnd(),
358 case tok::kw_reinterpret_cast
: {
359 if (!TypeDependent
) {
360 Op
.CheckReinterpretCast();
361 if (Op
.SrcExpr
.isInvalid())
363 DiscardMisalignedMemberAddress(DestType
.getTypePtr(), E
);
365 return Op
.complete(CXXReinterpretCastExpr::Create(Context
, Op
.ResultType
,
366 Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
367 nullptr, DestTInfo
, OpLoc
,
371 case tok::kw_static_cast
: {
372 if (!TypeDependent
) {
373 Op
.CheckStaticCast();
374 if (Op
.SrcExpr
.isInvalid())
376 DiscardMisalignedMemberAddress(DestType
.getTypePtr(), E
);
379 return Op
.complete(CXXStaticCastExpr::Create(
380 Context
, Op
.ResultType
, Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
381 &Op
.BasePath
, DestTInfo
, CurFPFeatureOverrides(), OpLoc
,
382 Parens
.getEnd(), AngleBrackets
));
387 ExprResult
Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc
, Declarator
&D
,
389 SourceLocation RParenLoc
) {
390 assert(!D
.isInvalidType());
392 TypeSourceInfo
*TInfo
= GetTypeForDeclaratorCast(D
, Operand
.get()->getType());
393 if (D
.isInvalidType())
396 return BuildBuiltinBitCastExpr(KWLoc
, TInfo
, Operand
.get(), RParenLoc
);
399 ExprResult
Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc
,
400 TypeSourceInfo
*TSI
, Expr
*Operand
,
401 SourceLocation RParenLoc
) {
402 CastOperation
Op(*this, TSI
->getType(), Operand
);
403 Op
.OpRange
= SourceRange(KWLoc
, RParenLoc
);
404 TypeLoc TL
= TSI
->getTypeLoc();
405 Op
.DestRange
= SourceRange(TL
.getBeginLoc(), TL
.getEndLoc());
407 if (!Operand
->isTypeDependent() && !TSI
->getType()->isDependentType()) {
408 Op
.CheckBuiltinBitCast();
409 if (Op
.SrcExpr
.isInvalid())
413 BuiltinBitCastExpr
*BCE
=
414 new (Context
) BuiltinBitCastExpr(Op
.ResultType
, Op
.ValueKind
, Op
.Kind
,
415 Op
.SrcExpr
.get(), TSI
, KWLoc
, RParenLoc
);
416 return Op
.complete(BCE
);
419 /// Try to diagnose a failed overloaded cast. Returns true if
420 /// diagnostics were emitted.
421 static bool tryDiagnoseOverloadedCast(Sema
&S
, CastType CT
,
422 SourceRange range
, Expr
*src
,
424 bool listInitialization
) {
426 // These cast kinds don't consider user-defined conversions.
440 QualType srcType
= src
->getType();
441 if (!destType
->isRecordType() && !srcType
->isRecordType())
444 InitializedEntity entity
= InitializedEntity::InitializeTemporary(destType
);
445 InitializationKind initKind
446 = (CT
== CT_CStyle
)? InitializationKind::CreateCStyleCast(range
.getBegin(),
447 range
, listInitialization
)
448 : (CT
== CT_Functional
)? InitializationKind::CreateFunctionalCast(range
,
450 : InitializationKind::CreateCast(/*type range?*/ range
);
451 InitializationSequence
sequence(S
, entity
, initKind
, src
);
453 assert(sequence
.Failed() && "initialization succeeded on second try?");
454 switch (sequence
.getFailureKind()) {
455 default: return false;
457 case InitializationSequence::FK_ParenthesizedListInitFailed
:
458 // In C++20, if the underlying destination type is a RecordType, Clang
459 // attempts to perform parentesized aggregate initialization if constructor
462 // C++20 [expr.static.cast]p4:
463 // An expression E can be explicitly converted to a type T...if overload
464 // resolution for a direct-initialization...would find at least one viable
465 // function ([over.match.viable]), or if T is an aggregate type having a
466 // first element X and there is an implicit conversion sequence from E to
469 // If that fails, then we'll generate the diagnostics from the failed
470 // previous constructor overload attempt. Array initialization, however, is
471 // not done after attempting constructor overloading, so we exit as there
472 // won't be a failed overload result.
473 if (destType
->isArrayType())
476 case InitializationSequence::FK_ConstructorOverloadFailed
:
477 case InitializationSequence::FK_UserConversionOverloadFailed
:
481 OverloadCandidateSet
&candidates
= sequence
.getFailedCandidateSet();
484 OverloadCandidateDisplayKind howManyCandidates
= OCD_AllCandidates
;
486 switch (sequence
.getFailedOverloadResult()) {
487 case OR_Success
: llvm_unreachable("successful failed overload");
488 case OR_No_Viable_Function
:
489 if (candidates
.empty())
490 msg
= diag::err_ovl_no_conversion_in_cast
;
492 msg
= diag::err_ovl_no_viable_conversion_in_cast
;
493 howManyCandidates
= OCD_AllCandidates
;
497 msg
= diag::err_ovl_ambiguous_conversion_in_cast
;
498 howManyCandidates
= OCD_AmbiguousCandidates
;
502 msg
= diag::err_ovl_deleted_conversion_in_cast
;
503 howManyCandidates
= OCD_ViableCandidates
;
507 candidates
.NoteCandidates(
508 PartialDiagnosticAt(range
.getBegin(),
509 S
.PDiag(msg
) << CT
<< srcType
<< destType
<< range
510 << src
->getSourceRange()),
511 S
, howManyCandidates
, src
);
516 /// Diagnose a failed cast.
517 static void diagnoseBadCast(Sema
&S
, unsigned msg
, CastType castType
,
518 SourceRange opRange
, Expr
*src
, QualType destType
,
519 bool listInitialization
) {
520 if (msg
== diag::err_bad_cxx_cast_generic
&&
521 tryDiagnoseOverloadedCast(S
, castType
, opRange
, src
, destType
,
525 S
.Diag(opRange
.getBegin(), msg
) << castType
526 << src
->getType() << destType
<< opRange
<< src
->getSourceRange();
528 // Detect if both types are (ptr to) class, and note any incompleteness.
529 int DifferentPtrness
= 0;
530 QualType From
= destType
;
531 if (auto Ptr
= From
->getAs
<PointerType
>()) {
532 From
= Ptr
->getPointeeType();
535 QualType To
= src
->getType();
536 if (auto Ptr
= To
->getAs
<PointerType
>()) {
537 To
= Ptr
->getPointeeType();
540 if (!DifferentPtrness
) {
541 auto RecFrom
= From
->getAs
<RecordType
>();
542 auto RecTo
= To
->getAs
<RecordType
>();
543 if (RecFrom
&& RecTo
) {
544 auto DeclFrom
= RecFrom
->getAsCXXRecordDecl();
545 if (!DeclFrom
->isCompleteDefinition())
546 S
.Diag(DeclFrom
->getLocation(), diag::note_type_incomplete
) << DeclFrom
;
547 auto DeclTo
= RecTo
->getAsCXXRecordDecl();
548 if (!DeclTo
->isCompleteDefinition())
549 S
.Diag(DeclTo
->getLocation(), diag::note_type_incomplete
) << DeclTo
;
555 /// The kind of unwrapping we did when determining whether a conversion casts
557 enum CastAwayConstnessKind
{
558 /// The conversion does not cast away constness.
560 /// We unwrapped similar types.
562 /// We unwrapped dissimilar types with similar representations (eg, a pointer
563 /// versus an Objective-C object pointer).
564 CACK_SimilarKind
= 2,
565 /// We unwrapped representationally-unrelated types, such as a pointer versus
566 /// a pointer-to-member.
571 /// Unwrap one level of types for CastsAwayConstness.
573 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
574 /// both types, provided that they're both pointer-like or array-like. Unlike
575 /// the Sema function, doesn't care if the unwrapped pieces are related.
577 /// This function may remove additional levels as necessary for correctness:
578 /// the resulting T1 is unwrapped sufficiently that it is never an array type,
579 /// so that its qualifiers can be directly compared to those of T2 (which will
580 /// have the combined set of qualifiers from all indermediate levels of T2),
581 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
582 /// with those from T2.
583 static CastAwayConstnessKind
584 unwrapCastAwayConstnessLevel(ASTContext
&Context
, QualType
&T1
, QualType
&T2
) {
585 enum { None
, Ptr
, MemPtr
, BlockPtr
, Array
};
586 auto Classify
= [](QualType T
) {
587 if (T
->isAnyPointerType()) return Ptr
;
588 if (T
->isMemberPointerType()) return MemPtr
;
589 if (T
->isBlockPointerType()) return BlockPtr
;
590 // We somewhat-arbitrarily don't look through VLA types here. This is at
591 // least consistent with the behavior of UnwrapSimilarTypes.
592 if (T
->isConstantArrayType() || T
->isIncompleteArrayType()) return Array
;
596 auto Unwrap
= [&](QualType T
) {
597 if (auto *AT
= Context
.getAsArrayType(T
))
598 return AT
->getElementType();
599 return T
->getPointeeType();
602 CastAwayConstnessKind Kind
;
604 if (T2
->isReferenceType()) {
605 // Special case: if the destination type is a reference type, unwrap it as
606 // the first level. (The source will have been an lvalue expression in this
607 // case, so there is no corresponding "reference to" in T1 to remove.) This
608 // simulates removing a "pointer to" from both sides.
609 T2
= T2
->getPointeeType();
610 Kind
= CastAwayConstnessKind::CACK_Similar
;
611 } else if (Context
.UnwrapSimilarTypes(T1
, T2
)) {
612 Kind
= CastAwayConstnessKind::CACK_Similar
;
614 // Try unwrapping mismatching levels.
615 int T1Class
= Classify(T1
);
617 return CastAwayConstnessKind::CACK_None
;
619 int T2Class
= Classify(T2
);
621 return CastAwayConstnessKind::CACK_None
;
625 Kind
= T1Class
== T2Class
? CastAwayConstnessKind::CACK_SimilarKind
626 : CastAwayConstnessKind::CACK_Incoherent
;
629 // We've unwrapped at least one level. If the resulting T1 is a (possibly
630 // multidimensional) array type, any qualifier on any matching layer of
631 // T2 is considered to correspond to T1. Decompose down to the element
632 // type of T1 so that we can compare properly.
634 Context
.UnwrapSimilarArrayTypes(T1
, T2
);
636 if (Classify(T1
) != Array
)
639 auto T2Class
= Classify(T2
);
643 if (T2Class
!= Array
)
644 Kind
= CastAwayConstnessKind::CACK_Incoherent
;
645 else if (Kind
!= CastAwayConstnessKind::CACK_Incoherent
)
646 Kind
= CastAwayConstnessKind::CACK_SimilarKind
;
649 T2
= Unwrap(T2
).withCVRQualifiers(T2
.getCVRQualifiers());
655 /// Check if the pointer conversion from SrcType to DestType casts away
656 /// constness as defined in C++ [expr.const.cast]. This is used by the cast
657 /// checkers. Both arguments must denote pointer (possibly to member) types.
659 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
660 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
661 static CastAwayConstnessKind
662 CastsAwayConstness(Sema
&Self
, QualType SrcType
, QualType DestType
,
663 bool CheckCVR
, bool CheckObjCLifetime
,
664 QualType
*TheOffendingSrcType
= nullptr,
665 QualType
*TheOffendingDestType
= nullptr,
666 Qualifiers
*CastAwayQualifiers
= nullptr) {
667 // If the only checking we care about is for Objective-C lifetime qualifiers,
668 // and we're not in ObjC mode, there's nothing to check.
669 if (!CheckCVR
&& CheckObjCLifetime
&& !Self
.Context
.getLangOpts().ObjC
)
670 return CastAwayConstnessKind::CACK_None
;
672 if (!DestType
->isReferenceType()) {
673 assert((SrcType
->isAnyPointerType() || SrcType
->isMemberPointerType() ||
674 SrcType
->isBlockPointerType()) &&
675 "Source type is not pointer or pointer to member.");
676 assert((DestType
->isAnyPointerType() || DestType
->isMemberPointerType() ||
677 DestType
->isBlockPointerType()) &&
678 "Destination type is not pointer or pointer to member.");
681 QualType UnwrappedSrcType
= Self
.Context
.getCanonicalType(SrcType
),
682 UnwrappedDestType
= Self
.Context
.getCanonicalType(DestType
);
684 // Find the qualifiers. We only care about cvr-qualifiers for the
685 // purpose of this check, because other qualifiers (address spaces,
686 // Objective-C GC, etc.) are part of the type's identity.
687 QualType PrevUnwrappedSrcType
= UnwrappedSrcType
;
688 QualType PrevUnwrappedDestType
= UnwrappedDestType
;
689 auto WorstKind
= CastAwayConstnessKind::CACK_Similar
;
690 bool AllConstSoFar
= true;
691 while (auto Kind
= unwrapCastAwayConstnessLevel(
692 Self
.Context
, UnwrappedSrcType
, UnwrappedDestType
)) {
693 // Track the worst kind of unwrap we needed to do before we found a
695 if (Kind
> WorstKind
)
698 // Determine the relevant qualifiers at this level.
699 Qualifiers SrcQuals
, DestQuals
;
700 Self
.Context
.getUnqualifiedArrayType(UnwrappedSrcType
, SrcQuals
);
701 Self
.Context
.getUnqualifiedArrayType(UnwrappedDestType
, DestQuals
);
703 // We do not meaningfully track object const-ness of Objective-C object
704 // types. Remove const from the source type if either the source or
705 // the destination is an Objective-C object type.
706 if (UnwrappedSrcType
->isObjCObjectType() ||
707 UnwrappedDestType
->isObjCObjectType())
708 SrcQuals
.removeConst();
711 Qualifiers SrcCvrQuals
=
712 Qualifiers::fromCVRMask(SrcQuals
.getCVRQualifiers());
713 Qualifiers DestCvrQuals
=
714 Qualifiers::fromCVRMask(DestQuals
.getCVRQualifiers());
716 if (SrcCvrQuals
!= DestCvrQuals
) {
717 if (CastAwayQualifiers
)
718 *CastAwayQualifiers
= SrcCvrQuals
- DestCvrQuals
;
720 // If we removed a cvr-qualifier, this is casting away 'constness'.
721 if (!DestCvrQuals
.compatiblyIncludes(SrcCvrQuals
)) {
722 if (TheOffendingSrcType
)
723 *TheOffendingSrcType
= PrevUnwrappedSrcType
;
724 if (TheOffendingDestType
)
725 *TheOffendingDestType
= PrevUnwrappedDestType
;
729 // If any prior level was not 'const', this is also casting away
730 // 'constness'. We noted the outermost type missing a 'const' already.
736 if (CheckObjCLifetime
&&
737 !DestQuals
.compatiblyIncludesObjCLifetime(SrcQuals
))
740 // If we found our first non-const-qualified type, this may be the place
741 // where things start to go wrong.
742 if (AllConstSoFar
&& !DestQuals
.hasConst()) {
743 AllConstSoFar
= false;
744 if (TheOffendingSrcType
)
745 *TheOffendingSrcType
= PrevUnwrappedSrcType
;
746 if (TheOffendingDestType
)
747 *TheOffendingDestType
= PrevUnwrappedDestType
;
750 PrevUnwrappedSrcType
= UnwrappedSrcType
;
751 PrevUnwrappedDestType
= UnwrappedDestType
;
754 return CastAwayConstnessKind::CACK_None
;
757 static TryCastResult
getCastAwayConstnessCastKind(CastAwayConstnessKind CACK
,
760 case CastAwayConstnessKind::CACK_None
:
761 llvm_unreachable("did not cast away constness");
763 case CastAwayConstnessKind::CACK_Similar
:
764 // FIXME: Accept these as an extension too?
765 case CastAwayConstnessKind::CACK_SimilarKind
:
766 DiagID
= diag::err_bad_cxx_cast_qualifiers_away
;
769 case CastAwayConstnessKind::CACK_Incoherent
:
770 DiagID
= diag::ext_bad_cxx_cast_qualifiers_away_incoherent
;
774 llvm_unreachable("unexpected cast away constness kind");
777 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
778 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
779 /// checked downcasts in class hierarchies.
780 void CastOperation::CheckDynamicCast() {
781 CheckNoDerefRAII
NoderefCheck(*this);
783 if (ValueKind
== VK_PRValue
)
784 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
785 else if (isPlaceholder())
786 SrcExpr
= Self
.CheckPlaceholderExpr(SrcExpr
.get());
787 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
790 QualType OrigSrcType
= SrcExpr
.get()->getType();
791 QualType DestType
= Self
.Context
.getCanonicalType(this->DestType
);
793 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
794 // or "pointer to cv void".
796 QualType DestPointee
;
797 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
798 const ReferenceType
*DestReference
= nullptr;
800 DestPointee
= DestPointer
->getPointeeType();
801 } else if ((DestReference
= DestType
->getAs
<ReferenceType
>())) {
802 DestPointee
= DestReference
->getPointeeType();
804 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr
)
805 << this->DestType
<< DestRange
;
806 SrcExpr
= ExprError();
810 const RecordType
*DestRecord
= DestPointee
->getAs
<RecordType
>();
811 if (DestPointee
->isVoidType()) {
812 assert(DestPointer
&& "Reference to void is not possible");
813 } else if (DestRecord
) {
814 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestPointee
,
815 diag::err_bad_cast_incomplete
,
817 SrcExpr
= ExprError();
821 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
822 << DestPointee
.getUnqualifiedType() << DestRange
;
823 SrcExpr
= ExprError();
827 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
828 // complete class type, [...]. If T is an lvalue reference type, v shall be
829 // an lvalue of a complete class type, [...]. If T is an rvalue reference
830 // type, v shall be an expression having a complete class type, [...]
831 QualType SrcType
= Self
.Context
.getCanonicalType(OrigSrcType
);
834 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
835 SrcPointee
= SrcPointer
->getPointeeType();
837 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ptr
)
838 << OrigSrcType
<< this->DestType
<< SrcExpr
.get()->getSourceRange();
839 SrcExpr
= ExprError();
842 } else if (DestReference
->isLValueReferenceType()) {
843 if (!SrcExpr
.get()->isLValue()) {
844 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_rvalue
)
845 << CT_Dynamic
<< OrigSrcType
<< this->DestType
<< OpRange
;
847 SrcPointee
= SrcType
;
849 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
850 // to materialize the prvalue before we bind the reference to it.
851 if (SrcExpr
.get()->isPRValue())
852 SrcExpr
= Self
.CreateMaterializeTemporaryExpr(
853 SrcType
, SrcExpr
.get(), /*IsLValueReference*/ false);
854 SrcPointee
= SrcType
;
857 const RecordType
*SrcRecord
= SrcPointee
->getAs
<RecordType
>();
859 if (Self
.RequireCompleteType(OpRange
.getBegin(), SrcPointee
,
860 diag::err_bad_cast_incomplete
,
862 SrcExpr
= ExprError();
866 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
867 << SrcPointee
.getUnqualifiedType() << SrcExpr
.get()->getSourceRange();
868 SrcExpr
= ExprError();
872 assert((DestPointer
|| DestReference
) &&
873 "Bad destination non-ptr/ref slipped through.");
874 assert((DestRecord
|| DestPointee
->isVoidType()) &&
875 "Bad destination pointee slipped through.");
876 assert(SrcRecord
&& "Bad source pointee slipped through.");
878 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
879 if (!DestPointee
.isAtLeastAsQualifiedAs(SrcPointee
)) {
880 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_qualifiers_away
)
881 << CT_Dynamic
<< OrigSrcType
<< this->DestType
<< OpRange
;
882 SrcExpr
= ExprError();
886 // C++ 5.2.7p3: If the type of v is the same as the required result type,
888 if (DestRecord
== SrcRecord
) {
894 // Upcasts are resolved statically.
896 Self
.IsDerivedFrom(OpRange
.getBegin(), SrcPointee
, DestPointee
)) {
897 if (Self
.CheckDerivedToBaseConversion(SrcPointee
, DestPointee
,
898 OpRange
.getBegin(), OpRange
,
900 SrcExpr
= ExprError();
904 Kind
= CK_DerivedToBase
;
908 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
909 const RecordDecl
*SrcDecl
= SrcRecord
->getDecl()->getDefinition();
910 assert(SrcDecl
&& "Definition missing");
911 if (!cast
<CXXRecordDecl
>(SrcDecl
)->isPolymorphic()) {
912 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic
)
913 << SrcPointee
.getUnqualifiedType() << SrcExpr
.get()->getSourceRange();
914 SrcExpr
= ExprError();
917 // dynamic_cast is not available with -fno-rtti.
918 // As an exception, dynamic_cast to void* is available because it doesn't
920 if (!Self
.getLangOpts().RTTI
&& !DestPointee
->isVoidType()) {
921 Self
.Diag(OpRange
.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti
);
922 SrcExpr
= ExprError();
926 // Warns when dynamic_cast is used with RTTI data disabled.
927 if (!Self
.getLangOpts().RTTIData
) {
929 Self
.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
930 bool isClangCL
= Self
.getDiagnostics().getDiagnosticOptions().getFormat() ==
931 DiagnosticOptions::MSVC
;
932 if (MicrosoftABI
|| !DestPointee
->isVoidType())
933 Self
.Diag(OpRange
.getBegin(),
934 diag::warn_no_dynamic_cast_with_rtti_disabled
)
938 // For a dynamic_cast to a final type, IR generation might emit a reference
941 auto *DestDecl
= DestRecord
->getAsCXXRecordDecl();
942 if (DestDecl
->isEffectivelyFinal())
943 Self
.MarkVTableUsed(OpRange
.getBegin(), DestDecl
);
946 // Done. Everything else is run-time checks.
950 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
951 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
953 /// const char *str = "literal";
954 /// legacy_function(const_cast\<char*\>(str));
955 void CastOperation::CheckConstCast() {
956 CheckNoDerefRAII
NoderefCheck(*this);
958 if (ValueKind
== VK_PRValue
)
959 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
960 else if (isPlaceholder())
961 SrcExpr
= Self
.CheckPlaceholderExpr(SrcExpr
.get());
962 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
965 unsigned msg
= diag::err_bad_cxx_cast_generic
;
966 auto TCR
= TryConstCast(Self
, SrcExpr
, DestType
, /*CStyle*/ false, msg
);
967 if (TCR
!= TC_Success
&& msg
!= 0) {
968 Self
.Diag(OpRange
.getBegin(), msg
) << CT_Const
969 << SrcExpr
.get()->getType() << DestType
<< OpRange
;
971 if (!isValidCast(TCR
))
972 SrcExpr
= ExprError();
975 void CastOperation::CheckAddrspaceCast() {
976 unsigned msg
= diag::err_bad_cxx_cast_generic
;
978 TryAddressSpaceCast(Self
, SrcExpr
, DestType
, /*CStyle*/ false, msg
, Kind
);
979 if (TCR
!= TC_Success
&& msg
!= 0) {
980 Self
.Diag(OpRange
.getBegin(), msg
)
981 << CT_Addrspace
<< SrcExpr
.get()->getType() << DestType
<< OpRange
;
983 if (!isValidCast(TCR
))
984 SrcExpr
= ExprError();
987 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
988 /// or downcast between respective pointers or references.
989 static void DiagnoseReinterpretUpDownCast(Sema
&Self
, const Expr
*SrcExpr
,
991 SourceRange OpRange
) {
992 QualType SrcType
= SrcExpr
->getType();
993 // When casting from pointer or reference, get pointee type; use original
995 const CXXRecordDecl
*SrcPointeeRD
= SrcType
->getPointeeCXXRecordDecl();
996 const CXXRecordDecl
*SrcRD
=
997 SrcPointeeRD
? SrcPointeeRD
: SrcType
->getAsCXXRecordDecl();
999 // Examining subobjects for records is only possible if the complete and
1000 // valid definition is available. Also, template instantiation is not
1002 if (!SrcRD
|| !SrcRD
->isCompleteDefinition() || SrcRD
->isInvalidDecl())
1005 const CXXRecordDecl
*DestRD
= DestType
->getPointeeCXXRecordDecl();
1007 if (!DestRD
|| !DestRD
->isCompleteDefinition() || DestRD
->isInvalidDecl())
1015 CXXBasePaths BasePaths
;
1017 if (SrcRD
->isDerivedFrom(DestRD
, BasePaths
))
1018 ReinterpretKind
= ReinterpretUpcast
;
1019 else if (DestRD
->isDerivedFrom(SrcRD
, BasePaths
))
1020 ReinterpretKind
= ReinterpretDowncast
;
1024 bool VirtualBase
= true;
1025 bool NonZeroOffset
= false;
1026 for (CXXBasePaths::const_paths_iterator I
= BasePaths
.begin(),
1027 E
= BasePaths
.end();
1029 const CXXBasePath
&Path
= *I
;
1030 CharUnits Offset
= CharUnits::Zero();
1031 bool IsVirtual
= false;
1032 for (CXXBasePath::const_iterator IElem
= Path
.begin(), EElem
= Path
.end();
1033 IElem
!= EElem
; ++IElem
) {
1034 IsVirtual
= IElem
->Base
->isVirtual();
1037 const CXXRecordDecl
*BaseRD
= IElem
->Base
->getType()->getAsCXXRecordDecl();
1038 assert(BaseRD
&& "Base type should be a valid unqualified class type");
1039 // Don't check if any base has invalid declaration or has no definition
1040 // since it has no layout info.
1041 const CXXRecordDecl
*Class
= IElem
->Class
,
1042 *ClassDefinition
= Class
->getDefinition();
1043 if (Class
->isInvalidDecl() || !ClassDefinition
||
1044 !ClassDefinition
->isCompleteDefinition())
1047 const ASTRecordLayout
&DerivedLayout
=
1048 Self
.Context
.getASTRecordLayout(Class
);
1049 Offset
+= DerivedLayout
.getBaseClassOffset(BaseRD
);
1052 // Don't warn if any path is a non-virtually derived base at offset zero.
1053 if (Offset
.isZero())
1055 // Offset makes sense only for non-virtual bases.
1057 NonZeroOffset
= true;
1059 VirtualBase
= VirtualBase
&& IsVirtual
;
1062 (void) NonZeroOffset
; // Silence set but not used warning.
1063 assert((VirtualBase
|| NonZeroOffset
) &&
1064 "Should have returned if has non-virtual base with zero offset");
1067 ReinterpretKind
== ReinterpretUpcast
? DestType
: SrcType
;
1068 QualType DerivedType
=
1069 ReinterpretKind
== ReinterpretUpcast
? SrcType
: DestType
;
1071 SourceLocation BeginLoc
= OpRange
.getBegin();
1072 Self
.Diag(BeginLoc
, diag::warn_reinterpret_different_from_static
)
1073 << DerivedType
<< BaseType
<< !VirtualBase
<< int(ReinterpretKind
)
1075 Self
.Diag(BeginLoc
, diag::note_reinterpret_updowncast_use_static
)
1076 << int(ReinterpretKind
)
1077 << FixItHint::CreateReplacement(BeginLoc
, "static_cast");
1080 static bool argTypeIsABIEquivalent(QualType SrcType
, QualType DestType
,
1081 ASTContext
&Context
) {
1082 if (SrcType
->isPointerType() && DestType
->isPointerType())
1085 // Allow integral type mismatch if their size are equal.
1086 if (SrcType
->isIntegralType(Context
) && DestType
->isIntegralType(Context
))
1087 if (Context
.getTypeInfoInChars(SrcType
).Width
==
1088 Context
.getTypeInfoInChars(DestType
).Width
)
1091 return Context
.hasSameUnqualifiedType(SrcType
, DestType
);
1094 static unsigned int checkCastFunctionType(Sema
&Self
, const ExprResult
&SrcExpr
,
1095 QualType DestType
) {
1096 unsigned int DiagID
= 0;
1097 const unsigned int DiagList
[] = {diag::warn_cast_function_type_strict
,
1098 diag::warn_cast_function_type
};
1099 for (auto ID
: DiagList
) {
1100 if (!Self
.Diags
.isIgnored(ID
, SrcExpr
.get()->getExprLoc())) {
1108 QualType SrcType
= SrcExpr
.get()->getType();
1109 const FunctionType
*SrcFTy
= nullptr;
1110 const FunctionType
*DstFTy
= nullptr;
1111 if (((SrcType
->isBlockPointerType() || SrcType
->isFunctionPointerType()) &&
1112 DestType
->isFunctionPointerType()) ||
1113 (SrcType
->isMemberFunctionPointerType() &&
1114 DestType
->isMemberFunctionPointerType())) {
1115 SrcFTy
= SrcType
->getPointeeType()->castAs
<FunctionType
>();
1116 DstFTy
= DestType
->getPointeeType()->castAs
<FunctionType
>();
1117 } else if (SrcType
->isFunctionType() && DestType
->isFunctionReferenceType()) {
1118 SrcFTy
= SrcType
->castAs
<FunctionType
>();
1119 DstFTy
= DestType
.getNonReferenceType()->castAs
<FunctionType
>();
1123 assert(SrcFTy
&& DstFTy
);
1125 if (Self
.Context
.hasSameType(SrcFTy
, DstFTy
))
1128 // For strict checks, ensure we have an exact match.
1129 if (DiagID
== diag::warn_cast_function_type_strict
)
1132 auto IsVoidVoid
= [](const FunctionType
*T
) {
1133 if (!T
->getReturnType()->isVoidType())
1135 if (const auto *PT
= T
->getAs
<FunctionProtoType
>())
1136 return !PT
->isVariadic() && PT
->getNumParams() == 0;
1140 // Skip if either function type is void(*)(void)
1141 if (IsVoidVoid(SrcFTy
) || IsVoidVoid(DstFTy
))
1144 // Check return type.
1145 if (!argTypeIsABIEquivalent(SrcFTy
->getReturnType(), DstFTy
->getReturnType(),
1149 // Check if either has unspecified number of parameters
1150 if (SrcFTy
->isFunctionNoProtoType() || DstFTy
->isFunctionNoProtoType())
1153 // Check parameter types.
1155 const auto *SrcFPTy
= cast
<FunctionProtoType
>(SrcFTy
);
1156 const auto *DstFPTy
= cast
<FunctionProtoType
>(DstFTy
);
1158 // In a cast involving function types with a variable argument list only the
1159 // types of initial arguments that are provided are considered.
1160 unsigned NumParams
= SrcFPTy
->getNumParams();
1161 unsigned DstNumParams
= DstFPTy
->getNumParams();
1162 if (NumParams
> DstNumParams
) {
1163 if (!DstFPTy
->isVariadic())
1165 NumParams
= DstNumParams
;
1166 } else if (NumParams
< DstNumParams
) {
1167 if (!SrcFPTy
->isVariadic())
1171 for (unsigned i
= 0; i
< NumParams
; ++i
)
1172 if (!argTypeIsABIEquivalent(SrcFPTy
->getParamType(i
),
1173 DstFPTy
->getParamType(i
), Self
.Context
))
1179 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
1181 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
1183 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
1184 void CastOperation::CheckReinterpretCast() {
1185 if (ValueKind
== VK_PRValue
&& !isPlaceholder(BuiltinType::Overload
))
1186 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
1188 checkNonOverloadPlaceholders();
1189 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
1192 unsigned msg
= diag::err_bad_cxx_cast_generic
;
1194 TryReinterpretCast(Self
, SrcExpr
, DestType
,
1195 /*CStyle*/false, OpRange
, msg
, Kind
);
1196 if (tcr
!= TC_Success
&& msg
!= 0) {
1197 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
1199 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
1200 //FIXME: &f<int>; is overloaded and resolvable
1201 Self
.Diag(OpRange
.getBegin(), diag::err_bad_reinterpret_cast_overload
)
1202 << OverloadExpr::find(SrcExpr
.get()).Expression
->getName()
1203 << DestType
<< OpRange
;
1204 Self
.NoteAllOverloadCandidates(SrcExpr
.get());
1207 diagnoseBadCast(Self
, msg
, CT_Reinterpret
, OpRange
, SrcExpr
.get(),
1208 DestType
, /*listInitialization=*/false);
1212 if (isValidCast(tcr
)) {
1213 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1214 checkObjCConversion(Sema::CCK_OtherCast
);
1215 DiagnoseReinterpretUpDownCast(Self
, SrcExpr
.get(), DestType
, OpRange
);
1217 if (unsigned DiagID
= checkCastFunctionType(Self
, SrcExpr
, DestType
))
1218 Self
.Diag(OpRange
.getBegin(), DiagID
)
1219 << SrcExpr
.get()->getType() << DestType
<< OpRange
;
1221 SrcExpr
= ExprError();
1226 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1227 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1228 /// implicit conversions explicit and getting rid of data loss warnings.
1229 void CastOperation::CheckStaticCast() {
1230 CheckNoDerefRAII
NoderefCheck(*this);
1232 if (isPlaceholder()) {
1233 checkNonOverloadPlaceholders();
1234 if (SrcExpr
.isInvalid())
1238 // This test is outside everything else because it's the only case where
1239 // a non-lvalue-reference target type does not lead to decay.
1240 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1241 if (DestType
->isVoidType()) {
1244 if (claimPlaceholder(BuiltinType::Overload
)) {
1245 Self
.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr
,
1246 false, // Decay Function to ptr
1248 OpRange
, DestType
, diag::err_bad_static_cast_overload
);
1249 if (SrcExpr
.isInvalid())
1253 SrcExpr
= Self
.IgnoredValueConversions(SrcExpr
.get());
1257 if (ValueKind
== VK_PRValue
&& !DestType
->isRecordType() &&
1258 !isPlaceholder(BuiltinType::Overload
)) {
1259 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
1260 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
1264 unsigned msg
= diag::err_bad_cxx_cast_generic
;
1266 = TryStaticCast(Self
, SrcExpr
, DestType
, Sema::CCK_OtherCast
, OpRange
, msg
,
1267 Kind
, BasePath
, /*ListInitialization=*/false);
1268 if (tcr
!= TC_Success
&& msg
!= 0) {
1269 if (SrcExpr
.isInvalid())
1271 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
1272 OverloadExpr
* oe
= OverloadExpr::find(SrcExpr
.get()).Expression
;
1273 Self
.Diag(OpRange
.getBegin(), diag::err_bad_static_cast_overload
)
1274 << oe
->getName() << DestType
<< OpRange
1275 << oe
->getQualifierLoc().getSourceRange();
1276 Self
.NoteAllOverloadCandidates(SrcExpr
.get());
1278 diagnoseBadCast(Self
, msg
, CT_Static
, OpRange
, SrcExpr
.get(), DestType
,
1279 /*listInitialization=*/false);
1283 if (isValidCast(tcr
)) {
1284 if (Kind
== CK_BitCast
)
1286 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1287 checkObjCConversion(Sema::CCK_OtherCast
);
1289 SrcExpr
= ExprError();
1293 static bool IsAddressSpaceConversion(QualType SrcType
, QualType DestType
) {
1294 auto *SrcPtrType
= SrcType
->getAs
<PointerType
>();
1297 auto *DestPtrType
= DestType
->getAs
<PointerType
>();
1300 return SrcPtrType
->getPointeeType().getAddressSpace() !=
1301 DestPtrType
->getPointeeType().getAddressSpace();
1304 /// TryStaticCast - Check if a static cast can be performed, and do so if
1305 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1306 /// and casting away constness.
1307 static TryCastResult
TryStaticCast(Sema
&Self
, ExprResult
&SrcExpr
,
1309 Sema::CheckedConversionKind CCK
,
1310 SourceRange OpRange
, unsigned &msg
,
1311 CastKind
&Kind
, CXXCastPath
&BasePath
,
1312 bool ListInitialization
) {
1313 // Determine whether we have the semantics of a C-style cast.
1315 = (CCK
== Sema::CCK_CStyleCast
|| CCK
== Sema::CCK_FunctionalCast
);
1317 // The order the tests is not entirely arbitrary. There is one conversion
1318 // that can be handled in two different ways. Given:
1320 // struct B : public A {
1321 // B(); B(const A&);
1323 // const A &a = B();
1324 // the cast static_cast<const B&>(a) could be seen as either a static
1325 // reference downcast, or an explicit invocation of the user-defined
1326 // conversion using B's conversion constructor.
1327 // DR 427 specifies that the downcast is to be applied here.
1329 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1330 // Done outside this function.
1334 // C++ 5.2.9p5, reference downcast.
1335 // See the function for details.
1336 // DR 427 specifies that this is to be applied before paragraph 2.
1337 tcr
= TryStaticReferenceDowncast(Self
, SrcExpr
.get(), DestType
, CStyle
,
1338 OpRange
, msg
, Kind
, BasePath
);
1339 if (tcr
!= TC_NotApplicable
)
1342 // C++11 [expr.static.cast]p3:
1343 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1344 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1345 tcr
= TryLValueToRValueCast(Self
, SrcExpr
.get(), DestType
, CStyle
, Kind
,
1347 if (tcr
!= TC_NotApplicable
)
1350 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1351 // [...] if the declaration "T t(e);" is well-formed, [...].
1352 tcr
= TryStaticImplicitCast(Self
, SrcExpr
, DestType
, CCK
, OpRange
, msg
,
1353 Kind
, ListInitialization
);
1354 if (SrcExpr
.isInvalid())
1356 if (tcr
!= TC_NotApplicable
)
1359 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1360 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1361 // conversions, subject to further restrictions.
1362 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1363 // of qualification conversions impossible. (In C++20, adding an array bound
1364 // would be the reverse of a qualification conversion, but adding permission
1365 // to add an array bound in a static_cast is a wording oversight.)
1366 // In the CStyle case, the earlier attempt to const_cast should have taken
1367 // care of reverse qualification conversions.
1369 QualType SrcType
= Self
.Context
.getCanonicalType(SrcExpr
.get()->getType());
1371 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1372 // converted to an integral type. [...] A value of a scoped enumeration type
1373 // can also be explicitly converted to a floating-point type [...].
1374 if (const EnumType
*Enum
= SrcType
->getAs
<EnumType
>()) {
1375 if (Enum
->getDecl()->isScoped()) {
1376 if (DestType
->isBooleanType()) {
1377 Kind
= CK_IntegralToBoolean
;
1379 } else if (DestType
->isIntegralType(Self
.Context
)) {
1380 Kind
= CK_IntegralCast
;
1382 } else if (DestType
->isRealFloatingType()) {
1383 Kind
= CK_IntegralToFloating
;
1389 // Reverse integral promotion/conversion. All such conversions are themselves
1390 // again integral promotions or conversions and are thus already handled by
1391 // p2 (TryDirectInitialization above).
1392 // (Note: any data loss warnings should be suppressed.)
1393 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1394 // enum->enum). See also C++ 5.2.9p7.
1395 // The same goes for reverse floating point promotion/conversion and
1396 // floating-integral conversions. Again, only floating->enum is relevant.
1397 if (DestType
->isEnumeralType()) {
1398 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
1399 diag::err_bad_cast_incomplete
)) {
1400 SrcExpr
= ExprError();
1403 if (SrcType
->isIntegralOrEnumerationType()) {
1404 // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1405 // type, the value is first converted to that type by integral conversion
1406 const EnumType
*Enum
= DestType
->castAs
<EnumType
>();
1407 Kind
= Enum
->getDecl()->isFixed() &&
1408 Enum
->getDecl()->getIntegerType()->isBooleanType()
1409 ? CK_IntegralToBoolean
1412 } else if (SrcType
->isRealFloatingType()) {
1413 Kind
= CK_FloatingToIntegral
;
1418 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1419 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1420 tcr
= TryStaticPointerDowncast(Self
, SrcType
, DestType
, CStyle
, OpRange
, msg
,
1422 if (tcr
!= TC_NotApplicable
)
1425 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1426 // conversion. C++ 5.2.9p9 has additional information.
1427 // DR54's access restrictions apply here also.
1428 tcr
= TryStaticMemberPointerUpcast(Self
, SrcExpr
, SrcType
, DestType
, CStyle
,
1429 OpRange
, msg
, Kind
, BasePath
);
1430 if (tcr
!= TC_NotApplicable
)
1433 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1434 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1435 // just the usual constness stuff.
1436 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
1437 QualType SrcPointee
= SrcPointer
->getPointeeType();
1438 if (SrcPointee
->isVoidType()) {
1439 if (const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>()) {
1440 QualType DestPointee
= DestPointer
->getPointeeType();
1441 if (DestPointee
->isIncompleteOrObjectType()) {
1442 // This is definitely the intended conversion, but it might fail due
1443 // to a qualifier violation. Note that we permit Objective-C lifetime
1444 // and GC qualifier mismatches here.
1446 Qualifiers DestPointeeQuals
= DestPointee
.getQualifiers();
1447 Qualifiers SrcPointeeQuals
= SrcPointee
.getQualifiers();
1448 DestPointeeQuals
.removeObjCGCAttr();
1449 DestPointeeQuals
.removeObjCLifetime();
1450 SrcPointeeQuals
.removeObjCGCAttr();
1451 SrcPointeeQuals
.removeObjCLifetime();
1452 if (DestPointeeQuals
!= SrcPointeeQuals
&&
1453 !DestPointeeQuals
.compatiblyIncludes(SrcPointeeQuals
)) {
1454 msg
= diag::err_bad_cxx_cast_qualifiers_away
;
1458 Kind
= IsAddressSpaceConversion(SrcType
, DestType
)
1459 ? CK_AddressSpaceConversion
1464 // Microsoft permits static_cast from 'pointer-to-void' to
1465 // 'pointer-to-function'.
1466 if (!CStyle
&& Self
.getLangOpts().MSVCCompat
&&
1467 DestPointee
->isFunctionType()) {
1468 Self
.Diag(OpRange
.getBegin(), diag::ext_ms_cast_fn_obj
) << OpRange
;
1473 else if (DestType
->isObjCObjectPointerType()) {
1474 // allow both c-style cast and static_cast of objective-c pointers as
1475 // they are pervasive.
1476 Kind
= CK_CPointerToObjCPointerCast
;
1479 else if (CStyle
&& DestType
->isBlockPointerType()) {
1480 // allow c-style cast of void * to block pointers.
1481 Kind
= CK_AnyPointerToBlockPointerCast
;
1486 // Allow arbitrary objective-c pointer conversion with static casts.
1487 if (SrcType
->isObjCObjectPointerType() &&
1488 DestType
->isObjCObjectPointerType()) {
1492 // Allow ns-pointer to cf-pointer conversion in either direction
1493 // with static casts.
1495 Self
.CheckTollFreeBridgeStaticCast(DestType
, SrcExpr
.get(), Kind
))
1498 // See if it looks like the user is trying to convert between
1499 // related record types, and select a better diagnostic if so.
1500 if (auto SrcPointer
= SrcType
->getAs
<PointerType
>())
1501 if (auto DestPointer
= DestType
->getAs
<PointerType
>())
1502 if (SrcPointer
->getPointeeType()->getAs
<RecordType
>() &&
1503 DestPointer
->getPointeeType()->getAs
<RecordType
>())
1504 msg
= diag::err_bad_cxx_cast_unrelated_class
;
1506 if (SrcType
->isMatrixType() && DestType
->isMatrixType()) {
1507 if (Self
.CheckMatrixCast(OpRange
, DestType
, SrcType
, Kind
)) {
1508 SrcExpr
= ExprError();
1514 // We tried everything. Everything! Nothing works! :-(
1515 return TC_NotApplicable
;
1518 /// Tests whether a conversion according to N2844 is valid.
1519 TryCastResult
TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
,
1520 QualType DestType
, bool CStyle
,
1521 CastKind
&Kind
, CXXCastPath
&BasePath
,
1523 // C++11 [expr.static.cast]p3:
1524 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1525 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1526 const RValueReferenceType
*R
= DestType
->getAs
<RValueReferenceType
>();
1528 return TC_NotApplicable
;
1530 if (!SrcExpr
->isGLValue())
1531 return TC_NotApplicable
;
1533 // Because we try the reference downcast before this function, from now on
1534 // this is the only cast possibility, so we issue an error if we fail now.
1535 // FIXME: Should allow casting away constness if CStyle.
1536 QualType FromType
= SrcExpr
->getType();
1537 QualType ToType
= R
->getPointeeType();
1539 FromType
= FromType
.getUnqualifiedType();
1540 ToType
= ToType
.getUnqualifiedType();
1543 Sema::ReferenceConversions RefConv
;
1544 Sema::ReferenceCompareResult RefResult
= Self
.CompareReferenceRelationship(
1545 SrcExpr
->getBeginLoc(), ToType
, FromType
, &RefConv
);
1546 if (RefResult
!= Sema::Ref_Compatible
) {
1547 if (CStyle
|| RefResult
== Sema::Ref_Incompatible
)
1548 return TC_NotApplicable
;
1549 // Diagnose types which are reference-related but not compatible here since
1550 // we can provide better diagnostics. In these cases forwarding to
1551 // [expr.static.cast]p4 should never result in a well-formed cast.
1552 msg
= SrcExpr
->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1553 : diag::err_bad_rvalue_to_rvalue_cast
;
1557 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
) {
1558 Kind
= CK_DerivedToBase
;
1559 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1560 /*DetectVirtual=*/true);
1561 if (!Self
.IsDerivedFrom(SrcExpr
->getBeginLoc(), SrcExpr
->getType(),
1562 R
->getPointeeType(), Paths
))
1563 return TC_NotApplicable
;
1565 Self
.BuildBasePathArray(Paths
, BasePath
);
1572 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1574 TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
1575 bool CStyle
, SourceRange OpRange
,
1576 unsigned &msg
, CastKind
&Kind
,
1577 CXXCastPath
&BasePath
) {
1578 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1579 // cast to type "reference to cv2 D", where D is a class derived from B,
1580 // if a valid standard conversion from "pointer to D" to "pointer to B"
1581 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1582 // In addition, DR54 clarifies that the base must be accessible in the
1583 // current context. Although the wording of DR54 only applies to the pointer
1584 // variant of this rule, the intent is clearly for it to apply to the this
1585 // conversion as well.
1587 const ReferenceType
*DestReference
= DestType
->getAs
<ReferenceType
>();
1588 if (!DestReference
) {
1589 return TC_NotApplicable
;
1591 bool RValueRef
= DestReference
->isRValueReferenceType();
1592 if (!RValueRef
&& !SrcExpr
->isLValue()) {
1593 // We know the left side is an lvalue reference, so we can suggest a reason.
1594 msg
= diag::err_bad_cxx_cast_rvalue
;
1595 return TC_NotApplicable
;
1598 QualType DestPointee
= DestReference
->getPointeeType();
1600 // FIXME: If the source is a prvalue, we should issue a warning (because the
1601 // cast always has undefined behavior), and for AST consistency, we should
1602 // materialize a temporary.
1603 return TryStaticDowncast(Self
,
1604 Self
.Context
.getCanonicalType(SrcExpr
->getType()),
1605 Self
.Context
.getCanonicalType(DestPointee
), CStyle
,
1606 OpRange
, SrcExpr
->getType(), DestType
, msg
, Kind
,
1610 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1612 TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
, QualType DestType
,
1613 bool CStyle
, SourceRange OpRange
,
1614 unsigned &msg
, CastKind
&Kind
,
1615 CXXCastPath
&BasePath
) {
1616 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1617 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1618 // is a class derived from B, if a valid standard conversion from "pointer
1619 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1621 // In addition, DR54 clarifies that the base must be accessible in the
1624 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
1626 return TC_NotApplicable
;
1629 const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>();
1631 msg
= diag::err_bad_static_cast_pointer_nonpointer
;
1632 return TC_NotApplicable
;
1635 return TryStaticDowncast(Self
,
1636 Self
.Context
.getCanonicalType(SrcPointer
->getPointeeType()),
1637 Self
.Context
.getCanonicalType(DestPointer
->getPointeeType()),
1638 CStyle
, OpRange
, SrcType
, DestType
, msg
, Kind
,
1642 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1643 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1644 /// DestType is possible and allowed.
1646 TryStaticDowncast(Sema
&Self
, CanQualType SrcType
, CanQualType DestType
,
1647 bool CStyle
, SourceRange OpRange
, QualType OrigSrcType
,
1648 QualType OrigDestType
, unsigned &msg
,
1649 CastKind
&Kind
, CXXCastPath
&BasePath
) {
1650 // We can only work with complete types. But don't complain if it doesn't work
1651 if (!Self
.isCompleteType(OpRange
.getBegin(), SrcType
) ||
1652 !Self
.isCompleteType(OpRange
.getBegin(), DestType
))
1653 return TC_NotApplicable
;
1655 // Downcast can only happen in class hierarchies, so we need classes.
1656 if (!DestType
->getAs
<RecordType
>() || !SrcType
->getAs
<RecordType
>()) {
1657 return TC_NotApplicable
;
1660 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1661 /*DetectVirtual=*/true);
1662 if (!Self
.IsDerivedFrom(OpRange
.getBegin(), DestType
, SrcType
, Paths
)) {
1663 return TC_NotApplicable
;
1666 // Target type does derive from source type. Now we're serious. If an error
1667 // appears now, it's not ignored.
1668 // This may not be entirely in line with the standard. Take for example:
1670 // struct B : virtual A {
1676 // (void)static_cast<const B&>(*((A*)0));
1678 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1679 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1680 // However, both GCC and Comeau reject this example, and accepting it would
1681 // mean more complex code if we're to preserve the nice error message.
1682 // FIXME: Being 100% compliant here would be nice to have.
1684 // Must preserve cv, as always, unless we're in C-style mode.
1685 if (!CStyle
&& !DestType
.isAtLeastAsQualifiedAs(SrcType
)) {
1686 msg
= diag::err_bad_cxx_cast_qualifiers_away
;
1690 if (Paths
.isAmbiguous(SrcType
.getUnqualifiedType())) {
1691 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1692 // that it builds the paths in reverse order.
1693 // To sum up: record all paths to the base and build a nice string from
1694 // them. Use it to spice up the error message.
1695 if (!Paths
.isRecordingPaths()) {
1697 Paths
.setRecordingPaths(true);
1698 Self
.IsDerivedFrom(OpRange
.getBegin(), DestType
, SrcType
, Paths
);
1700 std::string PathDisplayStr
;
1701 std::set
<unsigned> DisplayedPaths
;
1702 for (clang::CXXBasePath
&Path
: Paths
) {
1703 if (DisplayedPaths
.insert(Path
.back().SubobjectNumber
).second
) {
1704 // We haven't displayed a path to this particular base
1705 // class subobject yet.
1706 PathDisplayStr
+= "\n ";
1707 for (CXXBasePathElement
&PE
: llvm::reverse(Path
))
1708 PathDisplayStr
+= PE
.Base
->getType().getAsString() + " -> ";
1709 PathDisplayStr
+= QualType(DestType
).getAsString();
1713 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_base_to_derived_cast
)
1714 << QualType(SrcType
).getUnqualifiedType()
1715 << QualType(DestType
).getUnqualifiedType()
1716 << PathDisplayStr
<< OpRange
;
1721 if (Paths
.getDetectedVirtual() != nullptr) {
1722 QualType
VirtualBase(Paths
.getDetectedVirtual(), 0);
1723 Self
.Diag(OpRange
.getBegin(), diag::err_static_downcast_via_virtual
)
1724 << OrigSrcType
<< OrigDestType
<< VirtualBase
<< OpRange
;
1730 switch (Self
.CheckBaseClassAccess(OpRange
.getBegin(),
1733 diag::err_downcast_from_inaccessible_base
)) {
1734 case Sema::AR_accessible
:
1735 case Sema::AR_delayed
: // be optimistic
1736 case Sema::AR_dependent
: // be optimistic
1739 case Sema::AR_inaccessible
:
1745 Self
.BuildBasePathArray(Paths
, BasePath
);
1746 Kind
= CK_BaseToDerived
;
1750 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1751 /// C++ 5.2.9p9 is valid:
1753 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1754 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1755 /// where B is a base class of D [...].
1758 TryStaticMemberPointerUpcast(Sema
&Self
, ExprResult
&SrcExpr
, QualType SrcType
,
1759 QualType DestType
, bool CStyle
,
1760 SourceRange OpRange
,
1761 unsigned &msg
, CastKind
&Kind
,
1762 CXXCastPath
&BasePath
) {
1763 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>();
1765 return TC_NotApplicable
;
1767 bool WasOverloadedFunction
= false;
1768 DeclAccessPair FoundOverload
;
1769 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
1770 if (FunctionDecl
*Fn
1771 = Self
.ResolveAddressOfOverloadedFunction(SrcExpr
.get(), DestType
, false,
1773 CXXMethodDecl
*M
= cast
<CXXMethodDecl
>(Fn
);
1774 SrcType
= Self
.Context
.getMemberPointerType(Fn
->getType(),
1775 Self
.Context
.getTypeDeclType(M
->getParent()).getTypePtr());
1776 WasOverloadedFunction
= true;
1780 const MemberPointerType
*SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
1782 msg
= diag::err_bad_static_cast_member_pointer_nonmp
;
1783 return TC_NotApplicable
;
1786 // Lock down the inheritance model right now in MS ABI, whether or not the
1787 // pointee types are the same.
1788 if (Self
.Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
1789 (void)Self
.isCompleteType(OpRange
.getBegin(), SrcType
);
1790 (void)Self
.isCompleteType(OpRange
.getBegin(), DestType
);
1793 // T == T, modulo cv
1794 if (!Self
.Context
.hasSameUnqualifiedType(SrcMemPtr
->getPointeeType(),
1795 DestMemPtr
->getPointeeType()))
1796 return TC_NotApplicable
;
1799 QualType
SrcClass(SrcMemPtr
->getClass(), 0);
1800 QualType
DestClass(DestMemPtr
->getClass(), 0);
1801 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1802 /*DetectVirtual=*/true);
1803 if (!Self
.IsDerivedFrom(OpRange
.getBegin(), SrcClass
, DestClass
, Paths
))
1804 return TC_NotApplicable
;
1806 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1807 if (Paths
.isAmbiguous(Self
.Context
.getCanonicalType(DestClass
))) {
1809 Paths
.setRecordingPaths(true);
1811 Self
.IsDerivedFrom(OpRange
.getBegin(), SrcClass
, DestClass
, Paths
);
1814 std::string PathDisplayStr
= Self
.getAmbiguousPathsDisplayString(Paths
);
1815 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_memptr_conv
)
1816 << 1 << SrcClass
<< DestClass
<< PathDisplayStr
<< OpRange
;
1821 if (const RecordType
*VBase
= Paths
.getDetectedVirtual()) {
1822 Self
.Diag(OpRange
.getBegin(), diag::err_memptr_conv_via_virtual
)
1823 << SrcClass
<< DestClass
<< QualType(VBase
, 0) << OpRange
;
1829 switch (Self
.CheckBaseClassAccess(OpRange
.getBegin(),
1830 DestClass
, SrcClass
,
1832 diag::err_upcast_to_inaccessible_base
)) {
1833 case Sema::AR_accessible
:
1834 case Sema::AR_delayed
:
1835 case Sema::AR_dependent
:
1836 // Optimistically assume that the delayed and dependent cases
1840 case Sema::AR_inaccessible
:
1846 if (WasOverloadedFunction
) {
1847 // Resolve the address of the overloaded function again, this time
1848 // allowing complaints if something goes wrong.
1849 FunctionDecl
*Fn
= Self
.ResolveAddressOfOverloadedFunction(SrcExpr
.get(),
1858 SrcExpr
= Self
.FixOverloadedFunctionReference(SrcExpr
, FoundOverload
, Fn
);
1859 if (!SrcExpr
.isUsable()) {
1865 Self
.BuildBasePathArray(Paths
, BasePath
);
1866 Kind
= CK_DerivedToBaseMemberPointer
;
1870 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1873 /// An expression e can be explicitly converted to a type T using a
1874 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1876 TryStaticImplicitCast(Sema
&Self
, ExprResult
&SrcExpr
, QualType DestType
,
1877 Sema::CheckedConversionKind CCK
,
1878 SourceRange OpRange
, unsigned &msg
,
1879 CastKind
&Kind
, bool ListInitialization
) {
1880 if (DestType
->isRecordType()) {
1881 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
1882 diag::err_bad_cast_incomplete
) ||
1883 Self
.RequireNonAbstractType(OpRange
.getBegin(), DestType
,
1884 diag::err_allocation_of_abstract_type
)) {
1890 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(DestType
);
1891 InitializationKind InitKind
1892 = (CCK
== Sema::CCK_CStyleCast
)
1893 ? InitializationKind::CreateCStyleCast(OpRange
.getBegin(), OpRange
,
1895 : (CCK
== Sema::CCK_FunctionalCast
)
1896 ? InitializationKind::CreateFunctionalCast(OpRange
, ListInitialization
)
1897 : InitializationKind::CreateCast(OpRange
);
1898 Expr
*SrcExprRaw
= SrcExpr
.get();
1899 // FIXME: Per DR242, we should check for an implicit conversion sequence
1900 // or for a constructor that could be invoked by direct-initialization
1901 // here, not for an initialization sequence.
1902 InitializationSequence
InitSeq(Self
, Entity
, InitKind
, SrcExprRaw
);
1904 // At this point of CheckStaticCast, if the destination is a reference,
1905 // or the expression is an overload expression this has to work.
1906 // There is no other way that works.
1907 // On the other hand, if we're checking a C-style cast, we've still got
1908 // the reinterpret_cast way.
1910 = (CCK
== Sema::CCK_CStyleCast
|| CCK
== Sema::CCK_FunctionalCast
);
1911 if (InitSeq
.Failed() && (CStyle
|| !DestType
->isReferenceType()))
1912 return TC_NotApplicable
;
1914 ExprResult Result
= InitSeq
.Perform(Self
, Entity
, InitKind
, SrcExprRaw
);
1915 if (Result
.isInvalid()) {
1920 if (InitSeq
.isConstructorInitialization())
1921 Kind
= CK_ConstructorConversion
;
1929 /// TryConstCast - See if a const_cast from source to destination is allowed,
1930 /// and perform it if it is.
1931 static TryCastResult
TryConstCast(Sema
&Self
, ExprResult
&SrcExpr
,
1932 QualType DestType
, bool CStyle
,
1934 DestType
= Self
.Context
.getCanonicalType(DestType
);
1935 QualType SrcType
= SrcExpr
.get()->getType();
1936 bool NeedToMaterializeTemporary
= false;
1938 if (const ReferenceType
*DestTypeTmp
=DestType
->getAs
<ReferenceType
>()) {
1940 // if a pointer to T1 can be explicitly converted to the type "pointer to
1941 // T2" using a const_cast, then the following conversions can also be
1943 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1944 // type T2 using the cast const_cast<T2&>;
1945 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1946 // type T2 using the cast const_cast<T2&&>; and
1947 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1948 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1950 if (isa
<LValueReferenceType
>(DestTypeTmp
) && !SrcExpr
.get()->isLValue()) {
1951 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1952 // is C-style, static_cast might find a way, so we simply suggest a
1953 // message and tell the parent to keep searching.
1954 msg
= diag::err_bad_cxx_cast_rvalue
;
1955 return TC_NotApplicable
;
1958 if (isa
<RValueReferenceType
>(DestTypeTmp
) && SrcExpr
.get()->isPRValue()) {
1959 if (!SrcType
->isRecordType()) {
1960 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1961 // this is C-style, static_cast can do this.
1962 msg
= diag::err_bad_cxx_cast_rvalue
;
1963 return TC_NotApplicable
;
1966 // Materialize the class prvalue so that the const_cast can bind a
1968 NeedToMaterializeTemporary
= true;
1971 // It's not completely clear under the standard whether we can
1972 // const_cast bit-field gl-values. Doing so would not be
1973 // intrinsically complicated, but for now, we say no for
1974 // consistency with other compilers and await the word of the
1976 if (SrcExpr
.get()->refersToBitField()) {
1977 msg
= diag::err_bad_cxx_cast_bitfield
;
1978 return TC_NotApplicable
;
1981 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
1982 SrcType
= Self
.Context
.getPointerType(SrcType
);
1985 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1986 // the rules for const_cast are the same as those used for pointers.
1988 if (!DestType
->isPointerType() &&
1989 !DestType
->isMemberPointerType() &&
1990 !DestType
->isObjCObjectPointerType()) {
1991 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1992 // was a reference type, we converted it to a pointer above.
1993 // The status of rvalue references isn't entirely clear, but it looks like
1994 // conversion to them is simply invalid.
1995 // C++ 5.2.11p3: For two pointer types [...]
1997 msg
= diag::err_bad_const_cast_dest
;
1998 return TC_NotApplicable
;
2000 if (DestType
->isFunctionPointerType() ||
2001 DestType
->isMemberFunctionPointerType()) {
2002 // Cannot cast direct function pointers.
2003 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
2004 // T is the ultimate pointee of source and target type.
2006 msg
= diag::err_bad_const_cast_dest
;
2007 return TC_NotApplicable
;
2010 // C++ [expr.const.cast]p3:
2011 // "For two similar types T1 and T2, [...]"
2013 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
2014 // type qualifiers. (Likewise, we ignore other changes when determining
2015 // whether a cast casts away constness.)
2016 if (!Self
.Context
.hasCvrSimilarType(SrcType
, DestType
))
2017 return TC_NotApplicable
;
2019 if (NeedToMaterializeTemporary
)
2020 // This is a const_cast from a class prvalue to an rvalue reference type.
2021 // Materialize a temporary to store the result of the conversion.
2022 SrcExpr
= Self
.CreateMaterializeTemporaryExpr(SrcExpr
.get()->getType(),
2024 /*IsLValueReference*/ false);
2029 // Checks for undefined behavior in reinterpret_cast.
2030 // The cases that is checked for is:
2031 // *reinterpret_cast<T*>(&a)
2032 // reinterpret_cast<T&>(a)
2033 // where accessing 'a' as type 'T' will result in undefined behavior.
2034 void Sema::CheckCompatibleReinterpretCast(QualType SrcType
, QualType DestType
,
2036 SourceRange Range
) {
2037 unsigned DiagID
= IsDereference
?
2038 diag::warn_pointer_indirection_from_incompatible_type
:
2039 diag::warn_undefined_reinterpret_cast
;
2041 if (Diags
.isIgnored(DiagID
, Range
.getBegin()))
2044 QualType SrcTy
, DestTy
;
2045 if (IsDereference
) {
2046 if (!SrcType
->getAs
<PointerType
>() || !DestType
->getAs
<PointerType
>()) {
2049 SrcTy
= SrcType
->getPointeeType();
2050 DestTy
= DestType
->getPointeeType();
2052 if (!DestType
->getAs
<ReferenceType
>()) {
2056 DestTy
= DestType
->getPointeeType();
2059 // Cast is compatible if the types are the same.
2060 if (Context
.hasSameUnqualifiedType(DestTy
, SrcTy
)) {
2063 // or one of the types is a char or void type
2064 if (DestTy
->isAnyCharacterType() || DestTy
->isVoidType() ||
2065 SrcTy
->isAnyCharacterType() || SrcTy
->isVoidType()) {
2068 // or one of the types is a tag type.
2069 if (SrcTy
->getAs
<TagType
>() || DestTy
->getAs
<TagType
>()) {
2073 // FIXME: Scoped enums?
2074 if ((SrcTy
->isUnsignedIntegerType() && DestTy
->isSignedIntegerType()) ||
2075 (SrcTy
->isSignedIntegerType() && DestTy
->isUnsignedIntegerType())) {
2076 if (Context
.getTypeSize(DestTy
) == Context
.getTypeSize(SrcTy
)) {
2081 Diag(Range
.getBegin(), DiagID
) << SrcType
<< DestType
<< Range
;
2084 static void DiagnoseCastOfObjCSEL(Sema
&Self
, const ExprResult
&SrcExpr
,
2085 QualType DestType
) {
2086 QualType SrcType
= SrcExpr
.get()->getType();
2087 if (Self
.Context
.hasSameType(SrcType
, DestType
))
2089 if (const PointerType
*SrcPtrTy
= SrcType
->getAs
<PointerType
>())
2090 if (SrcPtrTy
->isObjCSelType()) {
2091 QualType DT
= DestType
;
2092 if (isa
<PointerType
>(DestType
))
2093 DT
= DestType
->getPointeeType();
2094 if (!DT
.getUnqualifiedType()->isVoidType())
2095 Self
.Diag(SrcExpr
.get()->getExprLoc(),
2096 diag::warn_cast_pointer_from_sel
)
2097 << SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
2101 /// Diagnose casts that change the calling convention of a pointer to a function
2102 /// defined in the current TU.
2103 static void DiagnoseCallingConvCast(Sema
&Self
, const ExprResult
&SrcExpr
,
2104 QualType DstType
, SourceRange OpRange
) {
2105 // Check if this cast would change the calling convention of a function
2107 QualType SrcType
= SrcExpr
.get()->getType();
2108 if (Self
.Context
.hasSameType(SrcType
, DstType
) ||
2109 !SrcType
->isFunctionPointerType() || !DstType
->isFunctionPointerType())
2111 const auto *SrcFTy
=
2112 SrcType
->castAs
<PointerType
>()->getPointeeType()->castAs
<FunctionType
>();
2113 const auto *DstFTy
=
2114 DstType
->castAs
<PointerType
>()->getPointeeType()->castAs
<FunctionType
>();
2115 CallingConv SrcCC
= SrcFTy
->getCallConv();
2116 CallingConv DstCC
= DstFTy
->getCallConv();
2120 // We have a calling convention cast. Check if the source is a pointer to a
2121 // known, specific function that has already been defined.
2122 Expr
*Src
= SrcExpr
.get()->IgnoreParenImpCasts();
2123 if (auto *UO
= dyn_cast
<UnaryOperator
>(Src
))
2124 if (UO
->getOpcode() == UO_AddrOf
)
2125 Src
= UO
->getSubExpr()->IgnoreParenImpCasts();
2126 auto *DRE
= dyn_cast
<DeclRefExpr
>(Src
);
2129 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
2133 // Only warn if we are casting from the default convention to a non-default
2134 // convention. This can happen when the programmer forgot to apply the calling
2135 // convention to the function declaration and then inserted this cast to
2136 // satisfy the type system.
2137 CallingConv DefaultCC
= Self
.getASTContext().getDefaultCallingConvention(
2138 FD
->isVariadic(), FD
->isCXXInstanceMember());
2139 if (DstCC
== DefaultCC
|| SrcCC
!= DefaultCC
)
2142 // Diagnose this cast, as it is probably bad.
2143 StringRef SrcCCName
= FunctionType::getNameForCallConv(SrcCC
);
2144 StringRef DstCCName
= FunctionType::getNameForCallConv(DstCC
);
2145 Self
.Diag(OpRange
.getBegin(), diag::warn_cast_calling_conv
)
2146 << SrcCCName
<< DstCCName
<< OpRange
;
2148 // The checks above are cheaper than checking if the diagnostic is enabled.
2149 // However, it's worth checking if the warning is enabled before we construct
2151 if (Self
.Diags
.isIgnored(diag::warn_cast_calling_conv
, OpRange
.getBegin()))
2154 // Try to suggest a fixit to change the calling convention of the function
2155 // whose address was taken. Try to use the latest macro for the convention.
2156 // For example, users probably want to write "WINAPI" instead of "__stdcall"
2157 // to match the Windows header declarations.
2158 SourceLocation NameLoc
= FD
->getFirstDecl()->getNameInfo().getLoc();
2159 Preprocessor
&PP
= Self
.getPreprocessor();
2160 SmallVector
<TokenValue
, 6> AttrTokens
;
2161 SmallString
<64> CCAttrText
;
2162 llvm::raw_svector_ostream
OS(CCAttrText
);
2163 if (Self
.getLangOpts().MicrosoftExt
) {
2164 // __stdcall or __vectorcall
2165 OS
<< "__" << DstCCName
;
2166 IdentifierInfo
*II
= PP
.getIdentifierInfo(OS
.str());
2167 AttrTokens
.push_back(II
->isKeyword(Self
.getLangOpts())
2168 ? TokenValue(II
->getTokenID())
2171 // __attribute__((stdcall)) or __attribute__((vectorcall))
2172 OS
<< "__attribute__((" << DstCCName
<< "))";
2173 AttrTokens
.push_back(tok::kw___attribute
);
2174 AttrTokens
.push_back(tok::l_paren
);
2175 AttrTokens
.push_back(tok::l_paren
);
2176 IdentifierInfo
*II
= PP
.getIdentifierInfo(DstCCName
);
2177 AttrTokens
.push_back(II
->isKeyword(Self
.getLangOpts())
2178 ? TokenValue(II
->getTokenID())
2180 AttrTokens
.push_back(tok::r_paren
);
2181 AttrTokens
.push_back(tok::r_paren
);
2183 StringRef AttrSpelling
= PP
.getLastMacroWithSpelling(NameLoc
, AttrTokens
);
2184 if (!AttrSpelling
.empty())
2185 CCAttrText
= AttrSpelling
;
2187 Self
.Diag(NameLoc
, diag::note_change_calling_conv_fixit
)
2188 << FD
<< DstCCName
<< FixItHint::CreateInsertion(NameLoc
, CCAttrText
);
2191 static void checkIntToPointerCast(bool CStyle
, const SourceRange
&OpRange
,
2192 const Expr
*SrcExpr
, QualType DestType
,
2194 QualType SrcType
= SrcExpr
->getType();
2196 // Not warning on reinterpret_cast, boolean, constant expressions, etc
2197 // are not explicit design choices, but consistent with GCC's behavior.
2198 // Feel free to modify them if you've reason/evidence for an alternative.
2199 if (CStyle
&& SrcType
->isIntegralType(Self
.Context
)
2200 && !SrcType
->isBooleanType()
2201 && !SrcType
->isEnumeralType()
2202 && !SrcExpr
->isIntegerConstantExpr(Self
.Context
)
2203 && Self
.Context
.getTypeSize(DestType
) >
2204 Self
.Context
.getTypeSize(SrcType
)) {
2205 // Separate between casts to void* and non-void* pointers.
2206 // Some APIs use (abuse) void* for something like a user context,
2207 // and often that value is an integer even if it isn't a pointer itself.
2208 // Having a separate warning flag allows users to control the warning
2209 // for their workflow.
2210 unsigned Diag
= DestType
->isVoidPointerType() ?
2211 diag::warn_int_to_void_pointer_cast
2212 : diag::warn_int_to_pointer_cast
;
2213 Self
.Diag(OpRange
.getBegin(), Diag
) << SrcType
<< DestType
<< OpRange
;
2217 static bool fixOverloadedReinterpretCastExpr(Sema
&Self
, QualType DestType
,
2218 ExprResult
&Result
) {
2219 // We can only fix an overloaded reinterpret_cast if
2220 // - it is a template with explicit arguments that resolves to an lvalue
2221 // unambiguously, or
2222 // - it is the only function in an overload set that may have its address
2225 Expr
*E
= Result
.get();
2226 // TODO: what if this fails because of DiagnoseUseOfDecl or something
2228 if (Self
.ResolveAndFixSingleFunctionTemplateSpecialization(
2230 Expr::getValueKindForType(DestType
) ==
2231 VK_PRValue
// Convert Fun to Ptr
2236 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2237 // preserves Result.
2239 if (!Self
.resolveAndFixAddressOfSingleOverloadCandidate(
2240 Result
, /*DoFunctionPointerConversion=*/true))
2242 return Result
.isUsable();
2245 static TryCastResult
TryReinterpretCast(Sema
&Self
, ExprResult
&SrcExpr
,
2246 QualType DestType
, bool CStyle
,
2247 SourceRange OpRange
,
2250 bool IsLValueCast
= false;
2252 DestType
= Self
.Context
.getCanonicalType(DestType
);
2253 QualType SrcType
= SrcExpr
.get()->getType();
2255 // Is the source an overloaded name? (i.e. &foo)
2256 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2257 if (SrcType
== Self
.Context
.OverloadTy
) {
2258 ExprResult FixedExpr
= SrcExpr
;
2259 if (!fixOverloadedReinterpretCastExpr(Self
, DestType
, FixedExpr
))
2260 return TC_NotApplicable
;
2262 assert(FixedExpr
.isUsable() && "Invalid result fixing overloaded expr");
2263 SrcExpr
= FixedExpr
;
2264 SrcType
= SrcExpr
.get()->getType();
2267 if (const ReferenceType
*DestTypeTmp
= DestType
->getAs
<ReferenceType
>()) {
2268 if (!SrcExpr
.get()->isGLValue()) {
2269 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2270 // similar comment in const_cast.
2271 msg
= diag::err_bad_cxx_cast_rvalue
;
2272 return TC_NotApplicable
;
2276 Self
.CheckCompatibleReinterpretCast(SrcType
, DestType
,
2277 /*IsDereference=*/false, OpRange
);
2280 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2281 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2282 // built-in & and * operators.
2284 const char *inappropriate
= nullptr;
2285 switch (SrcExpr
.get()->getObjectKind()) {
2289 msg
= diag::err_bad_cxx_cast_bitfield
;
2290 return TC_NotApplicable
;
2291 // FIXME: Use a specific diagnostic for the rest of these cases.
2292 case OK_VectorComponent
: inappropriate
= "vector element"; break;
2293 case OK_MatrixComponent
:
2294 inappropriate
= "matrix element";
2296 case OK_ObjCProperty
: inappropriate
= "property expression"; break;
2297 case OK_ObjCSubscript
: inappropriate
= "container subscripting expression";
2300 if (inappropriate
) {
2301 Self
.Diag(OpRange
.getBegin(), diag::err_bad_reinterpret_cast_reference
)
2302 << inappropriate
<< DestType
2303 << OpRange
<< SrcExpr
.get()->getSourceRange();
2304 msg
= 0; SrcExpr
= ExprError();
2305 return TC_NotApplicable
;
2308 // This code does this transformation for the checked types.
2309 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
2310 SrcType
= Self
.Context
.getPointerType(SrcType
);
2312 IsLValueCast
= true;
2315 // Canonicalize source for comparison.
2316 SrcType
= Self
.Context
.getCanonicalType(SrcType
);
2318 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>(),
2319 *SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
2320 if (DestMemPtr
&& SrcMemPtr
) {
2321 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2322 // can be explicitly converted to an rvalue of type "pointer to member
2323 // of Y of type T2" if T1 and T2 are both function types or both object
2325 if (DestMemPtr
->isMemberFunctionPointer() !=
2326 SrcMemPtr
->isMemberFunctionPointer())
2327 return TC_NotApplicable
;
2329 if (Self
.Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
2330 // We need to determine the inheritance model that the class will use if
2332 (void)Self
.isCompleteType(OpRange
.getBegin(), SrcType
);
2333 (void)Self
.isCompleteType(OpRange
.getBegin(), DestType
);
2336 // Don't allow casting between member pointers of different sizes.
2337 if (Self
.Context
.getTypeSize(DestMemPtr
) !=
2338 Self
.Context
.getTypeSize(SrcMemPtr
)) {
2339 msg
= diag::err_bad_cxx_cast_member_pointer_size
;
2343 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2345 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2348 CastsAwayConstness(Self
, SrcType
, DestType
, /*CheckCVR=*/!CStyle
,
2349 /*CheckObjCLifetime=*/CStyle
))
2350 return getCastAwayConstnessCastKind(CACK
, msg
);
2352 // A valid member pointer cast.
2353 assert(!IsLValueCast
);
2354 Kind
= CK_ReinterpretMemberPointer
;
2358 // See below for the enumeral issue.
2359 if (SrcType
->isNullPtrType() && DestType
->isIntegralType(Self
.Context
)) {
2360 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2361 // type large enough to hold it. A value of std::nullptr_t can be
2362 // converted to an integral type; the conversion has the same meaning
2363 // and validity as a conversion of (void*)0 to the integral type.
2364 if (Self
.Context
.getTypeSize(SrcType
) >
2365 Self
.Context
.getTypeSize(DestType
)) {
2366 msg
= diag::err_bad_reinterpret_cast_small_int
;
2369 Kind
= CK_PointerToIntegral
;
2373 // Allow reinterpret_casts between vectors of the same size and
2374 // between vectors and integers of the same size.
2375 bool destIsVector
= DestType
->isVectorType();
2376 bool srcIsVector
= SrcType
->isVectorType();
2377 if (srcIsVector
|| destIsVector
) {
2378 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2379 if (Self
.isValidSveBitcast(SrcType
, DestType
)) {
2384 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2385 if (Self
.isValidRVVBitcast(SrcType
, DestType
)) {
2390 // The non-vector type, if any, must have integral type. This is
2391 // the same rule that C vector casts use; note, however, that enum
2392 // types are not integral in C++.
2393 if ((!destIsVector
&& !DestType
->isIntegralType(Self
.Context
)) ||
2394 (!srcIsVector
&& !SrcType
->isIntegralType(Self
.Context
)))
2395 return TC_NotApplicable
;
2397 // The size we want to consider is eltCount * eltSize.
2398 // That's exactly what the lax-conversion rules will check.
2399 if (Self
.areLaxCompatibleVectorTypes(SrcType
, DestType
)) {
2404 if (Self
.LangOpts
.OpenCL
&& !CStyle
) {
2405 if (DestType
->isExtVectorType() || SrcType
->isExtVectorType()) {
2406 // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
2407 if (Self
.areVectorTypesSameSize(SrcType
, DestType
)) {
2414 // Otherwise, pick a reasonable diagnostic.
2416 msg
= diag::err_bad_cxx_cast_vector_to_scalar_different_size
;
2417 else if (!srcIsVector
)
2418 msg
= diag::err_bad_cxx_cast_scalar_to_vector_different_size
;
2420 msg
= diag::err_bad_cxx_cast_vector_to_vector_different_size
;
2425 if (SrcType
== DestType
) {
2426 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2427 // restrictions, a cast to the same type is allowed so long as it does not
2428 // cast away constness. In C++98, the intent was not entirely clear here,
2429 // since all other paragraphs explicitly forbid casts to the same type.
2430 // C++11 clarifies this case with p2.
2432 // The only allowed types are: integral, enumeration, pointer, or
2433 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2435 TryCastResult Result
= TC_NotApplicable
;
2436 if (SrcType
->isIntegralOrEnumerationType() ||
2437 SrcType
->isAnyPointerType() ||
2438 SrcType
->isMemberPointerType() ||
2439 SrcType
->isBlockPointerType()) {
2440 Result
= TC_Success
;
2445 bool destIsPtr
= DestType
->isAnyPointerType() ||
2446 DestType
->isBlockPointerType();
2447 bool srcIsPtr
= SrcType
->isAnyPointerType() ||
2448 SrcType
->isBlockPointerType();
2449 if (!destIsPtr
&& !srcIsPtr
) {
2450 // Except for std::nullptr_t->integer and lvalue->reference, which are
2451 // handled above, at least one of the two arguments must be a pointer.
2452 return TC_NotApplicable
;
2455 if (DestType
->isIntegralType(Self
.Context
)) {
2456 assert(srcIsPtr
&& "One type must be a pointer");
2457 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2458 // type large enough to hold it; except in Microsoft mode, where the
2459 // integral type size doesn't matter (except we don't allow bool).
2460 if ((Self
.Context
.getTypeSize(SrcType
) >
2461 Self
.Context
.getTypeSize(DestType
))) {
2462 bool MicrosoftException
=
2463 Self
.getLangOpts().MicrosoftExt
&& !DestType
->isBooleanType();
2464 if (MicrosoftException
) {
2465 unsigned Diag
= SrcType
->isVoidPointerType()
2466 ? diag::warn_void_pointer_to_int_cast
2467 : diag::warn_pointer_to_int_cast
;
2468 Self
.Diag(OpRange
.getBegin(), Diag
) << SrcType
<< DestType
<< OpRange
;
2470 msg
= diag::err_bad_reinterpret_cast_small_int
;
2474 Kind
= CK_PointerToIntegral
;
2478 if (SrcType
->isIntegralOrEnumerationType()) {
2479 assert(destIsPtr
&& "One type must be a pointer");
2480 checkIntToPointerCast(CStyle
, OpRange
, SrcExpr
.get(), DestType
, Self
);
2481 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2482 // converted to a pointer.
2483 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2484 // necessarily converted to a null pointer value.]
2485 Kind
= CK_IntegralToPointer
;
2489 if (!destIsPtr
|| !srcIsPtr
) {
2490 // With the valid non-pointer conversions out of the way, we can be even
2492 return TC_NotApplicable
;
2495 // Cannot convert between block pointers and Objective-C object pointers.
2496 if ((SrcType
->isBlockPointerType() && DestType
->isObjCObjectPointerType()) ||
2497 (DestType
->isBlockPointerType() && SrcType
->isObjCObjectPointerType()))
2498 return TC_NotApplicable
;
2500 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2501 // The C-style cast operator can.
2502 TryCastResult SuccessResult
= TC_Success
;
2504 CastsAwayConstness(Self
, SrcType
, DestType
, /*CheckCVR=*/!CStyle
,
2505 /*CheckObjCLifetime=*/CStyle
))
2506 SuccessResult
= getCastAwayConstnessCastKind(CACK
, msg
);
2508 if (IsAddressSpaceConversion(SrcType
, DestType
)) {
2509 Kind
= CK_AddressSpaceConversion
;
2510 assert(SrcType
->isPointerType() && DestType
->isPointerType());
2512 !DestType
->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2513 SrcType
->getPointeeType().getQualifiers())) {
2514 SuccessResult
= TC_Failed
;
2516 } else if (IsLValueCast
) {
2517 Kind
= CK_LValueBitCast
;
2518 } else if (DestType
->isObjCObjectPointerType()) {
2519 Kind
= Self
.PrepareCastToObjCObjectPointer(SrcExpr
);
2520 } else if (DestType
->isBlockPointerType()) {
2521 if (!SrcType
->isBlockPointerType()) {
2522 Kind
= CK_AnyPointerToBlockPointerCast
;
2530 // Any pointer can be cast to an Objective-C pointer type with a C-style
2532 if (CStyle
&& DestType
->isObjCObjectPointerType()) {
2533 return SuccessResult
;
2536 DiagnoseCastOfObjCSEL(Self
, SrcExpr
, DestType
);
2538 DiagnoseCallingConvCast(Self
, SrcExpr
, DestType
, OpRange
);
2540 // Not casting away constness, so the only remaining check is for compatible
2541 // pointer categories.
2543 if (SrcType
->isFunctionPointerType()) {
2544 if (DestType
->isFunctionPointerType()) {
2545 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2546 // a pointer to a function of a different type.
2547 return SuccessResult
;
2550 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2551 // an object type or vice versa is conditionally-supported.
2552 // Compilers support it in C++03 too, though, because it's necessary for
2553 // casting the return value of dlsym() and GetProcAddress().
2554 // FIXME: Conditionally-supported behavior should be configurable in the
2555 // TargetInfo or similar.
2556 Self
.Diag(OpRange
.getBegin(),
2557 Self
.getLangOpts().CPlusPlus11
?
2558 diag::warn_cxx98_compat_cast_fn_obj
: diag::ext_cast_fn_obj
)
2560 return SuccessResult
;
2563 if (DestType
->isFunctionPointerType()) {
2565 Self
.Diag(OpRange
.getBegin(),
2566 Self
.getLangOpts().CPlusPlus11
?
2567 diag::warn_cxx98_compat_cast_fn_obj
: diag::ext_cast_fn_obj
)
2569 return SuccessResult
;
2572 // Diagnose address space conversion in nested pointers.
2573 QualType DestPtee
= DestType
->getPointeeType().isNull()
2574 ? DestType
->getPointeeType()
2575 : DestType
->getPointeeType()->getPointeeType();
2576 QualType SrcPtee
= SrcType
->getPointeeType().isNull()
2577 ? SrcType
->getPointeeType()
2578 : SrcType
->getPointeeType()->getPointeeType();
2579 while (!DestPtee
.isNull() && !SrcPtee
.isNull()) {
2580 if (DestPtee
.getAddressSpace() != SrcPtee
.getAddressSpace()) {
2581 Self
.Diag(OpRange
.getBegin(),
2582 diag::warn_bad_cxx_cast_nested_pointer_addr_space
)
2583 << CStyle
<< SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
2586 DestPtee
= DestPtee
->getPointeeType();
2587 SrcPtee
= SrcPtee
->getPointeeType();
2590 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2591 // a pointer to an object of different type.
2592 // Void pointers are not specified, but supported by every compiler out there.
2593 // So we finish by allowing everything that remains - it's got to be two
2595 return SuccessResult
;
2598 static TryCastResult
TryAddressSpaceCast(Sema
&Self
, ExprResult
&SrcExpr
,
2599 QualType DestType
, bool CStyle
,
2600 unsigned &msg
, CastKind
&Kind
) {
2601 if (!Self
.getLangOpts().OpenCL
&& !Self
.getLangOpts().SYCLIsDevice
)
2602 // FIXME: As compiler doesn't have any information about overlapping addr
2603 // spaces at the moment we have to be permissive here.
2604 return TC_NotApplicable
;
2605 // Even though the logic below is general enough and can be applied to
2606 // non-OpenCL mode too, we fast-path above because no other languages
2607 // define overlapping address spaces currently.
2608 auto SrcType
= SrcExpr
.get()->getType();
2609 // FIXME: Should this be generalized to references? The reference parameter
2610 // however becomes a reference pointee type here and therefore rejected.
2611 // Perhaps this is the right behavior though according to C++.
2612 auto SrcPtrType
= SrcType
->getAs
<PointerType
>();
2614 return TC_NotApplicable
;
2615 auto DestPtrType
= DestType
->getAs
<PointerType
>();
2617 return TC_NotApplicable
;
2618 auto SrcPointeeType
= SrcPtrType
->getPointeeType();
2619 auto DestPointeeType
= DestPtrType
->getPointeeType();
2620 if (!DestPointeeType
.isAddressSpaceOverlapping(SrcPointeeType
)) {
2621 msg
= diag::err_bad_cxx_cast_addr_space_mismatch
;
2624 auto SrcPointeeTypeWithoutAS
=
2625 Self
.Context
.removeAddrSpaceQualType(SrcPointeeType
.getCanonicalType());
2626 auto DestPointeeTypeWithoutAS
=
2627 Self
.Context
.removeAddrSpaceQualType(DestPointeeType
.getCanonicalType());
2628 if (Self
.Context
.hasSameType(SrcPointeeTypeWithoutAS
,
2629 DestPointeeTypeWithoutAS
)) {
2630 Kind
= SrcPointeeType
.getAddressSpace() == DestPointeeType
.getAddressSpace()
2632 : CK_AddressSpaceConversion
;
2635 return TC_NotApplicable
;
2639 void CastOperation::checkAddressSpaceCast(QualType SrcType
, QualType DestType
) {
2640 // In OpenCL only conversions between pointers to objects in overlapping
2641 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2642 // with any named one, except for constant.
2644 // Converting the top level pointee addrspace is permitted for compatible
2645 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2646 // if any of the nested pointee addrspaces differ, we emit a warning
2647 // regardless of addrspace compatibility. This makes
2649 // return (generic int **) p;
2650 // warn even though local -> generic is permitted.
2651 if (Self
.getLangOpts().OpenCL
) {
2652 const Type
*DestPtr
, *SrcPtr
;
2653 bool Nested
= false;
2654 unsigned DiagID
= diag::err_typecheck_incompatible_address_space
;
2655 DestPtr
= Self
.getASTContext().getCanonicalType(DestType
.getTypePtr()),
2656 SrcPtr
= Self
.getASTContext().getCanonicalType(SrcType
.getTypePtr());
2658 while (isa
<PointerType
>(DestPtr
) && isa
<PointerType
>(SrcPtr
)) {
2659 const PointerType
*DestPPtr
= cast
<PointerType
>(DestPtr
);
2660 const PointerType
*SrcPPtr
= cast
<PointerType
>(SrcPtr
);
2661 QualType DestPPointee
= DestPPtr
->getPointeeType();
2662 QualType SrcPPointee
= SrcPPtr
->getPointeeType();
2664 ? DestPPointee
.getAddressSpace() != SrcPPointee
.getAddressSpace()
2665 : !DestPPointee
.isAddressSpaceOverlapping(SrcPPointee
)) {
2666 Self
.Diag(OpRange
.getBegin(), DiagID
)
2667 << SrcType
<< DestType
<< Sema::AA_Casting
2668 << SrcExpr
.get()->getSourceRange();
2670 SrcExpr
= ExprError();
2674 DestPtr
= DestPPtr
->getPointeeType().getTypePtr();
2675 SrcPtr
= SrcPPtr
->getPointeeType().getTypePtr();
2677 DiagID
= diag::ext_nested_pointer_qualifier_mismatch
;
2682 bool Sema::ShouldSplatAltivecScalarInCast(const VectorType
*VecTy
) {
2683 bool SrcCompatXL
= this->getLangOpts().getAltivecSrcCompat() ==
2684 LangOptions::AltivecSrcCompatKind::XL
;
2685 VectorKind VKind
= VecTy
->getVectorKind();
2687 if ((VKind
== VectorKind::AltiVecVector
) ||
2688 (SrcCompatXL
&& ((VKind
== VectorKind::AltiVecBool
) ||
2689 (VKind
== VectorKind::AltiVecPixel
)))) {
2695 bool Sema::CheckAltivecInitFromScalar(SourceRange R
, QualType VecTy
,
2697 bool SrcCompatGCC
= this->getLangOpts().getAltivecSrcCompat() ==
2698 LangOptions::AltivecSrcCompatKind::GCC
;
2699 if (this->getLangOpts().AltiVec
&& SrcCompatGCC
) {
2700 this->Diag(R
.getBegin(),
2701 diag::err_invalid_conversion_between_vector_and_integer
)
2702 << VecTy
<< SrcTy
<< R
;
2708 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle
,
2709 bool ListInitialization
) {
2710 assert(Self
.getLangOpts().CPlusPlus
);
2712 // Handle placeholders.
2713 if (isPlaceholder()) {
2714 // C-style casts can resolve __unknown_any types.
2715 if (claimPlaceholder(BuiltinType::UnknownAny
)) {
2716 SrcExpr
= Self
.checkUnknownAnyCast(DestRange
, DestType
,
2717 SrcExpr
.get(), Kind
,
2718 ValueKind
, BasePath
);
2722 checkNonOverloadPlaceholders();
2723 if (SrcExpr
.isInvalid())
2727 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2728 // This test is outside everything else because it's the only case where
2729 // a non-lvalue-reference target type does not lead to decay.
2730 if (DestType
->isVoidType()) {
2733 if (claimPlaceholder(BuiltinType::Overload
)) {
2734 Self
.ResolveAndFixSingleFunctionTemplateSpecialization(
2735 SrcExpr
, /* Decay Function to ptr */ false,
2736 /* Complain */ true, DestRange
, DestType
,
2737 diag::err_bad_cstyle_cast_overload
);
2738 if (SrcExpr
.isInvalid())
2742 SrcExpr
= Self
.IgnoredValueConversions(SrcExpr
.get());
2746 // If the type is dependent, we won't do any other semantic analysis now.
2747 if (DestType
->isDependentType() || SrcExpr
.get()->isTypeDependent() ||
2748 SrcExpr
.get()->isValueDependent()) {
2749 assert(Kind
== CK_Dependent
);
2753 if (ValueKind
== VK_PRValue
&& !DestType
->isRecordType() &&
2754 !isPlaceholder(BuiltinType::Overload
)) {
2755 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
2756 if (SrcExpr
.isInvalid())
2760 // AltiVec vector initialization with a single literal.
2761 if (const VectorType
*vecTy
= DestType
->getAs
<VectorType
>()) {
2762 if (Self
.CheckAltivecInitFromScalar(OpRange
, DestType
,
2763 SrcExpr
.get()->getType())) {
2764 SrcExpr
= ExprError();
2767 if (Self
.ShouldSplatAltivecScalarInCast(vecTy
) &&
2768 (SrcExpr
.get()->getType()->isIntegerType() ||
2769 SrcExpr
.get()->getType()->isFloatingType())) {
2770 Kind
= CK_VectorSplat
;
2771 SrcExpr
= Self
.prepareVectorSplat(DestType
, SrcExpr
.get());
2776 // WebAssembly tables cannot be cast.
2777 QualType SrcType
= SrcExpr
.get()->getType();
2778 if (SrcType
->isWebAssemblyTableType()) {
2779 Self
.Diag(OpRange
.getBegin(), diag::err_wasm_cast_table
)
2780 << 1 << SrcExpr
.get()->getSourceRange();
2781 SrcExpr
= ExprError();
2785 // C++ [expr.cast]p5: The conversions performed by
2788 // - a static_cast followed by a const_cast,
2789 // - a reinterpret_cast, or
2790 // - a reinterpret_cast followed by a const_cast,
2791 // can be performed using the cast notation of explicit type conversion.
2792 // [...] If a conversion can be interpreted in more than one of the ways
2793 // listed above, the interpretation that appears first in the list is used,
2794 // even if a cast resulting from that interpretation is ill-formed.
2795 // In plain language, this means trying a const_cast ...
2796 // Note that for address space we check compatibility after const_cast.
2797 unsigned msg
= diag::err_bad_cxx_cast_generic
;
2798 TryCastResult tcr
= TryConstCast(Self
, SrcExpr
, DestType
,
2799 /*CStyle*/ true, msg
);
2800 if (SrcExpr
.isInvalid())
2802 if (isValidCast(tcr
))
2805 Sema::CheckedConversionKind CCK
=
2806 FunctionalStyle
? Sema::CCK_FunctionalCast
: Sema::CCK_CStyleCast
;
2807 if (tcr
== TC_NotApplicable
) {
2808 tcr
= TryAddressSpaceCast(Self
, SrcExpr
, DestType
, /*CStyle*/ true, msg
,
2810 if (SrcExpr
.isInvalid())
2813 if (tcr
== TC_NotApplicable
) {
2814 // ... or if that is not possible, a static_cast, ignoring const and
2816 tcr
= TryStaticCast(Self
, SrcExpr
, DestType
, CCK
, OpRange
, msg
, Kind
,
2817 BasePath
, ListInitialization
);
2818 if (SrcExpr
.isInvalid())
2821 if (tcr
== TC_NotApplicable
) {
2822 // ... and finally a reinterpret_cast, ignoring const and addr space.
2823 tcr
= TryReinterpretCast(Self
, SrcExpr
, DestType
, /*CStyle*/ true,
2824 OpRange
, msg
, Kind
);
2825 if (SrcExpr
.isInvalid())
2831 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2833 checkObjCConversion(CCK
);
2835 if (tcr
!= TC_Success
&& msg
!= 0) {
2836 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
2837 DeclAccessPair Found
;
2838 FunctionDecl
*Fn
= Self
.ResolveAddressOfOverloadedFunction(SrcExpr
.get(),
2843 // If DestType is a function type (not to be confused with the function
2844 // pointer type), it will be possible to resolve the function address,
2845 // but the type cast should be considered as failure.
2846 OverloadExpr
*OE
= OverloadExpr::find(SrcExpr
.get()).Expression
;
2847 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cstyle_cast_overload
)
2848 << OE
->getName() << DestType
<< OpRange
2849 << OE
->getQualifierLoc().getSourceRange();
2850 Self
.NoteAllOverloadCandidates(SrcExpr
.get());
2853 diagnoseBadCast(Self
, msg
, (FunctionalStyle
? CT_Functional
: CT_CStyle
),
2854 OpRange
, SrcExpr
.get(), DestType
, ListInitialization
);
2858 if (isValidCast(tcr
)) {
2859 if (Kind
== CK_BitCast
)
2862 if (unsigned DiagID
= checkCastFunctionType(Self
, SrcExpr
, DestType
))
2863 Self
.Diag(OpRange
.getBegin(), DiagID
)
2864 << SrcExpr
.get()->getType() << DestType
<< OpRange
;
2867 SrcExpr
= ExprError();
2871 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2872 /// non-matching type. Such as enum function call to int, int call to
2873 /// pointer; etc. Cast to 'void' is an exception.
2874 static void DiagnoseBadFunctionCast(Sema
&Self
, const ExprResult
&SrcExpr
,
2875 QualType DestType
) {
2876 if (Self
.Diags
.isIgnored(diag::warn_bad_function_cast
,
2877 SrcExpr
.get()->getExprLoc()))
2880 if (!isa
<CallExpr
>(SrcExpr
.get()))
2883 QualType SrcType
= SrcExpr
.get()->getType();
2884 if (DestType
.getUnqualifiedType()->isVoidType())
2886 if ((SrcType
->isAnyPointerType() || SrcType
->isBlockPointerType())
2887 && (DestType
->isAnyPointerType() || DestType
->isBlockPointerType()))
2889 if (SrcType
->isIntegerType() && DestType
->isIntegerType() &&
2890 (SrcType
->isBooleanType() == DestType
->isBooleanType()) &&
2891 (SrcType
->isEnumeralType() == DestType
->isEnumeralType()))
2893 if (SrcType
->isRealFloatingType() && DestType
->isRealFloatingType())
2895 if (SrcType
->isEnumeralType() && DestType
->isEnumeralType())
2897 if (SrcType
->isComplexType() && DestType
->isComplexType())
2899 if (SrcType
->isComplexIntegerType() && DestType
->isComplexIntegerType())
2901 if (SrcType
->isFixedPointType() && DestType
->isFixedPointType())
2904 Self
.Diag(SrcExpr
.get()->getExprLoc(),
2905 diag::warn_bad_function_cast
)
2906 << SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
2909 /// Check the semantics of a C-style cast operation, in C.
2910 void CastOperation::CheckCStyleCast() {
2911 assert(!Self
.getLangOpts().CPlusPlus
);
2913 // C-style casts can resolve __unknown_any types.
2914 if (claimPlaceholder(BuiltinType::UnknownAny
)) {
2915 SrcExpr
= Self
.checkUnknownAnyCast(DestRange
, DestType
,
2916 SrcExpr
.get(), Kind
,
2917 ValueKind
, BasePath
);
2921 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2922 // type needs to be scalar.
2923 if (DestType
->isVoidType()) {
2924 // We don't necessarily do lvalue-to-rvalue conversions on this.
2925 SrcExpr
= Self
.IgnoredValueConversions(SrcExpr
.get());
2926 if (SrcExpr
.isInvalid())
2929 // Cast to void allows any expr type.
2934 // If the type is dependent, we won't do any other semantic analysis now.
2935 if (Self
.getASTContext().isDependenceAllowed() &&
2936 (DestType
->isDependentType() || SrcExpr
.get()->isTypeDependent() ||
2937 SrcExpr
.get()->isValueDependent())) {
2938 assert((DestType
->containsErrors() || SrcExpr
.get()->containsErrors() ||
2939 SrcExpr
.get()->containsErrors()) &&
2940 "should only occur in error-recovery path.");
2941 assert(Kind
== CK_Dependent
);
2945 // Overloads are allowed with C extensions, so we need to support them.
2946 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
2948 if (FunctionDecl
*FD
= Self
.ResolveAddressOfOverloadedFunction(
2949 SrcExpr
.get(), DestType
, /*Complain=*/true, DAP
))
2950 SrcExpr
= Self
.FixOverloadedFunctionReference(SrcExpr
.get(), DAP
, FD
);
2953 assert(SrcExpr
.isUsable());
2955 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
2956 if (SrcExpr
.isInvalid())
2958 QualType SrcType
= SrcExpr
.get()->getType();
2960 if (SrcType
->isWebAssemblyTableType()) {
2961 Self
.Diag(OpRange
.getBegin(), diag::err_wasm_cast_table
)
2962 << 1 << SrcExpr
.get()->getSourceRange();
2963 SrcExpr
= ExprError();
2967 assert(!SrcType
->isPlaceholderType());
2969 checkAddressSpaceCast(SrcType
, DestType
);
2970 if (SrcExpr
.isInvalid())
2973 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
2974 diag::err_typecheck_cast_to_incomplete
)) {
2975 SrcExpr
= ExprError();
2979 // Allow casting a sizeless built-in type to itself.
2980 if (DestType
->isSizelessBuiltinType() &&
2981 Self
.Context
.hasSameUnqualifiedType(DestType
, SrcType
)) {
2986 // Allow bitcasting between compatible SVE vector types.
2987 if ((SrcType
->isVectorType() || DestType
->isVectorType()) &&
2988 Self
.isValidSveBitcast(SrcType
, DestType
)) {
2993 // Allow bitcasting between compatible RVV vector types.
2994 if ((SrcType
->isVectorType() || DestType
->isVectorType()) &&
2995 Self
.isValidRVVBitcast(SrcType
, DestType
)) {
3000 if (!DestType
->isScalarType() && !DestType
->isVectorType() &&
3001 !DestType
->isMatrixType()) {
3002 const RecordType
*DestRecordTy
= DestType
->getAs
<RecordType
>();
3004 if (DestRecordTy
&& Self
.Context
.hasSameUnqualifiedType(DestType
, SrcType
)){
3005 // GCC struct/union extension: allow cast to self.
3006 Self
.Diag(OpRange
.getBegin(), diag::ext_typecheck_cast_nonscalar
)
3007 << DestType
<< SrcExpr
.get()->getSourceRange();
3012 // GCC's cast to union extension.
3013 if (DestRecordTy
&& DestRecordTy
->getDecl()->isUnion()) {
3014 RecordDecl
*RD
= DestRecordTy
->getDecl();
3015 if (CastExpr::getTargetFieldForToUnionCast(RD
, SrcType
)) {
3016 Self
.Diag(OpRange
.getBegin(), diag::ext_typecheck_cast_to_union
)
3017 << SrcExpr
.get()->getSourceRange();
3021 Self
.Diag(OpRange
.getBegin(), diag::err_typecheck_cast_to_union_no_type
)
3022 << SrcType
<< SrcExpr
.get()->getSourceRange();
3023 SrcExpr
= ExprError();
3028 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
3029 if (Self
.getLangOpts().OpenCL
&& DestType
->isEventT()) {
3030 Expr::EvalResult Result
;
3031 if (SrcExpr
.get()->EvaluateAsInt(Result
, Self
.Context
)) {
3032 llvm::APSInt CastInt
= Result
.Val
.getInt();
3034 Kind
= CK_ZeroToOCLOpaqueType
;
3037 Self
.Diag(OpRange
.getBegin(),
3038 diag::err_opencl_cast_non_zero_to_event_t
)
3039 << toString(CastInt
, 10) << SrcExpr
.get()->getSourceRange();
3040 SrcExpr
= ExprError();
3045 // Reject any other conversions to non-scalar types.
3046 Self
.Diag(OpRange
.getBegin(), diag::err_typecheck_cond_expect_scalar
)
3047 << DestType
<< SrcExpr
.get()->getSourceRange();
3048 SrcExpr
= ExprError();
3052 // The type we're casting to is known to be a scalar, a vector, or a matrix.
3054 // Require the operand to be a scalar, a vector, or a matrix.
3055 if (!SrcType
->isScalarType() && !SrcType
->isVectorType() &&
3056 !SrcType
->isMatrixType()) {
3057 Self
.Diag(SrcExpr
.get()->getExprLoc(),
3058 diag::err_typecheck_expect_scalar_operand
)
3059 << SrcType
<< SrcExpr
.get()->getSourceRange();
3060 SrcExpr
= ExprError();
3065 // The type nullptr_t shall not be converted to any type other than void,
3066 // bool, or a pointer type. No type other than nullptr_t shall be converted
3068 if (SrcType
->isNullPtrType()) {
3069 // FIXME: 6.3.2.4p2 says that nullptr_t can be converted to itself, but
3070 // 6.5.4p4 is a constraint check and nullptr_t is not void, bool, or a
3071 // pointer type. We're not going to diagnose that as a constraint violation.
3072 if (!DestType
->isVoidType() && !DestType
->isBooleanType() &&
3073 !DestType
->isPointerType() && !DestType
->isNullPtrType()) {
3074 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_nullptr_cast
)
3075 << /*nullptr to type*/ 0 << DestType
;
3076 SrcExpr
= ExprError();
3079 if (!DestType
->isNullPtrType()) {
3080 // Implicitly cast from the null pointer type to the type of the
3082 CastKind CK
= DestType
->isPointerType() ? CK_NullToPointer
: CK_BitCast
;
3083 SrcExpr
= ImplicitCastExpr::Create(Self
.Context
, DestType
, CK
,
3084 SrcExpr
.get(), nullptr, VK_PRValue
,
3085 Self
.CurFPFeatureOverrides());
3088 if (DestType
->isNullPtrType() && !SrcType
->isNullPtrType()) {
3089 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_nullptr_cast
)
3090 << /*type to nullptr*/ 1 << SrcType
;
3091 SrcExpr
= ExprError();
3095 if (DestType
->isExtVectorType()) {
3096 SrcExpr
= Self
.CheckExtVectorCast(OpRange
, DestType
, SrcExpr
.get(), Kind
);
3100 if (DestType
->getAs
<MatrixType
>() || SrcType
->getAs
<MatrixType
>()) {
3101 if (Self
.CheckMatrixCast(OpRange
, DestType
, SrcType
, Kind
))
3102 SrcExpr
= ExprError();
3106 if (const VectorType
*DestVecTy
= DestType
->getAs
<VectorType
>()) {
3107 if (Self
.CheckAltivecInitFromScalar(OpRange
, DestType
, SrcType
)) {
3108 SrcExpr
= ExprError();
3111 if (Self
.ShouldSplatAltivecScalarInCast(DestVecTy
) &&
3112 (SrcType
->isIntegerType() || SrcType
->isFloatingType())) {
3113 Kind
= CK_VectorSplat
;
3114 SrcExpr
= Self
.prepareVectorSplat(DestType
, SrcExpr
.get());
3115 } else if (Self
.CheckVectorCast(OpRange
, DestType
, SrcType
, Kind
)) {
3116 SrcExpr
= ExprError();
3121 if (SrcType
->isVectorType()) {
3122 if (Self
.CheckVectorCast(OpRange
, SrcType
, DestType
, Kind
))
3123 SrcExpr
= ExprError();
3127 // The source and target types are both scalars, i.e.
3128 // - arithmetic types (fundamental, enum, and complex)
3129 // - all kinds of pointers
3130 // Note that member pointers were filtered out with C++, above.
3132 if (isa
<ObjCSelectorExpr
>(SrcExpr
.get())) {
3133 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_cast_selector_expr
);
3134 SrcExpr
= ExprError();
3138 // If either type is a pointer, the other type has to be either an
3139 // integer or a pointer.
3140 if (!DestType
->isArithmeticType()) {
3141 if (!SrcType
->isIntegralType(Self
.Context
) && SrcType
->isArithmeticType()) {
3142 Self
.Diag(SrcExpr
.get()->getExprLoc(),
3143 diag::err_cast_pointer_from_non_pointer_int
)
3144 << SrcType
<< SrcExpr
.get()->getSourceRange();
3145 SrcExpr
= ExprError();
3148 checkIntToPointerCast(/* CStyle */ true, OpRange
, SrcExpr
.get(), DestType
,
3150 } else if (!SrcType
->isArithmeticType()) {
3151 if (!DestType
->isIntegralType(Self
.Context
) &&
3152 DestType
->isArithmeticType()) {
3153 Self
.Diag(SrcExpr
.get()->getBeginLoc(),
3154 diag::err_cast_pointer_to_non_pointer_int
)
3155 << DestType
<< SrcExpr
.get()->getSourceRange();
3156 SrcExpr
= ExprError();
3160 if ((Self
.Context
.getTypeSize(SrcType
) >
3161 Self
.Context
.getTypeSize(DestType
)) &&
3162 !DestType
->isBooleanType()) {
3163 // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3164 // Except as previously specified, the result is implementation-defined.
3165 // If the result cannot be represented in the integer type, the behavior
3166 // is undefined. The result need not be in the range of values of any
3169 if (SrcType
->isVoidPointerType())
3170 Diag
= DestType
->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
3171 : diag::warn_void_pointer_to_int_cast
;
3172 else if (DestType
->isEnumeralType())
3173 Diag
= diag::warn_pointer_to_enum_cast
;
3175 Diag
= diag::warn_pointer_to_int_cast
;
3176 Self
.Diag(OpRange
.getBegin(), Diag
) << SrcType
<< DestType
<< OpRange
;
3180 if (Self
.getLangOpts().OpenCL
&& !Self
.getOpenCLOptions().isAvailableOption(
3181 "cl_khr_fp16", Self
.getLangOpts())) {
3182 if (DestType
->isHalfType()) {
3183 Self
.Diag(SrcExpr
.get()->getBeginLoc(), diag::err_opencl_cast_to_half
)
3184 << DestType
<< SrcExpr
.get()->getSourceRange();
3185 SrcExpr
= ExprError();
3190 // ARC imposes extra restrictions on casts.
3191 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3192 checkObjCConversion(Sema::CCK_CStyleCast
);
3193 if (SrcExpr
.isInvalid())
3196 const PointerType
*CastPtr
= DestType
->getAs
<PointerType
>();
3197 if (Self
.getLangOpts().ObjCAutoRefCount
&& CastPtr
) {
3198 if (const PointerType
*ExprPtr
= SrcType
->getAs
<PointerType
>()) {
3199 Qualifiers CastQuals
= CastPtr
->getPointeeType().getQualifiers();
3200 Qualifiers ExprQuals
= ExprPtr
->getPointeeType().getQualifiers();
3201 if (CastPtr
->getPointeeType()->isObjCLifetimeType() &&
3202 ExprPtr
->getPointeeType()->isObjCLifetimeType() &&
3203 !CastQuals
.compatiblyIncludesObjCLifetime(ExprQuals
)) {
3204 Self
.Diag(SrcExpr
.get()->getBeginLoc(),
3205 diag::err_typecheck_incompatible_ownership
)
3206 << SrcType
<< DestType
<< Sema::AA_Casting
3207 << SrcExpr
.get()->getSourceRange();
3212 else if (!Self
.CheckObjCARCUnavailableWeakConversion(DestType
, SrcType
)) {
3213 Self
.Diag(SrcExpr
.get()->getBeginLoc(),
3214 diag::err_arc_convesion_of_weak_unavailable
)
3215 << 1 << SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
3216 SrcExpr
= ExprError();
3221 if (unsigned DiagID
= checkCastFunctionType(Self
, SrcExpr
, DestType
))
3222 Self
.Diag(OpRange
.getBegin(), DiagID
) << SrcType
<< DestType
<< OpRange
;
3224 if (isa
<PointerType
>(SrcType
) && isa
<PointerType
>(DestType
)) {
3225 QualType SrcTy
= cast
<PointerType
>(SrcType
)->getPointeeType();
3226 QualType DestTy
= cast
<PointerType
>(DestType
)->getPointeeType();
3228 const RecordDecl
*SrcRD
= SrcTy
->getAsRecordDecl();
3229 const RecordDecl
*DestRD
= DestTy
->getAsRecordDecl();
3231 if (SrcRD
&& DestRD
&& SrcRD
->hasAttr
<RandomizeLayoutAttr
>() &&
3233 // The struct we are casting the pointer from was randomized.
3234 Self
.Diag(OpRange
.getBegin(), diag::err_cast_from_randomized_struct
)
3235 << SrcType
<< DestType
;
3236 SrcExpr
= ExprError();
3241 DiagnoseCastOfObjCSEL(Self
, SrcExpr
, DestType
);
3242 DiagnoseCallingConvCast(Self
, SrcExpr
, DestType
, OpRange
);
3243 DiagnoseBadFunctionCast(Self
, SrcExpr
, DestType
);
3244 Kind
= Self
.PrepareScalarCast(SrcExpr
, DestType
);
3245 if (SrcExpr
.isInvalid())
3248 if (Kind
== CK_BitCast
)
3252 void CastOperation::CheckBuiltinBitCast() {
3253 QualType SrcType
= SrcExpr
.get()->getType();
3255 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
3256 diag::err_typecheck_cast_to_incomplete
) ||
3257 Self
.RequireCompleteType(OpRange
.getBegin(), SrcType
,
3258 diag::err_incomplete_type
)) {
3259 SrcExpr
= ExprError();
3263 if (SrcExpr
.get()->isPRValue())
3264 SrcExpr
= Self
.CreateMaterializeTemporaryExpr(SrcType
, SrcExpr
.get(),
3265 /*IsLValueReference=*/false);
3267 CharUnits DestSize
= Self
.Context
.getTypeSizeInChars(DestType
);
3268 CharUnits SourceSize
= Self
.Context
.getTypeSizeInChars(SrcType
);
3269 if (DestSize
!= SourceSize
) {
3270 Self
.Diag(OpRange
.getBegin(), diag::err_bit_cast_type_size_mismatch
)
3271 << (int)SourceSize
.getQuantity() << (int)DestSize
.getQuantity();
3272 SrcExpr
= ExprError();
3276 if (!DestType
.isTriviallyCopyableType(Self
.Context
)) {
3277 Self
.Diag(OpRange
.getBegin(), diag::err_bit_cast_non_trivially_copyable
)
3279 SrcExpr
= ExprError();
3283 if (!SrcType
.isTriviallyCopyableType(Self
.Context
)) {
3284 Self
.Diag(OpRange
.getBegin(), diag::err_bit_cast_non_trivially_copyable
)
3286 SrcExpr
= ExprError();
3290 Kind
= CK_LValueToRValueBitCast
;
3293 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3294 /// const, volatile or both.
3295 static void DiagnoseCastQual(Sema
&Self
, const ExprResult
&SrcExpr
,
3296 QualType DestType
) {
3297 if (SrcExpr
.isInvalid())
3300 QualType SrcType
= SrcExpr
.get()->getType();
3301 if (!((SrcType
->isAnyPointerType() && DestType
->isAnyPointerType()) ||
3302 DestType
->isLValueReferenceType()))
3305 QualType TheOffendingSrcType
, TheOffendingDestType
;
3306 Qualifiers CastAwayQualifiers
;
3307 if (CastsAwayConstness(Self
, SrcType
, DestType
, true, false,
3308 &TheOffendingSrcType
, &TheOffendingDestType
,
3309 &CastAwayQualifiers
) !=
3310 CastAwayConstnessKind::CACK_Similar
)
3313 // FIXME: 'restrict' is not properly handled here.
3314 int qualifiers
= -1;
3315 if (CastAwayQualifiers
.hasConst() && CastAwayQualifiers
.hasVolatile()) {
3317 } else if (CastAwayQualifiers
.hasConst()) {
3319 } else if (CastAwayQualifiers
.hasVolatile()) {
3322 // This is a variant of int **x; const int **y = (const int **)x;
3323 if (qualifiers
== -1)
3324 Self
.Diag(SrcExpr
.get()->getBeginLoc(), diag::warn_cast_qual2
)
3325 << SrcType
<< DestType
;
3327 Self
.Diag(SrcExpr
.get()->getBeginLoc(), diag::warn_cast_qual
)
3328 << TheOffendingSrcType
<< TheOffendingDestType
<< qualifiers
;
3331 ExprResult
Sema::BuildCStyleCastExpr(SourceLocation LPLoc
,
3332 TypeSourceInfo
*CastTypeInfo
,
3333 SourceLocation RPLoc
,
3335 CastOperation
Op(*this, CastTypeInfo
->getType(), CastExpr
);
3336 Op
.DestRange
= CastTypeInfo
->getTypeLoc().getSourceRange();
3337 Op
.OpRange
= SourceRange(LPLoc
, CastExpr
->getEndLoc());
3339 if (getLangOpts().CPlusPlus
) {
3340 Op
.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3341 isa
<InitListExpr
>(CastExpr
));
3343 Op
.CheckCStyleCast();
3346 if (Op
.SrcExpr
.isInvalid())
3350 DiagnoseCastQual(Op
.Self
, Op
.SrcExpr
, Op
.DestType
);
3352 return Op
.complete(CStyleCastExpr::Create(
3353 Context
, Op
.ResultType
, Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
3354 &Op
.BasePath
, CurFPFeatureOverrides(), CastTypeInfo
, LPLoc
, RPLoc
));
3357 ExprResult
Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo
*CastTypeInfo
,
3359 SourceLocation LPLoc
,
3361 SourceLocation RPLoc
) {
3362 assert(LPLoc
.isValid() && "List-initialization shouldn't get here.");
3363 CastOperation
Op(*this, Type
, CastExpr
);
3364 Op
.DestRange
= CastTypeInfo
->getTypeLoc().getSourceRange();
3365 Op
.OpRange
= SourceRange(Op
.DestRange
.getBegin(), RPLoc
);
3367 Op
.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3368 if (Op
.SrcExpr
.isInvalid())
3371 auto *SubExpr
= Op
.SrcExpr
.get();
3372 if (auto *BindExpr
= dyn_cast
<CXXBindTemporaryExpr
>(SubExpr
))
3373 SubExpr
= BindExpr
->getSubExpr();
3374 if (auto *ConstructExpr
= dyn_cast
<CXXConstructExpr
>(SubExpr
))
3375 ConstructExpr
->setParenOrBraceRange(SourceRange(LPLoc
, RPLoc
));
3378 DiagnoseCastQual(Op
.Self
, Op
.SrcExpr
, Op
.DestType
);
3380 return Op
.complete(CXXFunctionalCastExpr::Create(
3381 Context
, Op
.ResultType
, Op
.ValueKind
, CastTypeInfo
, Op
.Kind
,
3382 Op
.SrcExpr
.get(), &Op
.BasePath
, CurFPFeatureOverrides(), LPLoc
, RPLoc
));