blob: 989be96d218b601d889cf2f8fd1226d20a2c2a94 [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
Douglas Gregore81f58e2010-11-08 03:40:48 +000024
Douglas Gregore81f58e2010-11-08 03:40:48 +000025
Sebastian Redl9f831db2009-07-25 15:41:38 +000026enum TryCastResult {
27 TC_NotApplicable, ///< The cast method is not applicable.
28 TC_Success, ///< The cast method is appropriate and successful.
29 TC_Failed ///< The cast method is appropriate, but failed. A
30 ///< diagnostic has been emitted.
31};
32
33enum CastType {
34 CT_Const, ///< const_cast
35 CT_Static, ///< static_cast
36 CT_Reinterpret, ///< reinterpret_cast
37 CT_Dynamic, ///< dynamic_cast
38 CT_CStyle, ///< (Type)expr
39 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000040};
41
Douglas Gregore81f58e2010-11-08 03:40:48 +000042
43
44
John Wiegley01296292011-04-08 18:41:53 +000045static void CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000046 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000047 const SourceRange &OpRange,
48 const SourceRange &DestRange);
John Wiegley01296292011-04-08 18:41:53 +000049static void CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000050 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000051 const SourceRange &OpRange,
Anders Carlsson7cd39e02009-09-15 04:48:33 +000052 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000053 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +000054static void CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000055 ExprValueKind &VK,
Anders Carlssonf10e4142009-08-07 22:21:05 +000056 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +000057 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000058 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +000059static void CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000060 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000061 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000062 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000063 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000064 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000065
66static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-07-25 15:41:38 +000067
68// The Try functions attempt a specific way of casting. If they succeed, they
69// return TC_Success. If their way of casting is not appropriate for the given
70// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
71// to emit if no other way succeeds. If their way of casting is appropriate but
72// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
73// they emit a specialized diagnostic.
74// All diagnostics returned by these functions must expect the same three
75// arguments:
76// %0: Cast Type (a value from the CastType enumeration)
77// %1: Source Type
78// %2: Destination Type
79static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +000080 QualType DestType, bool CStyle,
81 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +000082 CXXCastPath &BasePath,
83 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +000084static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000085 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
87 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000088 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000089 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +000090static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
91 QualType DestType, bool CStyle,
92 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000093 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000094 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000095 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000096static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
97 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000098 const SourceRange &OpRange,
99 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000100 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000101 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000102 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000103static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000104 QualType SrcType,
105 QualType DestType,bool CStyle,
106 const SourceRange &OpRange,
107 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000108 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000109 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000110
John Wiegley01296292011-04-08 18:41:53 +0000111static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000112 QualType DestType, bool CStyle,
113 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000114 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000115 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +0000116static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000117 QualType DestType, bool CStyle,
118 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000119 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000120 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000121 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000122static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
123 bool CStyle, unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000124static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000125 QualType DestType, bool CStyle,
126 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000127 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000128 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000129
Douglas Gregorb491ed32011-02-19 21:32:49 +0000130
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000131/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000132ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000133Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallba7bf592010-08-24 05:47:05 +0000134 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000135 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000136 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000137 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000138
John McCall97513962010-01-15 18:39:57 +0000139 TypeSourceInfo *DestTInfo;
140 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
141 if (!DestTInfo)
142 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000143
144 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
145 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
146 SourceRange(LParenLoc, RParenLoc));
147}
148
John McCalldadc5752010-08-24 06:29:42 +0000149ExprResult
John McCalld377e042010-01-15 19:13:16 +0000150Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000151 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000152 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000153 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000154 QualType DestType = DestTInfo->getType();
155
156 SourceRange OpRange(OpLoc, Parens.getEnd());
157 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000158
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000159 // If the type is dependent, we won't do the semantic analysis now.
160 // FIXME: should we check this in a more fine-grained manner?
John Wiegley01296292011-04-08 18:41:53 +0000161 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000162
John Wiegley01296292011-04-08 18:41:53 +0000163 if (Ex.get()->isBoundMemberFunction(Context))
164 Diag(Ex.get()->getLocStart(), diag::err_invalid_use_of_bound_member_func)
165 << Ex.get()->getSourceRange();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +0000166
John McCall7decc9e2010-11-18 06:31:45 +0000167 ExprValueKind VK = VK_RValue;
John McCall29ac8e22010-11-26 10:57:22 +0000168 if (TypeDependent)
169 VK = Expr::getValueKindForType(DestType);
170
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000171 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000172 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000173
174 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000175 if (!TypeDependent) {
John McCall7decc9e2010-11-18 06:31:45 +0000176 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John Wiegley01296292011-04-08 18:41:53 +0000177 if (Ex.isInvalid())
178 return ExprError();
179 }
John McCallcf142162010-08-07 06:22:56 +0000180 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000181 DestType.getNonLValueExprType(Context),
John Wiegley01296292011-04-08 18:41:53 +0000182 VK, Ex.take(), DestTInfo, OpLoc,
Douglas Gregor4478f852011-01-12 22:41:29 +0000183 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000184
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000185 case tok::kw_dynamic_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000186 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000187 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +0000188 if (!TypeDependent) {
John McCall7decc9e2010-11-18 06:31:45 +0000189 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
190 Kind, BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000191 if (Ex.isInvalid())
192 return ExprError();
193 }
John McCallcf142162010-08-07 06:22:56 +0000194 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000195 DestType.getNonLValueExprType(Context),
John Wiegley01296292011-04-08 18:41:53 +0000196 VK, Kind, Ex.take(), &BasePath, DestTInfo,
Douglas Gregor4478f852011-01-12 22:41:29 +0000197 OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000198 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000199 case tok::kw_reinterpret_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000200 CastKind Kind = CK_Dependent;
John Wiegley01296292011-04-08 18:41:53 +0000201 if (!TypeDependent) {
John McCall7decc9e2010-11-18 06:31:45 +0000202 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John Wiegley01296292011-04-08 18:41:53 +0000203 if (Ex.isInvalid())
204 return ExprError();
205 }
John McCallcf142162010-08-07 06:22:56 +0000206 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000207 DestType.getNonLValueExprType(Context),
John Wiegley01296292011-04-08 18:41:53 +0000208 VK, Kind, Ex.take(), 0,
Douglas Gregor4478f852011-01-12 22:41:29 +0000209 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000210 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000211 case tok::kw_static_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000212 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000213 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +0000214 if (!TypeDependent) {
John McCall7decc9e2010-11-18 06:31:45 +0000215 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000216 if (Ex.isInvalid())
217 return ExprError();
218 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000219
John McCallcf142162010-08-07 06:22:56 +0000220 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000221 DestType.getNonLValueExprType(Context),
John Wiegley01296292011-04-08 18:41:53 +0000222 VK, Kind, Ex.take(), &BasePath,
Douglas Gregor4478f852011-01-12 22:41:29 +0000223 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000224 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000225 }
226
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000227 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000228}
229
John McCall909acf82011-02-14 18:34:10 +0000230/// Try to diagnose a failed overloaded cast. Returns true if
231/// diagnostics were emitted.
232static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
233 SourceRange range, Expr *src,
234 QualType destType) {
235 switch (CT) {
236 // These cast kinds don't consider user-defined conversions.
237 case CT_Const:
238 case CT_Reinterpret:
239 case CT_Dynamic:
240 return false;
241
242 // These do.
243 case CT_Static:
244 case CT_CStyle:
245 case CT_Functional:
246 break;
247 }
248
249 QualType srcType = src->getType();
250 if (!destType->isRecordType() && !srcType->isRecordType())
251 return false;
252
253 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
254 InitializationKind initKind
255 = InitializationKind::CreateCast(/*type range?*/ range,
256 (CT == CT_CStyle || CT == CT_Functional));
257 InitializationSequence sequence(S, entity, initKind, &src, 1);
258
259 assert(sequence.getKind() == InitializationSequence::FailedSequence &&
260 "initialization succeeded on second try?");
261 switch (sequence.getFailureKind()) {
262 default: return false;
263
264 case InitializationSequence::FK_ConstructorOverloadFailed:
265 case InitializationSequence::FK_UserConversionOverloadFailed:
266 break;
267 }
268
269 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
270
271 unsigned msg = 0;
272 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
273
274 switch (sequence.getFailedOverloadResult()) {
275 case OR_Success: llvm_unreachable("successful failed overload");
276 return false;
277 case OR_No_Viable_Function:
278 if (candidates.empty())
279 msg = diag::err_ovl_no_conversion_in_cast;
280 else
281 msg = diag::err_ovl_no_viable_conversion_in_cast;
282 howManyCandidates = OCD_AllCandidates;
283 break;
284
285 case OR_Ambiguous:
286 msg = diag::err_ovl_ambiguous_conversion_in_cast;
287 howManyCandidates = OCD_ViableCandidates;
288 break;
289
290 case OR_Deleted:
291 msg = diag::err_ovl_deleted_conversion_in_cast;
292 howManyCandidates = OCD_ViableCandidates;
293 break;
294 }
295
296 S.Diag(range.getBegin(), msg)
297 << CT << srcType << destType
298 << range << src->getSourceRange();
299
300 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
301
302 return true;
303}
304
305/// Diagnose a failed cast.
306static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
307 SourceRange opRange, Expr *src, QualType destType) {
308 if (msg == diag::err_bad_cxx_cast_generic &&
309 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
310 return;
311
312 S.Diag(opRange.getBegin(), msg) << castType
313 << src->getType() << destType << opRange << src->getSourceRange();
314}
315
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000316/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
317/// this removes one level of indirection from both types, provided that they're
318/// the same kind of pointer (plain or to-member). Unlike the Sema function,
319/// this one doesn't care if the two pointers-to-member don't point into the
320/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000321static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000322 const PointerType *T1PtrType = T1->getAs<PointerType>(),
323 *T2PtrType = T2->getAs<PointerType>();
324 if (T1PtrType && T2PtrType) {
325 T1 = T1PtrType->getPointeeType();
326 T2 = T2PtrType->getPointeeType();
327 return true;
328 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000329 const ObjCObjectPointerType *T1ObjCPtrType =
330 T1->getAs<ObjCObjectPointerType>(),
331 *T2ObjCPtrType =
332 T2->getAs<ObjCObjectPointerType>();
333 if (T1ObjCPtrType) {
334 if (T2ObjCPtrType) {
335 T1 = T1ObjCPtrType->getPointeeType();
336 T2 = T2ObjCPtrType->getPointeeType();
337 return true;
338 }
339 else if (T2PtrType) {
340 T1 = T1ObjCPtrType->getPointeeType();
341 T2 = T2PtrType->getPointeeType();
342 return true;
343 }
344 }
345 else if (T2ObjCPtrType) {
346 if (T1PtrType) {
347 T2 = T2ObjCPtrType->getPointeeType();
348 T1 = T1PtrType->getPointeeType();
349 return true;
350 }
351 }
352
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000353 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
354 *T2MPType = T2->getAs<MemberPointerType>();
355 if (T1MPType && T2MPType) {
356 T1 = T1MPType->getPointeeType();
357 T2 = T2MPType->getPointeeType();
358 return true;
359 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000360
361 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
362 *T2BPType = T2->getAs<BlockPointerType>();
363 if (T1BPType && T2BPType) {
364 T1 = T1BPType->getPointeeType();
365 T2 = T2BPType->getPointeeType();
366 return true;
367 }
368
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000369 return false;
370}
371
Sebastian Redla5a77a62009-01-27 23:18:31 +0000372/// CastsAwayConstness - Check if the pointer conversion from SrcType to
373/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
374/// the cast checkers. Both arguments must denote pointer (possibly to member)
375/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000376static bool
Mike Stump11289f42009-09-09 15:08:12 +0000377CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000378 // Casting away constness is defined in C++ 5.2.11p8 with reference to
379 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
380 // the rules are non-trivial. So first we construct Tcv *...cv* as described
381 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000382 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
383 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000384 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000385 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
386 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000387 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000388
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000389 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
390 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000391 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000392
393 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000394 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000395 Qualifiers SrcQuals;
396 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
397 cv1.push_back(SrcQuals);
398
399 Qualifiers DestQuals;
400 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
401 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000402 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000403 if (cv1.empty())
404 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000405
406 // Construct void pointers with those qualifiers (in reverse order of
407 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000408 QualType SrcConstruct = Self.Context.VoidTy;
409 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000410 ASTContext &Context = Self.Context;
411 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
412 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000413 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000414 SrcConstruct
415 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
416 DestConstruct
417 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000418 }
419
420 // Test if they're compatible.
421 return SrcConstruct != DestConstruct &&
Douglas Gregor58281352011-01-27 00:58:17 +0000422 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000423}
424
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000425/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
426/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
427/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000428static void
John Wiegley01296292011-04-08 18:41:53 +0000429CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000430 ExprValueKind &VK, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000431 const SourceRange &DestRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000432 CXXCastPath &BasePath) {
John Wiegley01296292011-04-08 18:41:53 +0000433 QualType OrigDestType = DestType, OrigSrcType = SrcExpr.get()->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000434 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000435
436 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
437 // or "pointer to cv void".
438
439 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000440 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000441 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000442 if (DestPointer) {
443 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000444 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000445 DestPointee = DestReference->getPointeeType();
Douglas Gregor465184a2011-01-22 00:06:57 +0000446 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
447 : isa<RValueReferenceType>(DestReference) ? VK_XValue
448 : VK_RValue;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000449 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000450 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000451 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000452 return;
453 }
454
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000455 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000456 if (DestPointee->isVoidType()) {
457 assert(DestPointer && "Reference to void is not possible");
458 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000459 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000460 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000461 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000462 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000463 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000464 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000465 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000466 return;
467 }
468
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000469 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
470 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000471 // an lvalue of a complete class type, [...]. If T is an rvalue reference
472 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000473 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000474 QualType SrcPointee;
475 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000476 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000477 SrcPointee = SrcPointer->getPointeeType();
478 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000479 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000480 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000481 return;
482 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000483 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000484 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000485 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000486 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000487 }
488 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000489 } else {
490 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000491 }
492
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000493 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000494 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000495 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000496 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley01296292011-04-08 18:41:53 +0000497 << SrcExpr.get()->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000498 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000499 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000500 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000501 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000502 return;
503 }
504
505 assert((DestPointer || DestReference) &&
506 "Bad destination non-ptr/ref slipped through.");
507 assert((DestRecord || DestPointee->isVoidType()) &&
508 "Bad destination pointee slipped through.");
509 assert(SrcRecord && "Bad source pointee slipped through.");
510
511 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
512 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000513 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000514 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000515 return;
516 }
517
518 // C++ 5.2.7p3: If the type of v is the same as the required result type,
519 // [except for cv].
520 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000521 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000522 return;
523 }
524
525 // C++ 5.2.7p5
526 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000527 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000528 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
529 OpRange.getBegin(), OpRange,
530 &BasePath))
531 return;
532
John McCalle3027922010-08-25 11:45:40 +0000533 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000534
535 // If we are casting to or through a virtual base class, we need a
536 // vtable.
537 if (Self.BasePathInvolvesVirtualBase(BasePath))
538 Self.MarkVTableUsed(OpRange.getBegin(),
539 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000540 return;
541 }
542
543 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000544 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000545 assert(SrcDecl && "Definition missing");
546 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000547 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000548 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000549 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000550 Self.MarkVTableUsed(OpRange.getBegin(),
551 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000552
553 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000554 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000555}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000556
557/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
558/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
559/// like this:
560/// const char *str = "literal";
561/// legacy_function(const_cast\<char*\>(str));
562void
John Wiegley01296292011-04-08 18:41:53 +0000563CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump11289f42009-09-09 15:08:12 +0000564 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCall7decc9e2010-11-18 06:31:45 +0000565 VK = Expr::getValueKindForType(DestType);
John Wiegley01296292011-04-08 18:41:53 +0000566 if (VK == VK_RValue) {
567 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
568 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
569 return;
570 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000571
572 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley01296292011-04-08 18:41:53 +0000573 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9f831db2009-07-25 15:41:38 +0000574 && msg != 0)
575 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000576 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000577}
578
579/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
580/// valid.
581/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
582/// like this:
583/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
584void
John Wiegley01296292011-04-08 18:41:53 +0000585CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000586 ExprValueKind &VK, const SourceRange &OpRange,
587 const SourceRange &DestRange, CastKind &Kind) {
588 VK = Expr::getValueKindForType(DestType);
John Wiegley01296292011-04-08 18:41:53 +0000589 if (VK == VK_RValue) {
590 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
591 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
592 return;
593 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000594
595 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000596 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
597 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000598 != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000599 {
John Wiegley01296292011-04-08 18:41:53 +0000600 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
601 return;
602 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000603 //FIXME: &f<int>; is overloaded and resolvable
604 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000605 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000606 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000607 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000608
John McCall909acf82011-02-14 18:34:10 +0000609 } else {
John Wiegley01296292011-04-08 18:41:53 +0000610 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000611 }
John McCall909acf82011-02-14 18:34:10 +0000612 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000613}
614
615
616/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
617/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
618/// implicit conversions explicit and getting rid of data loss warnings.
619void
John Wiegley01296292011-04-08 18:41:53 +0000620CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000621 ExprValueKind &VK, const SourceRange &OpRange,
622 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000623 // This test is outside everything else because it's the only case where
624 // a non-lvalue-reference target type does not lead to decay.
625 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000626 if (DestType->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +0000627 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
628 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
629 return;
630 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregorb491ed32011-02-19 21:32:49 +0000631 ExprResult SingleFunctionExpression =
John Wiegley01296292011-04-08 18:41:53 +0000632 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +0000633 false, // Decay Function to ptr
634 true, // Complain
635 OpRange, DestType, diag::err_bad_static_cast_overload);
636 if (SingleFunctionExpression.isUsable())
637 {
John Wiegley01296292011-04-08 18:41:53 +0000638 SrcExpr = SingleFunctionExpression;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000639 Kind = CK_ToVoid;
640 }
641 }
642 else
643 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000644 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000645 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000646
John McCall7decc9e2010-11-18 06:31:45 +0000647 VK = Expr::getValueKindForType(DestType);
John Wiegley01296292011-04-08 18:41:53 +0000648 if (VK == VK_RValue && !DestType->isRecordType()) {
649 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
650 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
651 return;
652 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000653
654 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000655 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000656 Kind, BasePath) != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000657 if (SrcExpr.isInvalid())
658 return;
659 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
660 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000661 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000662 << oe->getName() << DestType << OpRange
663 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000664 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000665 } else {
John Wiegley01296292011-04-08 18:41:53 +0000666 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000667 }
Douglas Gregore81f58e2010-11-08 03:40:48 +0000668 }
John McCalld50a2712010-11-16 05:46:29 +0000669 else if (Kind == CK_BitCast)
John Wiegley01296292011-04-08 18:41:53 +0000670 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000671}
672
673/// TryStaticCast - Check if a static cast can be performed, and do so if
674/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
675/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000676static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000677 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000678 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000679 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000680 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000681 // The order the tests is not entirely arbitrary. There is one conversion
682 // that can be handled in two different ways. Given:
683 // struct A {};
684 // struct B : public A {
685 // B(); B(const A&);
686 // };
687 // const A &a = B();
688 // the cast static_cast<const B&>(a) could be seen as either a static
689 // reference downcast, or an explicit invocation of the user-defined
690 // conversion using B's conversion constructor.
691 // DR 427 specifies that the downcast is to be applied here.
692
693 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
694 // Done outside this function.
695
696 TryCastResult tcr;
697
698 // C++ 5.2.9p5, reference downcast.
699 // See the function for details.
700 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley01296292011-04-08 18:41:53 +0000701 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000702 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000703 if (tcr != TC_NotApplicable)
704 return tcr;
705
Douglas Gregor465184a2011-01-22 00:06:57 +0000706 // C++0x [expr.static.cast]p3:
707 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
708 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley01296292011-04-08 18:41:53 +0000709 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregorce950842011-01-26 21:04:06 +0000710 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000711 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000712 return tcr;
713
714 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
715 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000716 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000717 Kind);
John Wiegley01296292011-04-08 18:41:53 +0000718 if (SrcExpr.isInvalid())
719 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000720 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000721 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000722
Sebastian Redl9f831db2009-07-25 15:41:38 +0000723 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
724 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
725 // conversions, subject to further restrictions.
726 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
727 // of qualification conversions impossible.
728 // In the CStyle case, the earlier attempt to const_cast should have taken
729 // care of reverse qualification conversions.
730
John Wiegley01296292011-04-08 18:41:53 +0000731 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000732
Douglas Gregor0bf31402010-10-08 23:50:27 +0000733 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000734 // converted to an integral type. [...] A value of a scoped enumeration type
735 // can also be explicitly converted to a floating-point type [...].
736 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
737 if (Enum->getDecl()->isScoped()) {
738 if (DestType->isBooleanType()) {
739 Kind = CK_IntegralToBoolean;
740 return TC_Success;
741 } else if (DestType->isIntegralType(Self.Context)) {
742 Kind = CK_IntegralCast;
743 return TC_Success;
744 } else if (DestType->isRealFloatingType()) {
745 Kind = CK_IntegralToFloating;
746 return TC_Success;
747 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000748 }
749 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000750
Sebastian Redl9f831db2009-07-25 15:41:38 +0000751 // Reverse integral promotion/conversion. All such conversions are themselves
752 // again integral promotions or conversions and are thus already handled by
753 // p2 (TryDirectInitialization above).
754 // (Note: any data loss warnings should be suppressed.)
755 // The exception is the reverse of enum->integer, i.e. integer->enum (and
756 // enum->enum). See also C++ 5.2.9p7.
757 // The same goes for reverse floating point promotion/conversion and
758 // floating-integral conversions. Again, only floating->enum is relevant.
759 if (DestType->isEnumeralType()) {
760 if (SrcType->isComplexType() || SrcType->isVectorType()) {
761 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000762 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCalle3027922010-08-25 11:45:40 +0000763 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000764 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000765 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000766 }
767
768 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
769 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000770 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000771 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000772 if (tcr != TC_NotApplicable)
773 return tcr;
774
775 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
776 // conversion. C++ 5.2.9p9 has additional information.
777 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000778 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000779 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000780 if (tcr != TC_NotApplicable)
781 return tcr;
782
783 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
784 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
785 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000786 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000787 QualType SrcPointee = SrcPointer->getPointeeType();
788 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000789 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000790 QualType DestPointee = DestPointer->getPointeeType();
791 if (DestPointee->isIncompleteOrObjectType()) {
792 // This is definitely the intended conversion, but it might fail due
793 // to a const violation.
794 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
795 msg = diag::err_bad_cxx_cast_const_away;
796 return TC_Failed;
797 }
John McCalle3027922010-08-25 11:45:40 +0000798 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000799 return TC_Success;
800 }
801 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000802 else if (DestType->isObjCObjectPointerType()) {
803 // allow both c-style cast and static_cast of objective-c pointers as
804 // they are pervasive.
John McCalle3027922010-08-25 11:45:40 +0000805 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000806 return TC_Success;
807 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000808 else if (CStyle && DestType->isBlockPointerType()) {
809 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000810 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000811 return TC_Success;
812 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000813 }
814 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000815 // Allow arbitray objective-c pointer conversion with static casts.
816 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000817 DestType->isObjCObjectPointerType()) {
818 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000819 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000820 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000821
Sebastian Redl9f831db2009-07-25 15:41:38 +0000822 // We tried everything. Everything! Nothing works! :-(
823 return TC_NotApplicable;
824}
825
826/// Tests whether a conversion according to N2844 is valid.
827TryCastResult
828TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000829 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
830 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000831 // C++0x [expr.static.cast]p3:
832 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
833 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000834 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000835 if (!R)
836 return TC_NotApplicable;
837
Douglas Gregor465184a2011-01-22 00:06:57 +0000838 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000839 return TC_NotApplicable;
840
841 // Because we try the reference downcast before this function, from now on
842 // this is the only cast possibility, so we issue an error if we fail now.
843 // FIXME: Should allow casting away constness if CStyle.
844 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000845 bool ObjCConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000846 QualType FromType = SrcExpr->getType();
847 QualType ToType = R->getPointeeType();
848 if (CStyle) {
849 FromType = FromType.getUnqualifiedType();
850 ToType = ToType.getUnqualifiedType();
851 }
852
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000853 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000854 ToType, FromType,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000855 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000856 Sema::Ref_Compatible_With_Added_Qualification) {
857 msg = diag::err_bad_lvalue_to_rvalue_cast;
858 return TC_Failed;
859 }
860
Douglas Gregorba278e22011-01-25 16:13:26 +0000861 if (DerivedToBase) {
862 Kind = CK_DerivedToBase;
863 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
864 /*DetectVirtual=*/true);
865 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
866 return TC_NotApplicable;
867
868 Self.BuildBasePathArray(Paths, BasePath);
869 } else
870 Kind = CK_NoOp;
871
Sebastian Redl9f831db2009-07-25 15:41:38 +0000872 return TC_Success;
873}
874
875/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
876TryCastResult
877TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
878 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000879 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000880 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000881 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
882 // cast to type "reference to cv2 D", where D is a class derived from B,
883 // if a valid standard conversion from "pointer to D" to "pointer to B"
884 // exists, cv2 >= cv1, and B is not a virtual base class of D.
885 // In addition, DR54 clarifies that the base must be accessible in the
886 // current context. Although the wording of DR54 only applies to the pointer
887 // variant of this rule, the intent is clearly for it to apply to the this
888 // conversion as well.
889
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000890 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000891 if (!DestReference) {
892 return TC_NotApplicable;
893 }
894 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000895 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000896 // We know the left side is an lvalue reference, so we can suggest a reason.
897 msg = diag::err_bad_cxx_cast_rvalue;
898 return TC_NotApplicable;
899 }
900
901 QualType DestPointee = DestReference->getPointeeType();
902
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000903 return TryStaticDowncast(Self,
904 Self.Context.getCanonicalType(SrcExpr->getType()),
905 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000906 OpRange, SrcExpr->getType(), DestType, msg, Kind,
907 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000908}
909
910/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
911TryCastResult
912TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000913 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000914 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000915 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000916 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
917 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
918 // is a class derived from B, if a valid standard conversion from "pointer
919 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
920 // class of D.
921 // In addition, DR54 clarifies that the base must be accessible in the
922 // current context.
923
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000924 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000925 if (!DestPointer) {
926 return TC_NotApplicable;
927 }
928
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000930 if (!SrcPointer) {
931 msg = diag::err_bad_static_cast_pointer_nonpointer;
932 return TC_NotApplicable;
933 }
934
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000935 return TryStaticDowncast(Self,
936 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
937 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000938 CStyle, OpRange, SrcType, DestType, msg, Kind,
939 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000940}
941
942/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
943/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000944/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000945TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000946TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000947 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000948 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000949 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000950 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000951 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
952 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000953 return TC_NotApplicable;
954
Sebastian Redl9f831db2009-07-25 15:41:38 +0000955 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000956 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000957 return TC_NotApplicable;
958 }
959
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000960 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000961 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000962 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
963 return TC_NotApplicable;
964 }
965
966 // Target type does derive from source type. Now we're serious. If an error
967 // appears now, it's not ignored.
968 // This may not be entirely in line with the standard. Take for example:
969 // struct A {};
970 // struct B : virtual A {
971 // B(A&);
972 // };
Mike Stump11289f42009-09-09 15:08:12 +0000973 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000974 // void f()
975 // {
976 // (void)static_cast<const B&>(*((A*)0));
977 // }
978 // As far as the standard is concerned, p5 does not apply (A is virtual), so
979 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
980 // However, both GCC and Comeau reject this example, and accepting it would
981 // mean more complex code if we're to preserve the nice error message.
982 // FIXME: Being 100% compliant here would be nice to have.
983
984 // Must preserve cv, as always, unless we're in C-style mode.
985 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
986 msg = diag::err_bad_cxx_cast_const_away;
987 return TC_Failed;
988 }
989
990 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
991 // This code is analoguous to that in CheckDerivedToBaseConversion, except
992 // that it builds the paths in reverse order.
993 // To sum up: record all paths to the base and build a nice string from
994 // them. Use it to spice up the error message.
995 if (!Paths.isRecordingPaths()) {
996 Paths.clear();
997 Paths.setRecordingPaths(true);
998 Self.IsDerivedFrom(DestType, SrcType, Paths);
999 }
1000 std::string PathDisplayStr;
1001 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001002 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001003 PI != PE; ++PI) {
1004 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1005 // We haven't displayed a path to this particular base
1006 // class subobject yet.
1007 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001008 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1009 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001010 EI != EE; ++EI)
1011 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001012 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001013 }
1014 }
1015
1016 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001017 << QualType(SrcType).getUnqualifiedType()
1018 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001019 << PathDisplayStr << OpRange;
1020 msg = 0;
1021 return TC_Failed;
1022 }
1023
1024 if (Paths.getDetectedVirtual() != 0) {
1025 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1026 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1027 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1028 msg = 0;
1029 return TC_Failed;
1030 }
1031
John McCallfe9cf0a2011-02-14 23:21:33 +00001032 if (!CStyle) {
1033 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1034 SrcType, DestType,
1035 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001036 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001037 case Sema::AR_accessible:
1038 case Sema::AR_delayed: // be optimistic
1039 case Sema::AR_dependent: // be optimistic
1040 break;
1041
1042 case Sema::AR_inaccessible:
1043 msg = 0;
1044 return TC_Failed;
1045 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001046 }
1047
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001048 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001049 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001050 return TC_Success;
1051}
1052
1053/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1054/// C++ 5.2.9p9 is valid:
1055///
1056/// An rvalue of type "pointer to member of D of type cv1 T" can be
1057/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1058/// where B is a base class of D [...].
1059///
1060TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001061TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001062 QualType DestType, bool CStyle,
1063 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001064 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001065 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001066 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001067 if (!DestMemPtr)
1068 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001069
1070 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001071 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001072 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001073 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001074 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001075 FoundOverload)) {
1076 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1077 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1078 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1079 WasOverloadedFunction = true;
1080 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001081 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001082
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001083 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001084 if (!SrcMemPtr) {
1085 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1086 return TC_NotApplicable;
1087 }
1088
1089 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001090 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1091 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001092 return TC_NotApplicable;
1093
1094 // B base of D
1095 QualType SrcClass(SrcMemPtr->getClass(), 0);
1096 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001097 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001098 /*DetectVirtual=*/true);
1099 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1100 return TC_NotApplicable;
1101 }
1102
1103 // 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 +00001104 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001105 Paths.clear();
1106 Paths.setRecordingPaths(true);
1107 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1108 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001109 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001110 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1111 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1112 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1113 msg = 0;
1114 return TC_Failed;
1115 }
1116
1117 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1118 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1119 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1120 msg = 0;
1121 return TC_Failed;
1122 }
1123
John McCallfe9cf0a2011-02-14 23:21:33 +00001124 if (!CStyle) {
1125 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1126 DestClass, SrcClass,
1127 Paths.front(),
1128 diag::err_upcast_to_inaccessible_base)) {
1129 case Sema::AR_accessible:
1130 case Sema::AR_delayed:
1131 case Sema::AR_dependent:
1132 // Optimistically assume that the delayed and dependent cases
1133 // will work out.
1134 break;
1135
1136 case Sema::AR_inaccessible:
1137 msg = 0;
1138 return TC_Failed;
1139 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001140 }
1141
Douglas Gregorc934bc82010-03-07 23:24:59 +00001142 if (WasOverloadedFunction) {
1143 // Resolve the address of the overloaded function again, this time
1144 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001145 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001146 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001147 true,
1148 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001149 if (!Fn) {
1150 msg = 0;
1151 return TC_Failed;
1152 }
1153
John McCall16df1e52010-03-30 21:47:33 +00001154 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001155 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001156 msg = 0;
1157 return TC_Failed;
1158 }
1159 }
1160
Anders Carlssonb78feca2010-04-24 19:22:20 +00001161 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001162 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001163 return TC_Success;
1164}
1165
1166/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1167/// is valid:
1168///
1169/// An expression e can be explicitly converted to a type T using a
1170/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1171TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001172TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001173 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001174 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001175 if (DestType->isRecordType()) {
1176 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1177 diag::err_bad_dynamic_cast_incomplete)) {
1178 msg = 0;
1179 return TC_Failed;
1180 }
1181 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001182
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001183 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1184 InitializationKind InitKind
Douglas Gregor58281352011-01-27 00:58:17 +00001185 = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);
John Wiegley01296292011-04-08 18:41:53 +00001186 Expr *SrcExprRaw = SrcExpr.get();
1187 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001188
1189 // At this point of CheckStaticCast, if the destination is a reference,
1190 // or the expression is an overload expression this has to work.
1191 // There is no other way that works.
1192 // On the other hand, if we're checking a C-style cast, we've still got
1193 // the reinterpret_cast way.
1194
Douglas Gregorb33eed02010-04-16 22:09:46 +00001195 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregore81f58e2010-11-08 03:40:48 +00001196 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001197 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001198
John McCalldadc5752010-08-24 06:29:42 +00001199 ExprResult Result
John Wiegley01296292011-04-08 18:41:53 +00001200 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001201 if (Result.isInvalid()) {
1202 msg = 0;
1203 return TC_Failed;
1204 }
1205
Douglas Gregorb33eed02010-04-16 22:09:46 +00001206 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001207 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001208 else
John McCalle3027922010-08-25 11:45:40 +00001209 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001210
John Wiegley01296292011-04-08 18:41:53 +00001211 SrcExpr = move(Result);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001212 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001213}
1214
1215/// TryConstCast - See if a const_cast from source to destination is allowed,
1216/// and perform it if it is.
1217static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1218 bool CStyle, unsigned &msg) {
1219 DestType = Self.Context.getCanonicalType(DestType);
1220 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001221 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1222 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001223 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1224 // is C-style, static_cast might find a way, so we simply suggest a
1225 // message and tell the parent to keep searching.
1226 msg = diag::err_bad_cxx_cast_rvalue;
1227 return TC_NotApplicable;
1228 }
1229
1230 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1231 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1232 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1233 SrcType = Self.Context.getPointerType(SrcType);
1234 }
1235
1236 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1237 // the rules for const_cast are the same as those used for pointers.
1238
John McCall0e704f72010-05-18 09:35:29 +00001239 if (!DestType->isPointerType() &&
1240 !DestType->isMemberPointerType() &&
1241 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001242 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1243 // was a reference type, we converted it to a pointer above.
1244 // The status of rvalue references isn't entirely clear, but it looks like
1245 // conversion to them is simply invalid.
1246 // C++ 5.2.11p3: For two pointer types [...]
1247 if (!CStyle)
1248 msg = diag::err_bad_const_cast_dest;
1249 return TC_NotApplicable;
1250 }
1251 if (DestType->isFunctionPointerType() ||
1252 DestType->isMemberFunctionPointerType()) {
1253 // Cannot cast direct function pointers.
1254 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1255 // T is the ultimate pointee of source and target type.
1256 if (!CStyle)
1257 msg = diag::err_bad_const_cast_dest;
1258 return TC_NotApplicable;
1259 }
1260 SrcType = Self.Context.getCanonicalType(SrcType);
1261
1262 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1263 // completely equal.
1264 // FIXME: const_cast should probably not be able to convert between pointers
1265 // to different address spaces.
1266 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1267 // in multi-level pointers may change, but the level count must be the same,
1268 // as must be the final pointee type.
1269 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001270 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001271 Qualifiers Quals;
1272 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1273 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001274 }
1275
1276 // Since we're dealing in canonical types, the remainder must be the same.
1277 if (SrcType != DestType)
1278 return TC_NotApplicable;
1279
1280 return TC_Success;
1281}
1282
Douglas Gregor1beec452011-03-12 01:48:56 +00001283
John Wiegley01296292011-04-08 18:41:53 +00001284static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001285 QualType DestType, bool CStyle,
1286 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001287 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001288 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001289 bool IsLValueCast = false;
1290
Sebastian Redl9f831db2009-07-25 15:41:38 +00001291 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001292 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001293
1294 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001295 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1296 if (SrcType == Self.Context.OverloadTy) {
1297 // ... unless foo<int> resolves to an lvalue unambiguously
1298 ExprResult SingleFunctionExpr =
John Wiegley01296292011-04-08 18:41:53 +00001299 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +00001300 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1301 );
1302 if (SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001303 SrcExpr = move(SingleFunctionExpr);
1304 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001305 }
1306 else
1307 return TC_NotApplicable;
1308 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001309
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001310 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001311 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00001312 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001313 // Cannot cast non-lvalue to lvalue reference type. See the similar
1314 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001315 msg = diag::err_bad_cxx_cast_rvalue;
1316 return TC_NotApplicable;
1317 }
1318
1319 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1320 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1321 // built-in & and * operators.
1322 // This code does this transformation for the checked types.
1323 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1324 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001325
Douglas Gregor51954272010-07-13 23:17:26 +00001326 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001327 }
1328
1329 // Canonicalize source for comparison.
1330 SrcType = Self.Context.getCanonicalType(SrcType);
1331
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001332 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1333 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001334 if (DestMemPtr && SrcMemPtr) {
1335 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1336 // can be explicitly converted to an rvalue of type "pointer to member
1337 // of Y of type T2" if T1 and T2 are both function types or both object
1338 // types.
1339 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1340 SrcMemPtr->getPointeeType()->isFunctionType())
1341 return TC_NotApplicable;
1342
1343 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1344 // constness.
1345 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1346 // we accept it.
1347 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1348 msg = diag::err_bad_cxx_cast_const_away;
1349 return TC_Failed;
1350 }
1351
Charles Davisebab1ed2010-08-16 05:30:44 +00001352 // Don't allow casting between member pointers of different sizes.
1353 if (Self.Context.getTypeSize(DestMemPtr) !=
1354 Self.Context.getTypeSize(SrcMemPtr)) {
1355 msg = diag::err_bad_cxx_cast_member_pointer_size;
1356 return TC_Failed;
1357 }
1358
Sebastian Redl9f831db2009-07-25 15:41:38 +00001359 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001360 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001361 return TC_Success;
1362 }
1363
1364 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001365 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001366 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1367 // type large enough to hold it. A value of std::nullptr_t can be
1368 // converted to an integral type; the conversion has the same meaning
1369 // and validity as a conversion of (void*)0 to the integral type.
1370 if (Self.Context.getTypeSize(SrcType) >
1371 Self.Context.getTypeSize(DestType)) {
1372 msg = diag::err_bad_reinterpret_cast_small_int;
1373 return TC_Failed;
1374 }
John McCalle3027922010-08-25 11:45:40 +00001375 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001376 return TC_Success;
1377 }
1378
Anders Carlsson570af5d2009-09-16 19:19:43 +00001379 bool destIsVector = DestType->isVectorType();
1380 bool srcIsVector = SrcType->isVectorType();
1381 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001382 // FIXME: Should this also apply to floating point types?
1383 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1384 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001385
1386 // Check if this is a cast between a vector and something else.
1387 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1388 !(srcIsVector && destIsVector))
1389 return TC_NotApplicable;
1390
1391 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001392 if (Self.Context.getTypeSize(SrcType)
1393 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001394 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001395 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001396 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001397
1398 if (destIsScalar)
1399 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1400 else if (srcIsScalar)
1401 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1402 else
1403 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1404
1405 return TC_Failed;
1406 }
1407
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001408 bool destIsPtr = DestType->isAnyPointerType() ||
1409 DestType->isBlockPointerType();
1410 bool srcIsPtr = SrcType->isAnyPointerType() ||
1411 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001412 if (!destIsPtr && !srcIsPtr) {
1413 // Except for std::nullptr_t->integer and lvalue->reference, which are
1414 // handled above, at least one of the two arguments must be a pointer.
1415 return TC_NotApplicable;
1416 }
1417
1418 if (SrcType == DestType) {
1419 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1420 // restrictions, a cast to the same type is allowed. The intent is not
1421 // entirely clear here, since all other paragraphs explicitly forbid casts
1422 // to the same type. However, the behavior of compilers is pretty consistent
1423 // on this point: allow same-type conversion if the involved types are
1424 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001425 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001426 return TC_Success;
1427 }
1428
Douglas Gregor6972a622010-06-16 00:35:25 +00001429 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001430 assert(srcIsPtr && "One type must be a pointer");
1431 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1432 // type large enough to hold it.
1433 if (Self.Context.getTypeSize(SrcType) >
1434 Self.Context.getTypeSize(DestType)) {
1435 msg = diag::err_bad_reinterpret_cast_small_int;
1436 return TC_Failed;
1437 }
John McCalle3027922010-08-25 11:45:40 +00001438 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001439 return TC_Success;
1440 }
1441
Douglas Gregorb90df602010-06-16 00:17:44 +00001442 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001443 assert(destIsPtr && "One type must be a pointer");
1444 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1445 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001446 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1447 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001448 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001449 return TC_Success;
1450 }
1451
1452 if (!destIsPtr || !srcIsPtr) {
1453 // With the valid non-pointer conversions out of the way, we can be even
1454 // more stringent.
1455 return TC_NotApplicable;
1456 }
1457
1458 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1459 // The C-style cast operator can.
1460 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1461 msg = diag::err_bad_cxx_cast_const_away;
1462 return TC_Failed;
1463 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001464
1465 // Cannot convert between block pointers and Objective-C object pointers.
1466 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1467 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1468 return TC_NotApplicable;
1469
1470 // Any pointer can be cast to an Objective-C pointer type with a C-style
1471 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001472 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001473 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001474 return TC_Success;
1475 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001476
Sebastian Redl9f831db2009-07-25 15:41:38 +00001477 // Not casting away constness, so the only remaining check is for compatible
1478 // pointer categories.
John McCalle3027922010-08-25 11:45:40 +00001479 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001480
1481 if (SrcType->isFunctionPointerType()) {
1482 if (DestType->isFunctionPointerType()) {
1483 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1484 // a pointer to a function of a different type.
1485 return TC_Success;
1486 }
1487
1488 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1489 // an object type or vice versa is conditionally-supported.
1490 // Compilers support it in C++03 too, though, because it's necessary for
1491 // casting the return value of dlsym() and GetProcAddress().
1492 // FIXME: Conditionally-supported behavior should be configurable in the
1493 // TargetInfo or similar.
1494 if (!Self.getLangOptions().CPlusPlus0x)
1495 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1496 return TC_Success;
1497 }
1498
1499 if (DestType->isFunctionPointerType()) {
1500 // See above.
1501 if (!Self.getLangOptions().CPlusPlus0x)
1502 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1503 return TC_Success;
1504 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001505
Sebastian Redl9f831db2009-07-25 15:41:38 +00001506 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1507 // a pointer to an object of different type.
1508 // Void pointers are not specified, but supported by every compiler out there.
1509 // So we finish by allowing everything that remains - it's got to be two
1510 // object pointers.
1511 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001512}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001513
John Wiegley01296292011-04-08 18:41:53 +00001514ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001515Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00001516 Expr *CastExpr, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001517 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001518 bool FunctionalStyle) {
John Wiegley01296292011-04-08 18:41:53 +00001519 if (CastExpr->isBoundMemberFunction(Context)) {
1520 Diag(CastExpr->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001521 << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00001522 return ExprError();
1523 }
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001524
Sebastian Redl9f831db2009-07-25 15:41:38 +00001525 // This test is outside everything else because it's the only case where
1526 // a non-lvalue-reference target type does not lead to decay.
1527 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001528 if (CastTy->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00001529 ExprResult CastExprRes = IgnoredValueConversions(CastExpr);
1530 if (CastExprRes.isInvalid())
1531 return ExprError();
1532 CastExpr = CastExprRes.take();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001533 bool ret = false; // false is 'able to convert'
1534 if (CastExpr->getType() == Context.OverloadTy) {
1535 ExprResult SingleFunctionExpr =
Douglas Gregor1beec452011-03-12 01:48:56 +00001536 ResolveAndFixSingleFunctionTemplateSpecialization(
1537 CastExpr, /* Decay Function to ptr */ false,
1538 /* Complain */ true, R, CastTy,
1539 diag::err_bad_cstyle_cast_overload);
1540
Douglas Gregorb491ed32011-02-19 21:32:49 +00001541 if (SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001542 CastExpr = SingleFunctionExpr.take();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001543 Kind = CK_ToVoid;
1544 }
1545 else
1546 ret = true;
1547 }
1548 else
1549 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00001550 return ret ? ExprError() : Owned(CastExpr);
Anders Carlsson9500ad12009-10-18 20:31:03 +00001551 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001552
Anton Yartsev28ccef72011-03-27 09:32:40 +00001553 // Case of AltiVec vector initialization with a single literal
1554 if (CastTy->isVectorType()
1555 && CastTy->getAs<VectorType>()->getVectorKind() ==
1556 VectorType::AltiVecVector
1557 && (CastExpr->getType()->isIntegerType()
1558 || CastExpr->getType()->isFloatingType())) {
1559 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00001560 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00001561 }
1562
John McCall4cec5f82010-11-30 02:05:44 +00001563 // Make sure we determine the value kind before we bail out for
1564 // dependent types.
1565 VK = Expr::getValueKindForType(CastTy);
1566
Sebastian Redl9f831db2009-07-25 15:41:38 +00001567 // If the type is dependent, we won't do any other semantic analysis now.
John McCall8cb679e2010-11-15 09:13:47 +00001568 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1569 Kind = CK_Dependent;
John Wiegley01296292011-04-08 18:41:53 +00001570 return Owned(CastExpr);
John McCall8cb679e2010-11-15 09:13:47 +00001571 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001572
John Wiegley01296292011-04-08 18:41:53 +00001573 if (VK == VK_RValue && !CastTy->isRecordType()) {
1574 ExprResult CastExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
1575 if (CastExprRes.isInvalid())
1576 return ExprError();
1577 CastExpr = CastExprRes.take();
1578 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001579
1580 // C++ [expr.cast]p5: The conversions performed by
1581 // - a const_cast,
1582 // - a static_cast,
1583 // - a static_cast followed by a const_cast,
1584 // - a reinterpret_cast, or
1585 // - a reinterpret_cast followed by a const_cast,
1586 // can be performed using the cast notation of explicit type conversion.
1587 // [...] If a conversion can be interpreted in more than one of the ways
1588 // listed above, the interpretation that appears first in the list is used,
1589 // even if a cast resulting from that interpretation is ill-formed.
1590 // In plain language, this means trying a const_cast ...
1591 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001592 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1593 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001594 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001595 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001596
Sebastian Redl9f831db2009-07-25 15:41:38 +00001597 if (tcr == TC_NotApplicable) {
1598 // ... or if that is not possible, a static_cast, ignoring const, ...
John Wiegley01296292011-04-08 18:41:53 +00001599 ExprResult CastExprRes = Owned(CastExpr);
1600 tcr = TryStaticCast(*this, CastExprRes, CastTy, /*CStyle*/true, R, msg, Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001601 BasePath);
John Wiegley01296292011-04-08 18:41:53 +00001602 if (CastExprRes.isInvalid())
1603 return ExprError();
1604 CastExpr = CastExprRes.take();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001605 if (tcr == TC_NotApplicable) {
1606 // ... and finally a reinterpret_cast, ignoring const.
John Wiegley01296292011-04-08 18:41:53 +00001607 CastExprRes = Owned(CastExpr);
1608 tcr = TryReinterpretCast(*this, CastExprRes, CastTy, /*CStyle*/true, R, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001609 Kind);
John Wiegley01296292011-04-08 18:41:53 +00001610 if (CastExprRes.isInvalid())
1611 return ExprError();
1612 CastExpr = CastExprRes.take();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001613 }
1614 }
1615
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001616 if (tcr != TC_Success && msg != 0) {
1617 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001618 DeclAccessPair Found;
John Wiegley01296292011-04-08 18:41:53 +00001619 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001620 CastTy,
1621 /* Complain */ true,
1622 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001623
1624 assert(!Fn
1625 && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001626 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001627
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001628 } else {
John McCall909acf82011-02-14 18:34:10 +00001629 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1630 R, CastExpr, CastTy);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001631 }
1632 }
John McCalld50a2712010-11-16 05:46:29 +00001633 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00001634 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001635
John Wiegley01296292011-04-08 18:41:53 +00001636 if (tcr != TC_Success)
1637 return ExprError();
1638
1639 return Owned(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001640}
John McCall31996342011-04-07 08:22:57 +00001641