#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Initialization.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "llvm/ADT/SmallVector.h"
#include <set>
using namespace clang;
enum TryCastResult {
TC_NotApplicable, TC_Success, TC_Failed };
enum CastType {
CT_Const, CT_Static, CT_Reinterpret, CT_Dynamic, CT_CStyle, CT_Functional };
namespace {
struct CastOperation {
CastOperation(Sema &S, QualType destType, ExprResult src)
: Self(S), SrcExpr(src), DestType(destType),
ResultType(destType.getNonLValueExprType(S.Context)),
ValueKind(Expr::getValueKindForType(destType)),
Kind(CK_Dependent), IsARCUnbridgedCast(false) {
if (const BuiltinType *placeholder =
src.get()->getType()->getAsPlaceholderType()) {
PlaceholderKind = placeholder->getKind();
} else {
PlaceholderKind = (BuiltinType::Kind) 0;
}
}
Sema &Self;
ExprResult SrcExpr;
QualType DestType;
QualType ResultType;
ExprValueKind ValueKind;
CastKind Kind;
BuiltinType::Kind PlaceholderKind;
CXXCastPath BasePath;
bool IsARCUnbridgedCast;
SourceRange OpRange;
SourceRange DestRange;
void CheckConstCast();
void CheckReinterpretCast();
void CheckStaticCast();
void CheckDynamicCast();
void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
void CheckCStyleCast();
ExprResult complete(CastExpr *castExpr) {
if (IsARCUnbridgedCast) {
castExpr = ImplicitCastExpr::Create(Self.Context,
Self.Context.ARCUnbridgedCastTy,
CK_Dependent, castExpr, 0,
castExpr->getValueKind());
}
return Self.Owned(castExpr);
}
bool claimPlaceholder(BuiltinType::Kind K) {
if (PlaceholderKind != K) return false;
PlaceholderKind = (BuiltinType::Kind) 0;
return true;
}
bool isPlaceholder() const {
return PlaceholderKind != 0;
}
bool isPlaceholder(BuiltinType::Kind K) const {
return PlaceholderKind == K;
}
void checkCastAlign() {
Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
}
void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
assert(Self.getLangOpts().ObjCAutoRefCount);
Expr *src = SrcExpr.get();
if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
Sema::ACR_unbridged)
IsARCUnbridgedCast = true;
SrcExpr = src;
}
void checkNonOverloadPlaceholders() {
if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
return;
SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
if (SrcExpr.isInvalid())
return;
PlaceholderKind = (BuiltinType::Kind) 0;
}
};
}
static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
bool CheckCVR, bool CheckObjCLifetime);
static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
QualType DestType, bool CStyle,
CastKind &Kind,
CXXCastPath &BasePath,
unsigned &msg);
static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
CanQualType DestType, bool CStyle,
const SourceRange &OpRange,
QualType OrigSrcType,
QualType OrigDestType, unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
QualType SrcType,
QualType DestType,bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind,
CXXCastPath &BasePath);
static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
bool ListInitialization);
static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath,
bool ListInitialization);
static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
bool CStyle, unsigned &msg);
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind);
ExprResult
Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
SourceLocation LAngleBracketLoc, Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc, Expr *E,
SourceLocation RParenLoc) {
assert(!D.isInvalidType());
TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
if (D.isInvalidType())
return ExprError();
if (getLangOpts().CPlusPlus) {
CheckExtraCXXDefaultArguments(D);
}
return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
SourceRange(LAngleBracketLoc, RAngleBracketLoc),
SourceRange(LParenLoc, RParenLoc));
}
ExprResult
Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
TypeSourceInfo *DestTInfo, Expr *E,
SourceRange AngleBrackets, SourceRange Parens) {
ExprResult Ex = Owned(E);
QualType DestType = DestTInfo->getType();
bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
CastOperation Op(*this, DestType, E);
Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
Op.DestRange = AngleBrackets;
switch (Kind) {
default: llvm_unreachable("Unknown C++ cast!");
case tok::kw_const_cast:
if (!TypeDependent) {
Op.CheckConstCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
OpLoc, Parens.getEnd()));
case tok::kw_dynamic_cast: {
if (!TypeDependent) {
Op.CheckDynamicCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
&Op.BasePath, DestTInfo,
OpLoc, Parens.getEnd()));
}
case tok::kw_reinterpret_cast: {
if (!TypeDependent) {
Op.CheckReinterpretCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
0, DestTInfo, OpLoc,
Parens.getEnd()));
}
case tok::kw_static_cast: {
if (!TypeDependent) {
Op.CheckStaticCast();
if (Op.SrcExpr.isInvalid())
return ExprError();
}
return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
&Op.BasePath, DestTInfo,
OpLoc, Parens.getEnd()));
}
}
}
static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
SourceRange range, Expr *src,
QualType destType,
bool listInitialization) {
switch (CT) {
case CT_Const:
case CT_Reinterpret:
case CT_Dynamic:
return false;
case CT_Static:
case CT_CStyle:
case CT_Functional:
break;
}
QualType srcType = src->getType();
if (!destType->isRecordType() && !srcType->isRecordType())
return false;
InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
InitializationKind initKind
= (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
range, listInitialization)
: (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
listInitialization)
: InitializationKind::CreateCast( range);
InitializationSequence sequence(S, entity, initKind, &src, 1);
assert(sequence.Failed() && "initialization succeeded on second try?");
switch (sequence.getFailureKind()) {
default: return false;
case InitializationSequence::FK_ConstructorOverloadFailed:
case InitializationSequence::FK_UserConversionOverloadFailed:
break;
}
OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
unsigned msg = 0;
OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
switch (sequence.getFailedOverloadResult()) {
case OR_Success: llvm_unreachable("successful failed overload");
case OR_No_Viable_Function:
if (candidates.empty())
msg = diag::err_ovl_no_conversion_in_cast;
else
msg = diag::err_ovl_no_viable_conversion_in_cast;
howManyCandidates = OCD_AllCandidates;
break;
case OR_Ambiguous:
msg = diag::err_ovl_ambiguous_conversion_in_cast;
howManyCandidates = OCD_ViableCandidates;
break;
case OR_Deleted:
msg = diag::err_ovl_deleted_conversion_in_cast;
howManyCandidates = OCD_ViableCandidates;
break;
}
S.Diag(range.getBegin(), msg)
<< CT << srcType << destType
<< range << src->getSourceRange();
candidates.NoteCandidates(S, howManyCandidates, src);
return true;
}
static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
SourceRange opRange, Expr *src, QualType destType,
bool listInitialization) {
if (src->getType() == S.Context.BoundMemberTy) {
(void) S.CheckPlaceholderExpr(src); return;
}
if (msg == diag::err_bad_cxx_cast_generic &&
tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
listInitialization))
return;
S.Diag(opRange.getBegin(), msg) << castType
<< src->getType() << destType << opRange << src->getSourceRange();
}
static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
const PointerType *T1PtrType = T1->getAs<PointerType>(),
*T2PtrType = T2->getAs<PointerType>();
if (T1PtrType && T2PtrType) {
T1 = T1PtrType->getPointeeType();
T2 = T2PtrType->getPointeeType();
return true;
}
const ObjCObjectPointerType *T1ObjCPtrType =
T1->getAs<ObjCObjectPointerType>(),
*T2ObjCPtrType =
T2->getAs<ObjCObjectPointerType>();
if (T1ObjCPtrType) {
if (T2ObjCPtrType) {
T1 = T1ObjCPtrType->getPointeeType();
T2 = T2ObjCPtrType->getPointeeType();
return true;
}
else if (T2PtrType) {
T1 = T1ObjCPtrType->getPointeeType();
T2 = T2PtrType->getPointeeType();
return true;
}
}
else if (T2ObjCPtrType) {
if (T1PtrType) {
T2 = T2ObjCPtrType->getPointeeType();
T1 = T1PtrType->getPointeeType();
return true;
}
}
const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
*T2MPType = T2->getAs<MemberPointerType>();
if (T1MPType && T2MPType) {
T1 = T1MPType->getPointeeType();
T2 = T2MPType->getPointeeType();
return true;
}
const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
*T2BPType = T2->getAs<BlockPointerType>();
if (T1BPType && T2BPType) {
T1 = T1BPType->getPointeeType();
T2 = T2BPType->getPointeeType();
return true;
}
return false;
}
static bool
CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
bool CheckCVR, bool CheckObjCLifetime) {
if (!CheckCVR && CheckObjCLifetime &&
!Self.Context.getLangOpts().ObjCAutoRefCount)
return false;
assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
SrcType->isBlockPointerType()) &&
"Source type is not pointer or pointer to member.");
assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
DestType->isBlockPointerType()) &&
"Destination type is not pointer or pointer to member.");
QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
UnwrappedDestType = Self.Context.getCanonicalType(DestType);
SmallVector<Qualifiers, 8> cv1, cv2;
while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Qualifiers SrcQuals, DestQuals;
Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Qualifiers RetainedSrcQuals, RetainedDestQuals;
if (CheckCVR) {
RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
}
if (CheckObjCLifetime &&
!DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
return true;
cv1.push_back(RetainedSrcQuals);
cv2.push_back(RetainedDestQuals);
}
if (cv1.empty())
return false;
QualType SrcConstruct = Self.Context.VoidTy;
QualType DestConstruct = Self.Context.VoidTy;
ASTContext &Context = Self.Context;
for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
i2 = cv2.rbegin();
i1 != cv1.rend(); ++i1, ++i2) {
SrcConstruct
= Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
DestConstruct
= Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
}
bool ObjCLifetimeConversion;
return SrcConstruct != DestConstruct &&
!Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
ObjCLifetimeConversion);
}
void CastOperation::CheckDynamicCast() {
if (ValueKind == VK_RValue)
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
else if (isPlaceholder())
SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
if (SrcExpr.isInvalid()) return;
QualType OrigSrcType = SrcExpr.get()->getType();
QualType DestType = Self.Context.getCanonicalType(this->DestType);
QualType DestPointee;
const PointerType *DestPointer = DestType->getAs<PointerType>();
const ReferenceType *DestReference = 0;
if (DestPointer) {
DestPointee = DestPointer->getPointeeType();
} else if ((DestReference = DestType->getAs<ReferenceType>())) {
DestPointee = DestReference->getPointeeType();
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
<< this->DestType << DestRange;
return;
}
const RecordType *DestRecord = DestPointee->getAs<RecordType>();
if (DestPointee->isVoidType()) {
assert(DestPointer && "Reference to void is not possible");
} else if (DestRecord) {
if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
diag::err_bad_dynamic_cast_incomplete,
DestRange))
return;
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
<< DestPointee.getUnqualifiedType() << DestRange;
return;
}
QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
QualType SrcPointee;
if (DestPointer) {
if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
SrcPointee = SrcPointer->getPointeeType();
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
<< OrigSrcType << SrcExpr.get()->getSourceRange();
return;
}
} else if (DestReference->isLValueReferenceType()) {
if (!SrcExpr.get()->isLValue()) {
Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;
}
SrcPointee = SrcType;
} else {
SrcPointee = SrcType;
}
const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
if (SrcRecord) {
if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
diag::err_bad_dynamic_cast_incomplete,
SrcExpr.get()))
return;
} else {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
return;
}
assert((DestPointer || DestReference) &&
"Bad destination non-ptr/ref slipped through.");
assert((DestRecord || DestPointee->isVoidType()) &&
"Bad destination pointee slipped through.");
assert(SrcRecord && "Bad source pointee slipped through.");
if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;
return;
}
if (DestRecord == SrcRecord) {
Kind = CK_NoOp;
return;
}
if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
OpRange.getBegin(), OpRange,
&BasePath))
return;
Kind = CK_DerivedToBase;
if (Self.BasePathInvolvesVirtualBase(BasePath))
Self.MarkVTableUsed(OpRange.getBegin(),
cast<CXXRecordDecl>(SrcRecord->getDecl()));
return;
}
const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
assert(SrcDecl && "Definition missing");
if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
}
Self.MarkVTableUsed(OpRange.getBegin(),
cast<CXXRecordDecl>(SrcRecord->getDecl()));
Kind = CK_Dynamic;
}
void CastOperation::CheckConstCast() {
if (ValueKind == VK_RValue)
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
else if (isPlaceholder())
SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
if (SrcExpr.isInvalid()) return;
unsigned msg = diag::err_bad_cxx_cast_generic;
if (TryConstCast(Self, SrcExpr.get(), DestType, false, msg) != TC_Success
&& msg != 0)
Self.Diag(OpRange.getBegin(), msg) << CT_Const
<< SrcExpr.get()->getType() << DestType << OpRange;
}
void CastOperation::CheckReinterpretCast() {
if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
else
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid()) return;
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr =
TryReinterpretCast(Self, SrcExpr, DestType,
false, OpRange, msg, Kind);
if (tcr != TC_Success && msg != 0)
{
if (SrcExpr.isInvalid()) return;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
<< OverloadExpr::find(SrcExpr.get()).Expression->getName()
<< DestType << OpRange;
Self.NoteAllOverloadCandidates(SrcExpr.get());
} else {
diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
DestType, false);
}
} else if (tcr == TC_Success && Self.getLangOpts().ObjCAutoRefCount) {
checkObjCARCConversion(Sema::CCK_OtherCast);
}
}
void CastOperation::CheckStaticCast() {
if (isPlaceholder()) {
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid())
return;
}
if (DestType->isVoidType()) {
Kind = CK_ToVoid;
if (claimPlaceholder(BuiltinType::Overload)) {
Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
false, true, OpRange, DestType, diag::err_bad_static_cast_overload);
if (SrcExpr.isInvalid())
return;
}
SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
return;
}
if (ValueKind == VK_RValue && !DestType->isRecordType() &&
!isPlaceholder(BuiltinType::Overload)) {
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
if (SrcExpr.isInvalid()) return;
}
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr
= TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Kind, BasePath, false);
if (tcr != TC_Success && msg != 0) {
if (SrcExpr.isInvalid())
return;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
<< oe->getName() << DestType << OpRange
<< oe->getQualifierLoc().getSourceRange();
Self.NoteAllOverloadCandidates(SrcExpr.get());
} else {
diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
false);
}
} else if (tcr == TC_Success) {
if (Kind == CK_BitCast)
checkCastAlign();
if (Self.getLangOpts().ObjCAutoRefCount)
checkObjCARCConversion(Sema::CCK_OtherCast);
} else if (Kind == CK_BitCast) {
checkCastAlign();
}
}
static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange, unsigned &msg,
CastKind &Kind, CXXCastPath &BasePath,
bool ListInitialization) {
bool CStyle
= (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
TryCastResult tcr;
tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
OpRange, msg, Kind, BasePath);
if (tcr != TC_NotApplicable)
return tcr;
tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
BasePath, msg);
if (tcr != TC_NotApplicable)
return tcr;
tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Kind, ListInitialization);
if (SrcExpr.isInvalid())
return TC_Failed;
if (tcr != TC_NotApplicable)
return tcr;
QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
if (Enum->getDecl()->isScoped()) {
if (DestType->isBooleanType()) {
Kind = CK_IntegralToBoolean;
return TC_Success;
} else if (DestType->isIntegralType(Self.Context)) {
Kind = CK_IntegralCast;
return TC_Success;
} else if (DestType->isRealFloatingType()) {
Kind = CK_IntegralToFloating;
return TC_Success;
}
}
}
if (DestType->isEnumeralType()) {
if (SrcType->isIntegralOrEnumerationType()) {
Kind = CK_IntegralCast;
return TC_Success;
} else if (SrcType->isRealFloatingType()) {
Kind = CK_FloatingToIntegral;
return TC_Success;
}
}
tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Kind, BasePath);
if (tcr != TC_NotApplicable)
return tcr;
tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
OpRange, msg, Kind, BasePath);
if (tcr != TC_NotApplicable)
return tcr;
if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
QualType SrcPointee = SrcPointer->getPointeeType();
if (SrcPointee->isVoidType()) {
if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
QualType DestPointee = DestPointer->getPointeeType();
if (DestPointee->isIncompleteOrObjectType()) {
if (!CStyle) {
Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
DestPointeeQuals.removeObjCGCAttr();
DestPointeeQuals.removeObjCLifetime();
SrcPointeeQuals.removeObjCGCAttr();
SrcPointeeQuals.removeObjCLifetime();
if (DestPointeeQuals != SrcPointeeQuals &&
!DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
}
Kind = CK_BitCast;
return TC_Success;
}
}
else if (DestType->isObjCObjectPointerType()) {
Kind = CK_CPointerToObjCPointerCast;
return TC_Success;
}
else if (CStyle && DestType->isBlockPointerType()) {
Kind = CK_AnyPointerToBlockPointerCast;
return TC_Success;
}
}
}
if (SrcType->isObjCObjectPointerType() &&
DestType->isObjCObjectPointerType()) {
Kind = CK_BitCast;
return TC_Success;
}
return TC_NotApplicable;
}
TryCastResult
TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
unsigned &msg) {
const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
if (!R)
return TC_NotApplicable;
if (!SrcExpr->isGLValue())
return TC_NotApplicable;
bool DerivedToBase;
bool ObjCConversion;
bool ObjCLifetimeConversion;
QualType FromType = SrcExpr->getType();
QualType ToType = R->getPointeeType();
if (CStyle) {
FromType = FromType.getUnqualifiedType();
ToType = ToType.getUnqualifiedType();
}
if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
ToType, FromType,
DerivedToBase, ObjCConversion,
ObjCLifetimeConversion)
< Sema::Ref_Compatible_With_Added_Qualification) {
msg = diag::err_bad_lvalue_to_rvalue_cast;
return TC_Failed;
}
if (DerivedToBase) {
Kind = CK_DerivedToBase;
CXXBasePaths Paths(true, true,
true);
if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
return TC_NotApplicable;
Self.BuildBasePathArray(Paths, BasePath);
} else
Kind = CK_NoOp;
return TC_Success;
}
TryCastResult
TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
bool CStyle, const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath) {
const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
if (!DestReference) {
return TC_NotApplicable;
}
bool RValueRef = DestReference->isRValueReferenceType();
if (!RValueRef && !SrcExpr->isLValue()) {
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
QualType DestPointee = DestReference->getPointeeType();
return TryStaticDowncast(Self,
Self.Context.getCanonicalType(SrcExpr->getType()),
Self.Context.getCanonicalType(DestPointee), CStyle,
OpRange, SrcExpr->getType(), DestType, msg, Kind,
BasePath);
}
TryCastResult
TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
bool CStyle, const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath) {
const PointerType *DestPointer = DestType->getAs<PointerType>();
if (!DestPointer) {
return TC_NotApplicable;
}
const PointerType *SrcPointer = SrcType->getAs<PointerType>();
if (!SrcPointer) {
msg = diag::err_bad_static_cast_pointer_nonpointer;
return TC_NotApplicable;
}
return TryStaticDowncast(Self,
Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
Self.Context.getCanonicalType(DestPointer->getPointeeType()),
CStyle, OpRange, SrcType, DestType, msg, Kind,
BasePath);
}
TryCastResult
TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
QualType OrigDestType, unsigned &msg,
CastKind &Kind, CXXCastPath &BasePath) {
if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
return TC_NotApplicable;
if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
return TC_NotApplicable;
}
CXXBasePaths Paths(true, true,
true);
if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
return TC_NotApplicable;
}
if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
if (!Paths.isRecordingPaths()) {
Paths.clear();
Paths.setRecordingPaths(true);
Self.IsDerivedFrom(DestType, SrcType, Paths);
}
std::string PathDisplayStr;
std::set<unsigned> DisplayedPaths;
for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
PI != PE; ++PI) {
if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
PathDisplayStr += "\n ";
for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
EE = PI->rend();
EI != EE; ++EI)
PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
PathDisplayStr += QualType(DestType).getAsString();
}
}
Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
<< QualType(SrcType).getUnqualifiedType()
<< QualType(DestType).getUnqualifiedType()
<< PathDisplayStr << OpRange;
msg = 0;
return TC_Failed;
}
if (Paths.getDetectedVirtual() != 0) {
QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
<< OrigSrcType << OrigDestType << VirtualBase << OpRange;
msg = 0;
return TC_Failed;
}
if (!CStyle) {
switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
SrcType, DestType,
Paths.front(),
diag::err_downcast_from_inaccessible_base)) {
case Sema::AR_accessible:
case Sema::AR_delayed: case Sema::AR_dependent: break;
case Sema::AR_inaccessible:
msg = 0;
return TC_Failed;
}
}
Self.BuildBasePathArray(Paths, BasePath);
Kind = CK_BaseToDerived;
return TC_Success;
}
TryCastResult
TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg, CastKind &Kind,
CXXCastPath &BasePath) {
const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
if (!DestMemPtr)
return TC_NotApplicable;
bool WasOverloadedFunction = false;
DeclAccessPair FoundOverload;
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
if (FunctionDecl *Fn
= Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
FoundOverload)) {
CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
SrcType = Self.Context.getMemberPointerType(Fn->getType(),
Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
WasOverloadedFunction = true;
}
}
const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
if (!SrcMemPtr) {
msg = diag::err_bad_static_cast_member_pointer_nonmp;
return TC_NotApplicable;
}
if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
DestMemPtr->getPointeeType()))
return TC_NotApplicable;
QualType SrcClass(SrcMemPtr->getClass(), 0);
QualType DestClass(DestMemPtr->getClass(), 0);
CXXBasePaths Paths(true, true,
true);
if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
return TC_NotApplicable;
}
if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Paths.clear();
Paths.setRecordingPaths(true);
bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
assert(StillOkay);
(void)StillOkay;
std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
<< 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
msg = 0;
return TC_Failed;
}
if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
<< SrcClass << DestClass << QualType(VBase, 0) << OpRange;
msg = 0;
return TC_Failed;
}
if (!CStyle) {
switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
DestClass, SrcClass,
Paths.front(),
diag::err_upcast_to_inaccessible_base)) {
case Sema::AR_accessible:
case Sema::AR_delayed:
case Sema::AR_dependent:
break;
case Sema::AR_inaccessible:
msg = 0;
return TC_Failed;
}
}
if (WasOverloadedFunction) {
FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
DestType,
true,
FoundOverload);
if (!Fn) {
msg = 0;
return TC_Failed;
}
SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
if (!SrcExpr.isUsable()) {
msg = 0;
return TC_Failed;
}
}
Self.BuildBasePathArray(Paths, BasePath);
Kind = CK_DerivedToBaseMemberPointer;
return TC_Success;
}
TryCastResult
TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Sema::CheckedConversionKind CCK,
const SourceRange &OpRange, unsigned &msg,
CastKind &Kind, bool ListInitialization) {
if (DestType->isRecordType()) {
if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
diag::err_bad_dynamic_cast_incomplete) ||
Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
diag::err_allocation_of_abstract_type)) {
msg = 0;
return TC_Failed;
}
}
InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
InitializationKind InitKind
= (CCK == Sema::CCK_CStyleCast)
? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
ListInitialization)
: (CCK == Sema::CCK_FunctionalCast)
? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
: InitializationKind::CreateCast(OpRange);
Expr *SrcExprRaw = SrcExpr.get();
InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
bool CStyle
= (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
return TC_NotApplicable;
ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
if (Result.isInvalid()) {
msg = 0;
return TC_Failed;
}
if (InitSeq.isConstructorInitialization())
Kind = CK_ConstructorConversion;
else
Kind = CK_NoOp;
SrcExpr = Result;
return TC_Success;
}
static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
bool CStyle, unsigned &msg) {
DestType = Self.Context.getCanonicalType(DestType);
QualType SrcType = SrcExpr->getType();
if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
SrcType = Self.Context.getPointerType(SrcType);
}
if (!DestType->isPointerType() &&
!DestType->isMemberPointerType() &&
!DestType->isObjCObjectPointerType()) {
if (!CStyle)
msg = diag::err_bad_const_cast_dest;
return TC_NotApplicable;
}
if (DestType->isFunctionPointerType() ||
DestType->isMemberFunctionPointerType()) {
if (!CStyle)
msg = diag::err_bad_const_cast_dest;
return TC_NotApplicable;
}
SrcType = Self.Context.getCanonicalType(SrcType);
while (SrcType != DestType &&
Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Qualifiers SrcQuals, DestQuals;
SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
SrcQuals.removeCVRQualifiers();
DestQuals.removeCVRQualifiers();
if (SrcQuals != DestQuals)
return TC_NotApplicable;
}
if (SrcType != DestType)
return TC_NotApplicable;
return TC_Success;
}
void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference,
SourceRange Range) {
unsigned DiagID = IsDereference ?
diag::warn_pointer_indirection_from_incompatible_type :
diag::warn_undefined_reinterpret_cast;
if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
DiagnosticsEngine::Ignored) {
return;
}
QualType SrcTy, DestTy;
if (IsDereference) {
if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
return;
}
SrcTy = SrcType->getPointeeType();
DestTy = DestType->getPointeeType();
} else {
if (!DestType->getAs<ReferenceType>()) {
return;
}
SrcTy = SrcType;
DestTy = DestType->getPointeeType();
}
if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
return;
}
if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
return;
}
if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
return;
}
if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
(SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
return;
}
}
Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
}
static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
QualType DestType) {
QualType SrcType = SrcExpr.get()->getType();
if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
if (SrcPtrTy->isObjCSelType()) {
QualType DT = DestType;
if (isa<PointerType>(DestType))
DT = DestType->getPointeeType();
if (!DT.getUnqualifiedType()->isVoidType())
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::warn_cast_pointer_from_sel)
<< SrcType << DestType << SrcExpr.get()->getSourceRange();
}
}
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
QualType DestType, bool CStyle,
const SourceRange &OpRange,
unsigned &msg,
CastKind &Kind) {
bool IsLValueCast = false;
DestType = Self.Context.getCanonicalType(DestType);
QualType SrcType = SrcExpr.get()->getType();
if (SrcType == Self.Context.OverloadTy) {
ExprResult SingleFunctionExpr = SrcExpr;
if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
SingleFunctionExpr,
Expr::getValueKindForType(DestType) == VK_RValue ) && SingleFunctionExpr.isUsable()) {
SrcExpr = SingleFunctionExpr;
SrcType = SrcExpr.get()->getType();
} else {
return TC_NotApplicable;
}
}
if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
if (!SrcExpr.get()->isGLValue()) {
msg = diag::err_bad_cxx_cast_rvalue;
return TC_NotApplicable;
}
if (!CStyle) {
Self.CheckCompatibleReinterpretCast(SrcType, DestType,
false, OpRange);
}
const char *inappropriate = 0;
switch (SrcExpr.get()->getObjectKind()) {
case OK_Ordinary:
break;
case OK_BitField: inappropriate = "bit-field"; break;
case OK_VectorComponent: inappropriate = "vector element"; break;
case OK_ObjCProperty: inappropriate = "property expression"; break;
case OK_ObjCSubscript: inappropriate = "container subscripting expression";
break;
}
if (inappropriate) {
Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
<< inappropriate << DestType
<< OpRange << SrcExpr.get()->getSourceRange();
msg = 0; SrcExpr = ExprError();
return TC_NotApplicable;
}
DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
SrcType = Self.Context.getPointerType(SrcType);
IsLValueCast = true;
}
SrcType = Self.Context.getCanonicalType(SrcType);
const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
*SrcMemPtr = SrcType->getAs<MemberPointerType>();
if (DestMemPtr && SrcMemPtr) {
if (DestMemPtr->getPointeeType()->isFunctionType() !=
SrcMemPtr->getPointeeType()->isFunctionType())
return TC_NotApplicable;
if (CastsAwayConstness(Self, SrcType, DestType, !CStyle,
CStyle)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
if (Self.Context.getTypeSize(DestMemPtr) !=
Self.Context.getTypeSize(SrcMemPtr)) {
msg = diag::err_bad_cxx_cast_member_pointer_size;
return TC_Failed;
}
assert(!IsLValueCast);
Kind = CK_ReinterpretMemberPointer;
return TC_Success;
}
if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
if (Self.Context.getTypeSize(SrcType) >
Self.Context.getTypeSize(DestType)) {
msg = diag::err_bad_reinterpret_cast_small_int;
return TC_Failed;
}
Kind = CK_PointerToIntegral;
return TC_Success;
}
bool destIsVector = DestType->isVectorType();
bool srcIsVector = SrcType->isVectorType();
if (srcIsVector || destIsVector) {
bool srcIsScalar = SrcType->isIntegralType(Self.Context);
bool destIsScalar = DestType->isIntegralType(Self.Context);
if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
!(srcIsVector && destIsVector))
return TC_NotApplicable;
if (Self.Context.getTypeSize(SrcType)
== Self.Context.getTypeSize(DestType)) {
Kind = CK_BitCast;
return TC_Success;
}
if (destIsScalar)
msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
else if (srcIsScalar)
msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
else
msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
return TC_Failed;
}
if (SrcType == DestType) {
Kind = CK_NoOp;
TryCastResult Result = TC_NotApplicable;
if (SrcType->isIntegralOrEnumerationType() ||
SrcType->isAnyPointerType() ||
SrcType->isMemberPointerType() ||
SrcType->isBlockPointerType()) {
Result = TC_Success;
}
return Result;
}
bool destIsPtr = DestType->isAnyPointerType() ||
DestType->isBlockPointerType();
bool srcIsPtr = SrcType->isAnyPointerType() ||
SrcType->isBlockPointerType();
if (!destIsPtr && !srcIsPtr) {
return TC_NotApplicable;
}
if (DestType->isIntegralType(Self.Context)) {
assert(srcIsPtr && "One type must be a pointer");
if ((Self.Context.getTypeSize(SrcType) >
Self.Context.getTypeSize(DestType)) &&
!Self.getLangOpts().MicrosoftExt) {
msg = diag::err_bad_reinterpret_cast_small_int;
return TC_Failed;
}
Kind = CK_PointerToIntegral;
return TC_Success;
}
if (SrcType->isIntegralOrEnumerationType()) {
assert(destIsPtr && "One type must be a pointer");
Kind = CK_IntegralToPointer;
return TC_Success;
}
if (!destIsPtr || !srcIsPtr) {
return TC_NotApplicable;
}
if (CastsAwayConstness(Self, SrcType, DestType, !CStyle,
CStyle)) {
msg = diag::err_bad_cxx_cast_qualifiers_away;
return TC_Failed;
}
if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
(DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
return TC_NotApplicable;
if (IsLValueCast) {
Kind = CK_LValueBitCast;
} else if (DestType->isObjCObjectPointerType()) {
Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
} else if (DestType->isBlockPointerType()) {
if (!SrcType->isBlockPointerType()) {
Kind = CK_AnyPointerToBlockPointerCast;
} else {
Kind = CK_BitCast;
}
} else {
Kind = CK_BitCast;
}
if (CStyle && DestType->isObjCObjectPointerType()) {
return TC_Success;
}
if (CStyle)
DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
if (SrcType->isFunctionPointerType()) {
if (DestType->isFunctionPointerType()) {
return TC_Success;
}
Self.Diag(OpRange.getBegin(),
Self.getLangOpts().CPlusPlus0x ?
diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
<< OpRange;
return TC_Success;
}
if (DestType->isFunctionPointerType()) {
Self.Diag(OpRange.getBegin(),
Self.getLangOpts().CPlusPlus0x ?
diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
<< OpRange;
return TC_Success;
}
return TC_Success;
}
void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
bool ListInitialization) {
if (isPlaceholder()) {
if (claimPlaceholder(BuiltinType::UnknownAny)) {
SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
SrcExpr.get(), Kind,
ValueKind, BasePath);
return;
}
checkNonOverloadPlaceholders();
if (SrcExpr.isInvalid())
return;
}
if (DestType->isVoidType()) {
Kind = CK_ToVoid;
if (claimPlaceholder(BuiltinType::Overload)) {
Self.ResolveAndFixSingleFunctionTemplateSpecialization(
SrcExpr, false,
true, DestRange, DestType,
diag::err_bad_cstyle_cast_overload);
if (SrcExpr.isInvalid())
return;
}
SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
if (SrcExpr.isInvalid())
return;
return;
}
if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
assert(Kind == CK_Dependent);
return;
}
if (ValueKind == VK_RValue && !DestType->isRecordType() &&
!isPlaceholder(BuiltinType::Overload)) {
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
if (SrcExpr.isInvalid())
return;
}
if (const VectorType *vecTy = DestType->getAs<VectorType>())
if (vecTy->getVectorKind() == VectorType::AltiVecVector
&& (SrcExpr.get()->getType()->isIntegerType()
|| SrcExpr.get()->getType()->isFloatingType())) {
Kind = CK_VectorSplat;
return;
}
unsigned msg = diag::err_bad_cxx_cast_generic;
TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
true, msg);
if (tcr == TC_Success)
Kind = CK_NoOp;
Sema::CheckedConversionKind CCK
= FunctionalStyle? Sema::CCK_FunctionalCast
: Sema::CCK_CStyleCast;
if (tcr == TC_NotApplicable) {
tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
msg, Kind, BasePath, ListInitialization);
if (SrcExpr.isInvalid())
return;
if (tcr == TC_NotApplicable) {
tcr = TryReinterpretCast(Self, SrcExpr, DestType, true,
OpRange, msg, Kind);
if (SrcExpr.isInvalid())
return;
}
}
if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
checkObjCARCConversion(CCK);
if (tcr != TC_Success && msg != 0) {
if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
DeclAccessPair Found;
FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
DestType,
true,
Found);
assert(!Fn && "cast failed but able to resolve overload expression!!");
(void)Fn;
} else {
diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
OpRange, SrcExpr.get(), DestType, ListInitialization);
}
} else if (Kind == CK_BitCast) {
checkCastAlign();
}
if (tcr != TC_Success)
SrcExpr = ExprError();
}
static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
QualType DestType) {
if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
SrcExpr.get()->getExprLoc())
== DiagnosticsEngine::Ignored)
return;
if (!isa<CallExpr>(SrcExpr.get()))
return;
QualType SrcType = SrcExpr.get()->getType();
if (DestType.getUnqualifiedType()->isVoidType())
return;
if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
&& (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
return;
if (SrcType->isIntegerType() && DestType->isIntegerType() &&
(SrcType->isBooleanType() == DestType->isBooleanType()) &&
(SrcType->isEnumeralType() == DestType->isEnumeralType()))
return;
if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
return;
if (SrcType->isEnumeralType() && DestType->isEnumeralType())
return;
if (SrcType->isComplexType() && DestType->isComplexType())
return;
if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
return;
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::warn_bad_function_cast)
<< SrcType << DestType << SrcExpr.get()->getSourceRange();
}
void CastOperation::CheckCStyleCast() {
assert(!Self.getLangOpts().CPlusPlus);
if (claimPlaceholder(BuiltinType::UnknownAny)) {
SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
SrcExpr.get(), Kind,
ValueKind, BasePath);
return;
}
if (DestType->isVoidType()) {
SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
if (SrcExpr.isInvalid())
return;
Kind = CK_ToVoid;
return;
}
SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
if (SrcExpr.isInvalid())
return;
QualType SrcType = SrcExpr.get()->getType();
assert(!SrcType->isPlaceholderType());
if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
diag::err_typecheck_cast_to_incomplete)) {
SrcExpr = ExprError();
return;
}
if (!DestType->isScalarType() && !DestType->isVectorType()) {
const RecordType *DestRecordTy = DestType->getAs<RecordType>();
if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
<< DestType << SrcExpr.get()->getSourceRange();
Kind = CK_NoOp;
return;
}
if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
RecordDecl *RD = DestRecordTy->getDecl();
RecordDecl::field_iterator Field, FieldEnd;
for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Field != FieldEnd; ++Field) {
if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
!Field->isUnnamedBitfield()) {
Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
<< SrcExpr.get()->getSourceRange();
break;
}
}
if (Field == FieldEnd) {
Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
<< SrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
Kind = CK_ToUnion;
return;
}
Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
<< DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::err_typecheck_expect_scalar_operand)
<< SrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
if (DestType->isExtVectorType()) {
SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
return;
}
if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
(SrcType->isIntegerType() || SrcType->isFloatingType())) {
Kind = CK_VectorSplat;
} else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
SrcExpr = ExprError();
}
return;
}
if (SrcType->isVectorType()) {
if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
SrcExpr = ExprError();
return;
}
if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
SrcExpr = ExprError();
return;
}
if (!DestType->isArithmeticType()) {
if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
Self.Diag(SrcExpr.get()->getExprLoc(),
diag::err_cast_pointer_from_non_pointer_int)
<< SrcType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
} else if (!SrcType->isArithmeticType()) {
if (!DestType->isIntegralType(Self.Context) &&
DestType->isArithmeticType()) {
Self.Diag(SrcExpr.get()->getLocStart(),
diag::err_cast_pointer_to_non_pointer_int)
<< DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
}
if (Self.getLangOpts().ObjCAutoRefCount) {
checkObjCARCConversion(Sema::CCK_CStyleCast);
if (SrcExpr.isInvalid())
return;
if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
ExprPtr->getPointeeType()->isObjCLifetimeType() &&
!CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Self.Diag(SrcExpr.get()->getLocStart(),
diag::err_typecheck_incompatible_ownership)
<< SrcType << DestType << Sema::AA_Casting
<< SrcExpr.get()->getSourceRange();
return;
}
}
}
else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
Self.Diag(SrcExpr.get()->getLocStart(),
diag::err_arc_convesion_of_weak_unavailable)
<< 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
SrcExpr = ExprError();
return;
}
}
DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
Kind = Self.PrepareScalarCast(SrcExpr, DestType);
if (SrcExpr.isInvalid())
return;
if (Kind == CK_BitCast)
checkCastAlign();
}
ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
TypeSourceInfo *CastTypeInfo,
SourceLocation RPLoc,
Expr *CastExpr) {
CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
if (getLangOpts().CPlusPlus) {
Op.CheckCXXCStyleCast( false,
isa<InitListExpr>(CastExpr));
} else {
Op.CheckCStyleCast();
}
if (Op.SrcExpr.isInvalid())
return ExprError();
return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
&Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
}
ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
SourceLocation LPLoc,
Expr *CastExpr,
SourceLocation RPLoc) {
assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
Op.CheckCXXCStyleCast(true, false);
if (Op.SrcExpr.isInvalid())
return ExprError();
if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
}