blob: fc9ef73a590d378f3aa53eaf684181f51fa932fd [file] [log] [blame]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000022using namespace clang;
23
Sebastian Redl9f831db2009-07-25 15:41:38 +000024enum TryCastResult {
25 TC_NotApplicable, ///< The cast method is not applicable.
26 TC_Success, ///< The cast method is appropriate and successful.
27 TC_Failed ///< The cast method is appropriate, but failed. A
28 ///< diagnostic has been emitted.
29};
30
31enum CastType {
32 CT_Const, ///< const_cast
33 CT_Static, ///< static_cast
34 CT_Reinterpret, ///< reinterpret_cast
35 CT_Dynamic, ///< dynamic_cast
36 CT_CStyle, ///< (Type)expr
37 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000038};
39
40static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
41 const SourceRange &OpRange,
42 const SourceRange &DestRange);
43static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
44 const SourceRange &OpRange,
Anders Carlsson7cd39e02009-09-15 04:48:33 +000045 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000046 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000047static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssonf10e4142009-08-07 22:21:05 +000048 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +000049 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000050 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000051static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
52 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000053 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000054 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000055 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000056
57static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-07-25 15:41:38 +000058
59// The Try functions attempt a specific way of casting. If they succeed, they
60// return TC_Success. If their way of casting is not appropriate for the given
61// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
62// to emit if no other way succeeds. If their way of casting is appropriate but
63// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
64// they emit a specialized diagnostic.
65// All diagnostics returned by these functions must expect the same three
66// arguments:
67// %0: Cast Type (a value from the CastType enumeration)
68// %1: Source Type
69// %2: Destination Type
70static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, unsigned &msg);
72static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000073 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
75 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000076 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000077 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +000078static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000081 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000082 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000083 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000084static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
85 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000086 const SourceRange &OpRange,
87 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000088 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000089 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000090 CXXCastPath &BasePath);
Douglas Gregorc934bc82010-03-07 23:24:59 +000091static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +000092 QualType SrcType,
93 QualType DestType,bool CStyle,
94 const SourceRange &OpRange,
95 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000096 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000097 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +000098
Sebastian Redl7c353682009-11-14 21:15:49 +000099static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000102 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000103 CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +0000104static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000105 QualType DestType, bool CStyle,
106 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000107 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000108 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000109 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000110static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
111 bool CStyle, unsigned &msg);
112static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
113 QualType DestType, bool CStyle,
114 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000115 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000116 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000117
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000118/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000119ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000120Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallba7bf592010-08-24 05:47:05 +0000121 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000122 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000123 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000124 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000125
John McCall97513962010-01-15 18:39:57 +0000126 TypeSourceInfo *DestTInfo;
127 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
128 if (!DestTInfo)
129 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000130
131 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
132 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
133 SourceRange(LParenLoc, RParenLoc));
134}
135
John McCalldadc5752010-08-24 06:29:42 +0000136ExprResult
John McCalld377e042010-01-15 19:13:16 +0000137Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallfaf5fb42010-08-26 23:41:50 +0000138 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCalld377e042010-01-15 19:13:16 +0000139 SourceRange AngleBrackets, SourceRange Parens) {
John McCalld377e042010-01-15 19:13:16 +0000140 QualType DestType = DestTInfo->getType();
141
142 SourceRange OpRange(OpLoc, Parens.getEnd());
143 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000144
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000145 // If the type is dependent, we won't do the semantic analysis now.
146 // FIXME: should we check this in a more fine-grained manner?
147 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
148
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +0000149 if (Ex->isBoundMemberFunction(Context))
150 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
151 << Ex->getSourceRange();
152
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000153 switch (Kind) {
154 default: assert(0 && "Unknown C++ cast!");
155
156 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000157 if (!TypeDependent)
158 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
John McCallcf142162010-08-07 06:22:56 +0000159 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000160 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000161 Ex, DestTInfo, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000162
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000163 case tok::kw_dynamic_cast: {
John McCalle3027922010-08-25 11:45:40 +0000164 CastKind Kind = CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000165 CXXCastPath BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000166 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000167 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
John McCallcf142162010-08-07 06:22:56 +0000168 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000169 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000170 Kind, Ex, &BasePath, DestTInfo,
171 OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000172 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000173 case tok::kw_reinterpret_cast: {
John McCalle3027922010-08-25 11:45:40 +0000174 CastKind Kind = CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000175 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000176 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
John McCallcf142162010-08-07 06:22:56 +0000177 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000178 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000179 Kind, Ex, 0,
Anders Carlssona70cff62010-04-24 19:06:50 +0000180 DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000181 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000182 case tok::kw_static_cast: {
John McCalle3027922010-08-25 11:45:40 +0000183 CastKind Kind = CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000184 CXXCastPath BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000185 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000186 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000187
John McCallcf142162010-08-07 06:22:56 +0000188 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000189 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000190 Kind, Ex, &BasePath,
191 DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000192 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000193 }
194
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000195 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000196}
197
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000198/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
199/// this removes one level of indirection from both types, provided that they're
200/// the same kind of pointer (plain or to-member). Unlike the Sema function,
201/// this one doesn't care if the two pointers-to-member don't point into the
202/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000203static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000204 const PointerType *T1PtrType = T1->getAs<PointerType>(),
205 *T2PtrType = T2->getAs<PointerType>();
206 if (T1PtrType && T2PtrType) {
207 T1 = T1PtrType->getPointeeType();
208 T2 = T2PtrType->getPointeeType();
209 return true;
210 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000211 const ObjCObjectPointerType *T1ObjCPtrType =
212 T1->getAs<ObjCObjectPointerType>(),
213 *T2ObjCPtrType =
214 T2->getAs<ObjCObjectPointerType>();
215 if (T1ObjCPtrType) {
216 if (T2ObjCPtrType) {
217 T1 = T1ObjCPtrType->getPointeeType();
218 T2 = T2ObjCPtrType->getPointeeType();
219 return true;
220 }
221 else if (T2PtrType) {
222 T1 = T1ObjCPtrType->getPointeeType();
223 T2 = T2PtrType->getPointeeType();
224 return true;
225 }
226 }
227 else if (T2ObjCPtrType) {
228 if (T1PtrType) {
229 T2 = T2ObjCPtrType->getPointeeType();
230 T1 = T1PtrType->getPointeeType();
231 return true;
232 }
233 }
234
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000235 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
236 *T2MPType = T2->getAs<MemberPointerType>();
237 if (T1MPType && T2MPType) {
238 T1 = T1MPType->getPointeeType();
239 T2 = T2MPType->getPointeeType();
240 return true;
241 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000242
243 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
244 *T2BPType = T2->getAs<BlockPointerType>();
245 if (T1BPType && T2BPType) {
246 T1 = T1BPType->getPointeeType();
247 T2 = T2BPType->getPointeeType();
248 return true;
249 }
250
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000251 return false;
252}
253
Sebastian Redla5a77a62009-01-27 23:18:31 +0000254/// CastsAwayConstness - Check if the pointer conversion from SrcType to
255/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
256/// the cast checkers. Both arguments must denote pointer (possibly to member)
257/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000258static bool
Mike Stump11289f42009-09-09 15:08:12 +0000259CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000260 // Casting away constness is defined in C++ 5.2.11p8 with reference to
261 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
262 // the rules are non-trivial. So first we construct Tcv *...cv* as described
263 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000264 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
265 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000266 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000267 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
268 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000269 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000270
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000271 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
272 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000273 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000274
275 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000276 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000277 Qualifiers SrcQuals;
278 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
279 cv1.push_back(SrcQuals);
280
281 Qualifiers DestQuals;
282 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
283 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000284 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000285 if (cv1.empty())
286 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000287
288 // Construct void pointers with those qualifiers (in reverse order of
289 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000290 QualType SrcConstruct = Self.Context.VoidTy;
291 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000292 ASTContext &Context = Self.Context;
293 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
294 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000295 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000296 SrcConstruct
297 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
298 DestConstruct
299 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000300 }
301
302 // Test if they're compatible.
303 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000304 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000305}
306
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000307/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
308/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
309/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000310static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000311CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
312 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000313 const SourceRange &DestRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000314 CXXCastPath &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000315 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000316 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000317
318 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
319 // or "pointer to cv void".
320
321 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000322 const PointerType *DestPointer = DestType->getAs<PointerType>();
323 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000324 if (DestPointer) {
325 DestPointee = DestPointer->getPointeeType();
326 } else if (DestReference) {
327 DestPointee = DestReference->getPointeeType();
328 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000329 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000330 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000331 return;
332 }
333
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000334 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000335 if (DestPointee->isVoidType()) {
336 assert(DestPointer && "Reference to void is not possible");
337 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000338 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000339 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000340 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000341 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000342 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000343 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000344 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000345 return;
346 }
347
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000348 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
349 // complete class type, [...]. If T is an lvalue reference type, v shall be
350 // an lvalue of a complete class type, [...]. If T is an rvalue reference
351 // type, v shall be an expression having a complete effective class type,
352 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000353
Sebastian Redl842ef522008-11-08 13:00:26 +0000354 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000355 QualType SrcPointee;
356 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000357 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000358 SrcPointee = SrcPointer->getPointeeType();
359 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000360 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000361 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000362 return;
363 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000364 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000365 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000366 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000367 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000368 }
369 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000370 } else {
371 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000372 }
373
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000374 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000375 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000376 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000377 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000378 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000379 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000380 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000381 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000382 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000383 return;
384 }
385
386 assert((DestPointer || DestReference) &&
387 "Bad destination non-ptr/ref slipped through.");
388 assert((DestRecord || DestPointee->isVoidType()) &&
389 "Bad destination pointee slipped through.");
390 assert(SrcRecord && "Bad source pointee slipped through.");
391
392 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
393 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000394 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000395 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000396 return;
397 }
398
399 // C++ 5.2.7p3: If the type of v is the same as the required result type,
400 // [except for cv].
401 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000402 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000403 return;
404 }
405
406 // C++ 5.2.7p5
407 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000408 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000409 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
410 OpRange.getBegin(), OpRange,
411 &BasePath))
412 return;
413
John McCalle3027922010-08-25 11:45:40 +0000414 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000415
416 // If we are casting to or through a virtual base class, we need a
417 // vtable.
418 if (Self.BasePathInvolvesVirtualBase(BasePath))
419 Self.MarkVTableUsed(OpRange.getBegin(),
420 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000421 return;
422 }
423
424 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000425 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000426 assert(SrcDecl && "Definition missing");
427 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000428 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000429 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000430 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000431 Self.MarkVTableUsed(OpRange.getBegin(),
432 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000433
434 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000435 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000436}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000437
438/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
439/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
440/// like this:
441/// const char *str = "literal";
442/// legacy_function(const_cast\<char*\>(str));
443void
444CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000445 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000446 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000447 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000448
449 unsigned msg = diag::err_bad_cxx_cast_generic;
450 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
451 && msg != 0)
452 Self.Diag(OpRange.getBegin(), msg) << CT_Const
453 << SrcExpr->getType() << DestType << OpRange;
454}
455
456/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
457/// valid.
458/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
459/// like this:
460/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
461void
462CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000463 const SourceRange &OpRange, const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +0000464 CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000465 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000466 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000467
468 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000469 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
470 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000471 != TC_Success && msg != 0)
472 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
473 << SrcExpr->getType() << DestType << OpRange;
474}
475
476
477/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
478/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
479/// implicit conversions explicit and getting rid of data loss warnings.
480void
481CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCalle3027922010-08-25 11:45:40 +0000482 const SourceRange &OpRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000483 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000484 // This test is outside everything else because it's the only case where
485 // a non-lvalue-reference target type does not lead to decay.
486 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000487 if (DestType->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +0000488 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000489 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000490 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000491
Douglas Gregorad8b2222009-11-06 01:14:41 +0000492 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000493 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000494
495 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000496 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000497 Kind, BasePath) != TC_Success && msg != 0)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000498 Self.Diag(OpRange.getBegin(), msg) << CT_Static
499 << SrcExpr->getType() << DestType << OpRange;
John McCalle3027922010-08-25 11:45:40 +0000500 else if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +0000501 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000502}
503
504/// TryStaticCast - Check if a static cast can be performed, and do so if
505/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
506/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000507static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000508 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000509 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000510 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000511 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000512 // The order the tests is not entirely arbitrary. There is one conversion
513 // that can be handled in two different ways. Given:
514 // struct A {};
515 // struct B : public A {
516 // B(); B(const A&);
517 // };
518 // const A &a = B();
519 // the cast static_cast<const B&>(a) could be seen as either a static
520 // reference downcast, or an explicit invocation of the user-defined
521 // conversion using B's conversion constructor.
522 // DR 427 specifies that the downcast is to be applied here.
523
524 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
525 // Done outside this function.
526
527 TryCastResult tcr;
528
529 // C++ 5.2.9p5, reference downcast.
530 // See the function for details.
531 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000532 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000533 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000534 if (tcr != TC_NotApplicable)
535 return tcr;
536
537 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
538 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
539 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000540 if (tcr != TC_NotApplicable) {
John McCalle3027922010-08-25 11:45:40 +0000541 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000542 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000543 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000544
545 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
546 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000547 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000548 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000549 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000550 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000551
Sebastian Redl9f831db2009-07-25 15:41:38 +0000552 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
553 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
554 // conversions, subject to further restrictions.
555 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
556 // of qualification conversions impossible.
557 // In the CStyle case, the earlier attempt to const_cast should have taken
558 // care of reverse qualification conversions.
559
560 QualType OrigSrcType = SrcExpr->getType();
561
562 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
563
Douglas Gregor0bf31402010-10-08 23:50:27 +0000564 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
565 // converted to an integral type.
566 if (Self.getLangOptions().CPlusPlus0x && SrcType->isEnumeralType()) {
567 if (DestType->isIntegralType(Self.Context)) {
568 Kind = CK_IntegralCast;
569 return TC_Success;
570 }
571 }
572
Sebastian Redl9f831db2009-07-25 15:41:38 +0000573 // Reverse integral promotion/conversion. All such conversions are themselves
574 // again integral promotions or conversions and are thus already handled by
575 // p2 (TryDirectInitialization above).
576 // (Note: any data loss warnings should be suppressed.)
577 // The exception is the reverse of enum->integer, i.e. integer->enum (and
578 // enum->enum). See also C++ 5.2.9p7.
579 // The same goes for reverse floating point promotion/conversion and
580 // floating-integral conversions. Again, only floating->enum is relevant.
581 if (DestType->isEnumeralType()) {
582 if (SrcType->isComplexType() || SrcType->isVectorType()) {
583 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000584 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCalle3027922010-08-25 11:45:40 +0000585 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000586 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000587 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000588 }
589
590 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
591 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000592 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000593 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000594 if (tcr != TC_NotApplicable)
595 return tcr;
596
597 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
598 // conversion. C++ 5.2.9p9 has additional information.
599 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000600 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000601 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000602 if (tcr != TC_NotApplicable)
603 return tcr;
604
605 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
606 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
607 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000608 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000609 QualType SrcPointee = SrcPointer->getPointeeType();
610 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000611 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000612 QualType DestPointee = DestPointer->getPointeeType();
613 if (DestPointee->isIncompleteOrObjectType()) {
614 // This is definitely the intended conversion, but it might fail due
615 // to a const violation.
616 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
617 msg = diag::err_bad_cxx_cast_const_away;
618 return TC_Failed;
619 }
John McCalle3027922010-08-25 11:45:40 +0000620 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000621 return TC_Success;
622 }
623 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000624 else if (DestType->isObjCObjectPointerType()) {
625 // allow both c-style cast and static_cast of objective-c pointers as
626 // they are pervasive.
John McCalle3027922010-08-25 11:45:40 +0000627 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000628 return TC_Success;
629 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000630 else if (CStyle && DestType->isBlockPointerType()) {
631 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000632 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000633 return TC_Success;
634 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000635 }
636 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000637 // Allow arbitray objective-c pointer conversion with static casts.
638 if (SrcType->isObjCObjectPointerType() &&
639 DestType->isObjCObjectPointerType())
640 return TC_Success;
641
Sebastian Redl9f831db2009-07-25 15:41:38 +0000642 // We tried everything. Everything! Nothing works! :-(
643 return TC_NotApplicable;
644}
645
646/// Tests whether a conversion according to N2844 is valid.
647TryCastResult
648TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000649 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000650 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
651 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000652 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000653 if (!R)
654 return TC_NotApplicable;
655
656 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
657 return TC_NotApplicable;
658
659 // Because we try the reference downcast before this function, from now on
660 // this is the only cast possibility, so we issue an error if we fail now.
661 // FIXME: Should allow casting away constness if CStyle.
662 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000663 bool ObjCConversion;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000664 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
665 SrcExpr->getType(), R->getPointeeType(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000666 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000667 Sema::Ref_Compatible_With_Added_Qualification) {
668 msg = diag::err_bad_lvalue_to_rvalue_cast;
669 return TC_Failed;
670 }
671
Douglas Gregor031296e2010-03-25 00:20:38 +0000672 // FIXME: We should probably have an AST node for lvalue-to-rvalue
673 // conversions.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000674 return TC_Success;
675}
676
677/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
678TryCastResult
679TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
680 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000681 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000682 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000683 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
684 // cast to type "reference to cv2 D", where D is a class derived from B,
685 // if a valid standard conversion from "pointer to D" to "pointer to B"
686 // exists, cv2 >= cv1, and B is not a virtual base class of D.
687 // In addition, DR54 clarifies that the base must be accessible in the
688 // current context. Although the wording of DR54 only applies to the pointer
689 // variant of this rule, the intent is clearly for it to apply to the this
690 // conversion as well.
691
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000692 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000693 if (!DestReference) {
694 return TC_NotApplicable;
695 }
696 bool RValueRef = DestReference->isRValueReferenceType();
697 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
698 // We know the left side is an lvalue reference, so we can suggest a reason.
699 msg = diag::err_bad_cxx_cast_rvalue;
700 return TC_NotApplicable;
701 }
702
703 QualType DestPointee = DestReference->getPointeeType();
704
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000705 return TryStaticDowncast(Self,
706 Self.Context.getCanonicalType(SrcExpr->getType()),
707 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000708 OpRange, SrcExpr->getType(), DestType, msg, Kind,
709 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000710}
711
712/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
713TryCastResult
714TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000715 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000716 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000717 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000718 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
719 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
720 // is a class derived from B, if a valid standard conversion from "pointer
721 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
722 // class of D.
723 // In addition, DR54 clarifies that the base must be accessible in the
724 // current context.
725
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000726 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000727 if (!DestPointer) {
728 return TC_NotApplicable;
729 }
730
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000731 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000732 if (!SrcPointer) {
733 msg = diag::err_bad_static_cast_pointer_nonpointer;
734 return TC_NotApplicable;
735 }
736
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000737 return TryStaticDowncast(Self,
738 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
739 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000740 CStyle, OpRange, SrcType, DestType, msg, Kind,
741 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000742}
743
744/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
745/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000746/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000747TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000748TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000749 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000750 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000751 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000752 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000753 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
754 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000755 return TC_NotApplicable;
756
Sebastian Redl9f831db2009-07-25 15:41:38 +0000757 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000758 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000759 return TC_NotApplicable;
760 }
761
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000762 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000763 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000764 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
765 return TC_NotApplicable;
766 }
767
768 // Target type does derive from source type. Now we're serious. If an error
769 // appears now, it's not ignored.
770 // This may not be entirely in line with the standard. Take for example:
771 // struct A {};
772 // struct B : virtual A {
773 // B(A&);
774 // };
Mike Stump11289f42009-09-09 15:08:12 +0000775 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000776 // void f()
777 // {
778 // (void)static_cast<const B&>(*((A*)0));
779 // }
780 // As far as the standard is concerned, p5 does not apply (A is virtual), so
781 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
782 // However, both GCC and Comeau reject this example, and accepting it would
783 // mean more complex code if we're to preserve the nice error message.
784 // FIXME: Being 100% compliant here would be nice to have.
785
786 // Must preserve cv, as always, unless we're in C-style mode.
787 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
788 msg = diag::err_bad_cxx_cast_const_away;
789 return TC_Failed;
790 }
791
792 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
793 // This code is analoguous to that in CheckDerivedToBaseConversion, except
794 // that it builds the paths in reverse order.
795 // To sum up: record all paths to the base and build a nice string from
796 // them. Use it to spice up the error message.
797 if (!Paths.isRecordingPaths()) {
798 Paths.clear();
799 Paths.setRecordingPaths(true);
800 Self.IsDerivedFrom(DestType, SrcType, Paths);
801 }
802 std::string PathDisplayStr;
803 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000804 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000805 PI != PE; ++PI) {
806 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
807 // We haven't displayed a path to this particular base
808 // class subobject yet.
809 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000810 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
811 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000812 EI != EE; ++EI)
813 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000814 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000815 }
816 }
817
818 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000819 << QualType(SrcType).getUnqualifiedType()
820 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000821 << PathDisplayStr << OpRange;
822 msg = 0;
823 return TC_Failed;
824 }
825
826 if (Paths.getDetectedVirtual() != 0) {
827 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
828 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
829 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
830 msg = 0;
831 return TC_Failed;
832 }
833
John McCall5b0829a2010-02-10 09:31:12 +0000834 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000835 SrcType, DestType,
John McCall1064d7e2010-03-16 05:22:47 +0000836 Paths.front(),
837 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000838 msg = 0;
839 return TC_Failed;
840 }
841
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000842 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +0000843 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000844 return TC_Success;
845}
846
847/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
848/// C++ 5.2.9p9 is valid:
849///
850/// An rvalue of type "pointer to member of D of type cv1 T" can be
851/// converted to an rvalue of type "pointer to member of B of type cv2 T",
852/// where B is a base class of D [...].
853///
854TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +0000855TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
856 QualType DestType, bool CStyle,
857 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000858 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000859 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000860 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000861 if (!DestMemPtr)
862 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +0000863
864 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +0000865 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +0000866 if (SrcExpr->getType() == Self.Context.OverloadTy) {
867 if (FunctionDecl *Fn
868 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
869 FoundOverload)) {
870 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
871 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
872 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
873 WasOverloadedFunction = true;
874 }
Douglas Gregorc934bc82010-03-07 23:24:59 +0000875 }
Douglas Gregor064fdb22010-04-14 23:11:21 +0000876
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000877 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000878 if (!SrcMemPtr) {
879 msg = diag::err_bad_static_cast_member_pointer_nonmp;
880 return TC_NotApplicable;
881 }
882
883 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000884 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
885 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000886 return TC_NotApplicable;
887
888 // B base of D
889 QualType SrcClass(SrcMemPtr->getClass(), 0);
890 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000891 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000892 /*DetectVirtual=*/true);
893 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
894 return TC_NotApplicable;
895 }
896
897 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +0000898 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000899 Paths.clear();
900 Paths.setRecordingPaths(true);
901 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
902 assert(StillOkay);
903 StillOkay = StillOkay;
904 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
905 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
906 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
907 msg = 0;
908 return TC_Failed;
909 }
910
911 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
912 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
913 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
914 msg = 0;
915 return TC_Failed;
916 }
917
John McCall5b0829a2010-02-10 09:31:12 +0000918 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedmand4c75cd2010-07-23 19:25:41 +0000919 DestClass, SrcClass,
John McCall1064d7e2010-03-16 05:22:47 +0000920 Paths.front(),
921 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000922 msg = 0;
923 return TC_Failed;
924 }
925
Douglas Gregorc934bc82010-03-07 23:24:59 +0000926 if (WasOverloadedFunction) {
927 // Resolve the address of the overloaded function again, this time
928 // allowing complaints if something goes wrong.
929 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
930 DestType,
John McCall16df1e52010-03-30 21:47:33 +0000931 true,
932 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000933 if (!Fn) {
934 msg = 0;
935 return TC_Failed;
936 }
937
John McCall16df1e52010-03-30 21:47:33 +0000938 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000939 if (!SrcExpr) {
940 msg = 0;
941 return TC_Failed;
942 }
943 }
944
Anders Carlssonb78feca2010-04-24 19:22:20 +0000945 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +0000946 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000947 return TC_Success;
948}
949
950/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
951/// is valid:
952///
953/// An expression e can be explicitly converted to a type T using a
954/// @c static_cast if the declaration "T t(e);" is well-formed [...].
955TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000956TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000957 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000958 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000959 if (DestType->isRecordType()) {
960 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
961 diag::err_bad_dynamic_cast_incomplete)) {
962 msg = 0;
963 return TC_Failed;
964 }
965 }
Douglas Gregorb33eed02010-04-16 22:09:46 +0000966
967 // At this point of CheckStaticCast, if the destination is a reference,
968 // this has to work. There is no other way that works.
969 // On the other hand, if we're checking a C-style cast, we've still got
970 // the reinterpret_cast way.
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000971 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
972 InitializationKind InitKind
Douglas Gregorb33eed02010-04-16 22:09:46 +0000973 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
974 CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000975 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregorb33eed02010-04-16 22:09:46 +0000976 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
977 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000978 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000979
John McCalldadc5752010-08-24 06:29:42 +0000980 ExprResult Result
John McCallfaf5fb42010-08-26 23:41:50 +0000981 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000982 if (Result.isInvalid()) {
983 msg = 0;
984 return TC_Failed;
985 }
986
Douglas Gregorb33eed02010-04-16 22:09:46 +0000987 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +0000988 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000989 else
John McCalle3027922010-08-25 11:45:40 +0000990 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000991
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000992 SrcExpr = Result.takeAs<Expr>();
993 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994}
995
996/// TryConstCast - See if a const_cast from source to destination is allowed,
997/// and perform it if it is.
998static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
999 bool CStyle, unsigned &msg) {
1000 DestType = Self.Context.getCanonicalType(DestType);
1001 QualType SrcType = SrcExpr->getType();
1002 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001003 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001004 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1005 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1006 // is C-style, static_cast might find a way, so we simply suggest a
1007 // message and tell the parent to keep searching.
1008 msg = diag::err_bad_cxx_cast_rvalue;
1009 return TC_NotApplicable;
1010 }
1011
1012 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1013 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1014 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1015 SrcType = Self.Context.getPointerType(SrcType);
1016 }
1017
1018 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1019 // the rules for const_cast are the same as those used for pointers.
1020
John McCall0e704f72010-05-18 09:35:29 +00001021 if (!DestType->isPointerType() &&
1022 !DestType->isMemberPointerType() &&
1023 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001024 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1025 // was a reference type, we converted it to a pointer above.
1026 // The status of rvalue references isn't entirely clear, but it looks like
1027 // conversion to them is simply invalid.
1028 // C++ 5.2.11p3: For two pointer types [...]
1029 if (!CStyle)
1030 msg = diag::err_bad_const_cast_dest;
1031 return TC_NotApplicable;
1032 }
1033 if (DestType->isFunctionPointerType() ||
1034 DestType->isMemberFunctionPointerType()) {
1035 // Cannot cast direct function pointers.
1036 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1037 // T is the ultimate pointee of source and target type.
1038 if (!CStyle)
1039 msg = diag::err_bad_const_cast_dest;
1040 return TC_NotApplicable;
1041 }
1042 SrcType = Self.Context.getCanonicalType(SrcType);
1043
1044 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1045 // completely equal.
1046 // FIXME: const_cast should probably not be able to convert between pointers
1047 // to different address spaces.
1048 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1049 // in multi-level pointers may change, but the level count must be the same,
1050 // as must be the final pointee type.
1051 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001052 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001053 Qualifiers Quals;
1054 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1055 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001056 }
1057
1058 // Since we're dealing in canonical types, the remainder must be the same.
1059 if (SrcType != DestType)
1060 return TC_NotApplicable;
1061
1062 return TC_Success;
1063}
1064
1065static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1066 QualType DestType, bool CStyle,
1067 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001068 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001069 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001070 bool IsLValueCast = false;
1071
Sebastian Redl9f831db2009-07-25 15:41:38 +00001072 DestType = Self.Context.getCanonicalType(DestType);
1073 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001074 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001075 bool LValue = DestTypeTmp->isLValueReferenceType();
1076 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1077 // Cannot cast non-lvalue to reference type. See the similar comment in
1078 // const_cast.
1079 msg = diag::err_bad_cxx_cast_rvalue;
1080 return TC_NotApplicable;
1081 }
1082
1083 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1084 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1085 // built-in & and * operators.
1086 // This code does this transformation for the checked types.
1087 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1088 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor51954272010-07-13 23:17:26 +00001089 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001090 }
1091
1092 // Canonicalize source for comparison.
1093 SrcType = Self.Context.getCanonicalType(SrcType);
1094
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001095 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1096 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001097 if (DestMemPtr && SrcMemPtr) {
1098 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1099 // can be explicitly converted to an rvalue of type "pointer to member
1100 // of Y of type T2" if T1 and T2 are both function types or both object
1101 // types.
1102 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1103 SrcMemPtr->getPointeeType()->isFunctionType())
1104 return TC_NotApplicable;
1105
1106 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1107 // constness.
1108 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1109 // we accept it.
1110 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1111 msg = diag::err_bad_cxx_cast_const_away;
1112 return TC_Failed;
1113 }
1114
Charles Davisebab1ed2010-08-16 05:30:44 +00001115 // Don't allow casting between member pointers of different sizes.
1116 if (Self.Context.getTypeSize(DestMemPtr) !=
1117 Self.Context.getTypeSize(SrcMemPtr)) {
1118 msg = diag::err_bad_cxx_cast_member_pointer_size;
1119 return TC_Failed;
1120 }
1121
Sebastian Redl9f831db2009-07-25 15:41:38 +00001122 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001123 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001124 return TC_Success;
1125 }
1126
1127 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001128 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001129 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1130 // type large enough to hold it. A value of std::nullptr_t can be
1131 // converted to an integral type; the conversion has the same meaning
1132 // and validity as a conversion of (void*)0 to the integral type.
1133 if (Self.Context.getTypeSize(SrcType) >
1134 Self.Context.getTypeSize(DestType)) {
1135 msg = diag::err_bad_reinterpret_cast_small_int;
1136 return TC_Failed;
1137 }
John McCalle3027922010-08-25 11:45:40 +00001138 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001139 return TC_Success;
1140 }
1141
Anders Carlsson570af5d2009-09-16 19:19:43 +00001142 bool destIsVector = DestType->isVectorType();
1143 bool srcIsVector = SrcType->isVectorType();
1144 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001145 // FIXME: Should this also apply to floating point types?
1146 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1147 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001148
1149 // Check if this is a cast between a vector and something else.
1150 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1151 !(srcIsVector && destIsVector))
1152 return TC_NotApplicable;
1153
1154 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001155 if (Self.Context.getTypeSize(SrcType)
1156 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001157 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001158 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001159 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001160
1161 if (destIsScalar)
1162 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1163 else if (srcIsScalar)
1164 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1165 else
1166 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1167
1168 return TC_Failed;
1169 }
1170
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001171 bool destIsPtr = DestType->isAnyPointerType() ||
1172 DestType->isBlockPointerType();
1173 bool srcIsPtr = SrcType->isAnyPointerType() ||
1174 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001175 if (!destIsPtr && !srcIsPtr) {
1176 // Except for std::nullptr_t->integer and lvalue->reference, which are
1177 // handled above, at least one of the two arguments must be a pointer.
1178 return TC_NotApplicable;
1179 }
1180
1181 if (SrcType == DestType) {
1182 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1183 // restrictions, a cast to the same type is allowed. The intent is not
1184 // entirely clear here, since all other paragraphs explicitly forbid casts
1185 // to the same type. However, the behavior of compilers is pretty consistent
1186 // on this point: allow same-type conversion if the involved types are
1187 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001188 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001189 return TC_Success;
1190 }
1191
Douglas Gregor6972a622010-06-16 00:35:25 +00001192 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001193 assert(srcIsPtr && "One type must be a pointer");
1194 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1195 // type large enough to hold it.
1196 if (Self.Context.getTypeSize(SrcType) >
1197 Self.Context.getTypeSize(DestType)) {
1198 msg = diag::err_bad_reinterpret_cast_small_int;
1199 return TC_Failed;
1200 }
John McCalle3027922010-08-25 11:45:40 +00001201 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001202 return TC_Success;
1203 }
1204
Douglas Gregorb90df602010-06-16 00:17:44 +00001205 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001206 assert(destIsPtr && "One type must be a pointer");
1207 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1208 // converted to a pointer.
John McCalle3027922010-08-25 11:45:40 +00001209 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001210 return TC_Success;
1211 }
1212
1213 if (!destIsPtr || !srcIsPtr) {
1214 // With the valid non-pointer conversions out of the way, we can be even
1215 // more stringent.
1216 return TC_NotApplicable;
1217 }
1218
1219 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1220 // The C-style cast operator can.
1221 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1222 msg = diag::err_bad_cxx_cast_const_away;
1223 return TC_Failed;
1224 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001225
1226 // Cannot convert between block pointers and Objective-C object pointers.
1227 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1228 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1229 return TC_NotApplicable;
1230
1231 // Any pointer can be cast to an Objective-C pointer type with a C-style
1232 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001233 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001234 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001235 return TC_Success;
1236 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001237
Sebastian Redl9f831db2009-07-25 15:41:38 +00001238 // Not casting away constness, so the only remaining check is for compatible
1239 // pointer categories.
John McCalle3027922010-08-25 11:45:40 +00001240 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001241
1242 if (SrcType->isFunctionPointerType()) {
1243 if (DestType->isFunctionPointerType()) {
1244 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1245 // a pointer to a function of a different type.
1246 return TC_Success;
1247 }
1248
1249 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1250 // an object type or vice versa is conditionally-supported.
1251 // Compilers support it in C++03 too, though, because it's necessary for
1252 // casting the return value of dlsym() and GetProcAddress().
1253 // FIXME: Conditionally-supported behavior should be configurable in the
1254 // TargetInfo or similar.
1255 if (!Self.getLangOptions().CPlusPlus0x)
1256 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1257 return TC_Success;
1258 }
1259
1260 if (DestType->isFunctionPointerType()) {
1261 // See above.
1262 if (!Self.getLangOptions().CPlusPlus0x)
1263 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1264 return TC_Success;
1265 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001266
Sebastian Redl9f831db2009-07-25 15:41:38 +00001267 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1268 // a pointer to an object of different type.
1269 // Void pointers are not specified, but supported by every compiler out there.
1270 // So we finish by allowing everything that remains - it's got to be two
1271 // object pointers.
1272 return TC_Success;
1273}
1274
Anders Carlssona70cff62010-04-24 19:06:50 +00001275bool
1276Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00001277 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001278 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001279 bool FunctionalStyle) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001280 if (CastExpr->isBoundMemberFunction(Context))
1281 return Diag(CastExpr->getLocStart(),
1282 diag::err_invalid_use_of_bound_member_func)
1283 << CastExpr->getSourceRange();
1284
Sebastian Redl9f831db2009-07-25 15:41:38 +00001285 // This test is outside everything else because it's the only case where
1286 // a non-lvalue-reference target type does not lead to decay.
1287 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001288 if (CastTy->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00001289 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001290 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001291 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001292
1293 // If the type is dependent, we won't do any other semantic analysis now.
1294 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1295 return false;
1296
Douglas Gregorad8b2222009-11-06 01:14:41 +00001297 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001298 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001299
1300 // C++ [expr.cast]p5: The conversions performed by
1301 // - a const_cast,
1302 // - a static_cast,
1303 // - a static_cast followed by a const_cast,
1304 // - a reinterpret_cast, or
1305 // - a reinterpret_cast followed by a const_cast,
1306 // can be performed using the cast notation of explicit type conversion.
1307 // [...] If a conversion can be interpreted in more than one of the ways
1308 // listed above, the interpretation that appears first in the list is used,
1309 // even if a cast resulting from that interpretation is ill-formed.
1310 // In plain language, this means trying a const_cast ...
1311 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001312 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1313 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001314 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001315 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001316
Sebastian Redl9f831db2009-07-25 15:41:38 +00001317 if (tcr == TC_NotApplicable) {
1318 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001319 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1320 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001321 if (tcr == TC_NotApplicable) {
1322 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001323 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1324 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001325 }
1326 }
1327
Sebastian Redl9f831db2009-07-25 15:41:38 +00001328 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001329 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001330 << CastExpr->getType() << CastTy << R;
John McCalle3027922010-08-25 11:45:40 +00001331 else if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00001332 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001333
1334 return tcr != TC_Success;
1335}