blob: 506d2612ffbc06d479ecb59a91c46392d01e294b [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
Sebastian Redl842ef522008-11-08 13:00:26 +000045static void CheckConstCast(Sema &Self, Expr *&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);
49static void CheckReinterpretCast(Sema &Self, Expr *&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);
Sebastian Redl842ef522008-11-08 13:00:26 +000054static void CheckStaticCast(Sema &Self, Expr *&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);
Sebastian Redl842ef522008-11-08 13:00:26 +000059static void CheckDynamicCast(Sema &Self, Expr *&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);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000103static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&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
Sebastian Redl7c353682009-11-14 21:15:49 +0000111static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&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);
Sebastian Redl7c353682009-11-14 21:15:49 +0000116static TryCastResult TryStaticCast(Sema &Self, Expr *&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);
Douglas Gregorb491ed32011-02-19 21:32:49 +0000124static TryCastResult TryReinterpretCast(Sema &Self, Expr *&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
131static ExprResult
132ResolveAndFixSingleFunctionTemplateSpecialization(
133 Sema &Self, Expr *SrcExpr,
134 bool DoFunctionPointerConverion = false,
135 bool Complain = false,
136 const SourceRange& OpRangeForComplaining = SourceRange(),
137 QualType DestTypeForComplaining = QualType(),
138 unsigned DiagIDForComplaining = 0);
139
140
141
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000142/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000143ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000144Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallba7bf592010-08-24 05:47:05 +0000145 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000146 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000147 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000148 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000149
John McCall97513962010-01-15 18:39:57 +0000150 TypeSourceInfo *DestTInfo;
151 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
152 if (!DestTInfo)
153 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000154
155 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
156 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
157 SourceRange(LParenLoc, RParenLoc));
158}
159
John McCalldadc5752010-08-24 06:29:42 +0000160ExprResult
John McCalld377e042010-01-15 19:13:16 +0000161Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallfaf5fb42010-08-26 23:41:50 +0000162 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCalld377e042010-01-15 19:13:16 +0000163 SourceRange AngleBrackets, SourceRange Parens) {
John McCalld377e042010-01-15 19:13:16 +0000164 QualType DestType = DestTInfo->getType();
165
166 SourceRange OpRange(OpLoc, Parens.getEnd());
167 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000168
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000169 // If the type is dependent, we won't do the semantic analysis now.
170 // FIXME: should we check this in a more fine-grained manner?
171 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
172
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +0000173 if (Ex->isBoundMemberFunction(Context))
174 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
175 << Ex->getSourceRange();
176
John McCall7decc9e2010-11-18 06:31:45 +0000177 ExprValueKind VK = VK_RValue;
John McCall29ac8e22010-11-26 10:57:22 +0000178 if (TypeDependent)
179 VK = Expr::getValueKindForType(DestType);
180
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000181 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000182 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000183
184 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000185 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000186 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John McCallcf142162010-08-07 06:22:56 +0000187 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000188 DestType.getNonLValueExprType(Context),
Douglas Gregor4478f852011-01-12 22:41:29 +0000189 VK, Ex, DestTInfo, OpLoc,
190 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000191
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000192 case tok::kw_dynamic_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000193 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000194 CXXCastPath BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000195 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000196 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
197 Kind, BasePath);
John McCallcf142162010-08-07 06:22:56 +0000198 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000199 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000200 VK, Kind, Ex, &BasePath, DestTInfo,
Douglas Gregor4478f852011-01-12 22:41:29 +0000201 OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000202 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000203 case tok::kw_reinterpret_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000204 CastKind Kind = CK_Dependent;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000205 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000206 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John McCallcf142162010-08-07 06:22:56 +0000207 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000208 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000209 VK, Kind, Ex, 0,
Douglas Gregor4478f852011-01-12 22:41:29 +0000210 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000211 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000212 case tok::kw_static_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000213 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000214 CXXCastPath BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000215 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000216 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000217
John McCallcf142162010-08-07 06:22:56 +0000218 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000219 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000220 VK, Kind, Ex, &BasePath,
Douglas Gregor4478f852011-01-12 22:41:29 +0000221 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000222 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000223 }
224
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000225 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000226}
227
John McCall909acf82011-02-14 18:34:10 +0000228/// Try to diagnose a failed overloaded cast. Returns true if
229/// diagnostics were emitted.
230static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
231 SourceRange range, Expr *src,
232 QualType destType) {
233 switch (CT) {
234 // These cast kinds don't consider user-defined conversions.
235 case CT_Const:
236 case CT_Reinterpret:
237 case CT_Dynamic:
238 return false;
239
240 // These do.
241 case CT_Static:
242 case CT_CStyle:
243 case CT_Functional:
244 break;
245 }
246
247 QualType srcType = src->getType();
248 if (!destType->isRecordType() && !srcType->isRecordType())
249 return false;
250
251 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
252 InitializationKind initKind
253 = InitializationKind::CreateCast(/*type range?*/ range,
254 (CT == CT_CStyle || CT == CT_Functional));
255 InitializationSequence sequence(S, entity, initKind, &src, 1);
256
257 assert(sequence.getKind() == InitializationSequence::FailedSequence &&
258 "initialization succeeded on second try?");
259 switch (sequence.getFailureKind()) {
260 default: return false;
261
262 case InitializationSequence::FK_ConstructorOverloadFailed:
263 case InitializationSequence::FK_UserConversionOverloadFailed:
264 break;
265 }
266
267 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
268
269 unsigned msg = 0;
270 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
271
272 switch (sequence.getFailedOverloadResult()) {
273 case OR_Success: llvm_unreachable("successful failed overload");
274 return false;
275 case OR_No_Viable_Function:
276 if (candidates.empty())
277 msg = diag::err_ovl_no_conversion_in_cast;
278 else
279 msg = diag::err_ovl_no_viable_conversion_in_cast;
280 howManyCandidates = OCD_AllCandidates;
281 break;
282
283 case OR_Ambiguous:
284 msg = diag::err_ovl_ambiguous_conversion_in_cast;
285 howManyCandidates = OCD_ViableCandidates;
286 break;
287
288 case OR_Deleted:
289 msg = diag::err_ovl_deleted_conversion_in_cast;
290 howManyCandidates = OCD_ViableCandidates;
291 break;
292 }
293
294 S.Diag(range.getBegin(), msg)
295 << CT << srcType << destType
296 << range << src->getSourceRange();
297
298 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
299
300 return true;
301}
302
303/// Diagnose a failed cast.
304static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
305 SourceRange opRange, Expr *src, QualType destType) {
306 if (msg == diag::err_bad_cxx_cast_generic &&
307 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
308 return;
309
310 S.Diag(opRange.getBegin(), msg) << castType
311 << src->getType() << destType << opRange << src->getSourceRange();
312}
313
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000314/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
315/// this removes one level of indirection from both types, provided that they're
316/// the same kind of pointer (plain or to-member). Unlike the Sema function,
317/// this one doesn't care if the two pointers-to-member don't point into the
318/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000319static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000320 const PointerType *T1PtrType = T1->getAs<PointerType>(),
321 *T2PtrType = T2->getAs<PointerType>();
322 if (T1PtrType && T2PtrType) {
323 T1 = T1PtrType->getPointeeType();
324 T2 = T2PtrType->getPointeeType();
325 return true;
326 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000327 const ObjCObjectPointerType *T1ObjCPtrType =
328 T1->getAs<ObjCObjectPointerType>(),
329 *T2ObjCPtrType =
330 T2->getAs<ObjCObjectPointerType>();
331 if (T1ObjCPtrType) {
332 if (T2ObjCPtrType) {
333 T1 = T1ObjCPtrType->getPointeeType();
334 T2 = T2ObjCPtrType->getPointeeType();
335 return true;
336 }
337 else if (T2PtrType) {
338 T1 = T1ObjCPtrType->getPointeeType();
339 T2 = T2PtrType->getPointeeType();
340 return true;
341 }
342 }
343 else if (T2ObjCPtrType) {
344 if (T1PtrType) {
345 T2 = T2ObjCPtrType->getPointeeType();
346 T1 = T1PtrType->getPointeeType();
347 return true;
348 }
349 }
350
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000351 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
352 *T2MPType = T2->getAs<MemberPointerType>();
353 if (T1MPType && T2MPType) {
354 T1 = T1MPType->getPointeeType();
355 T2 = T2MPType->getPointeeType();
356 return true;
357 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000358
359 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
360 *T2BPType = T2->getAs<BlockPointerType>();
361 if (T1BPType && T2BPType) {
362 T1 = T1BPType->getPointeeType();
363 T2 = T2BPType->getPointeeType();
364 return true;
365 }
366
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000367 return false;
368}
369
Sebastian Redla5a77a62009-01-27 23:18:31 +0000370/// CastsAwayConstness - Check if the pointer conversion from SrcType to
371/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
372/// the cast checkers. Both arguments must denote pointer (possibly to member)
373/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000374static bool
Mike Stump11289f42009-09-09 15:08:12 +0000375CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000376 // Casting away constness is defined in C++ 5.2.11p8 with reference to
377 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
378 // the rules are non-trivial. So first we construct Tcv *...cv* as described
379 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000380 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
381 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000382 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000383 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
384 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000385 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000386
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000387 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
388 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000389 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000390
391 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000392 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000393 Qualifiers SrcQuals;
394 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
395 cv1.push_back(SrcQuals);
396
397 Qualifiers DestQuals;
398 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
399 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000400 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000401 if (cv1.empty())
402 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000403
404 // Construct void pointers with those qualifiers (in reverse order of
405 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000406 QualType SrcConstruct = Self.Context.VoidTy;
407 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000408 ASTContext &Context = Self.Context;
409 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
410 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000411 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000412 SrcConstruct
413 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
414 DestConstruct
415 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000416 }
417
418 // Test if they're compatible.
419 return SrcConstruct != DestConstruct &&
Douglas Gregor58281352011-01-27 00:58:17 +0000420 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000421}
422
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000423/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
424/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
425/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000426static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000427CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000428 ExprValueKind &VK, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000429 const SourceRange &DestRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000430 CXXCastPath &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000431 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000432 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000433
434 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
435 // or "pointer to cv void".
436
437 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000438 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000439 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000440 if (DestPointer) {
441 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000442 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000443 DestPointee = DestReference->getPointeeType();
Douglas Gregor465184a2011-01-22 00:06:57 +0000444 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
445 : isa<RValueReferenceType>(DestReference) ? VK_XValue
446 : VK_RValue;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000447 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000448 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000449 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000450 return;
451 }
452
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000453 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000454 if (DestPointee->isVoidType()) {
455 assert(DestPointer && "Reference to void is not possible");
456 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000457 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000458 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000459 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000460 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000461 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000462 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000463 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000464 return;
465 }
466
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000467 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
468 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000469 // an lvalue of a complete class type, [...]. If T is an rvalue reference
470 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000471 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000472 QualType SrcPointee;
473 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000474 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000475 SrcPointee = SrcPointer->getPointeeType();
476 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000477 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000478 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000479 return;
480 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000481 } else if (DestReference->isLValueReferenceType()) {
John McCall086a4642010-11-24 05:12:34 +0000482 if (!SrcExpr->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000483 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000484 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000485 }
486 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000487 } else {
488 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000489 }
490
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000491 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000492 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000493 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000494 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000495 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000496 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000497 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000498 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000499 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000500 return;
501 }
502
503 assert((DestPointer || DestReference) &&
504 "Bad destination non-ptr/ref slipped through.");
505 assert((DestRecord || DestPointee->isVoidType()) &&
506 "Bad destination pointee slipped through.");
507 assert(SrcRecord && "Bad source pointee slipped through.");
508
509 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
510 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000511 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000512 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000513 return;
514 }
515
516 // C++ 5.2.7p3: If the type of v is the same as the required result type,
517 // [except for cv].
518 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000519 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000520 return;
521 }
522
523 // C++ 5.2.7p5
524 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000525 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000526 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
527 OpRange.getBegin(), OpRange,
528 &BasePath))
529 return;
530
John McCalle3027922010-08-25 11:45:40 +0000531 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000532
533 // If we are casting to or through a virtual base class, we need a
534 // vtable.
535 if (Self.BasePathInvolvesVirtualBase(BasePath))
536 Self.MarkVTableUsed(OpRange.getBegin(),
537 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000538 return;
539 }
540
541 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000542 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000543 assert(SrcDecl && "Definition missing");
544 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000545 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000546 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000547 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000548 Self.MarkVTableUsed(OpRange.getBegin(),
549 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000550
551 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000552 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000553}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000554
555/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
556/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
557/// like this:
558/// const char *str = "literal";
559/// legacy_function(const_cast\<char*\>(str));
560void
John McCall7decc9e2010-11-18 06:31:45 +0000561CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump11289f42009-09-09 15:08:12 +0000562 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCall7decc9e2010-11-18 06:31:45 +0000563 VK = Expr::getValueKindForType(DestType);
564 if (VK == VK_RValue)
Douglas Gregorb92a1562010-02-03 00:27:59 +0000565 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000566
567 unsigned msg = diag::err_bad_cxx_cast_generic;
568 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
569 && msg != 0)
570 Self.Diag(OpRange.getBegin(), msg) << CT_Const
571 << SrcExpr->getType() << DestType << OpRange;
572}
573
574/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
575/// valid.
576/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
577/// like this:
578/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
579void
580CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000581 ExprValueKind &VK, const SourceRange &OpRange,
582 const SourceRange &DestRange, CastKind &Kind) {
583 VK = Expr::getValueKindForType(DestType);
584 if (VK == VK_RValue)
Douglas Gregorb92a1562010-02-03 00:27:59 +0000585 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000586
587 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000588 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
589 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000590 != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000591 {
John McCall909acf82011-02-14 18:34:10 +0000592 if (SrcExpr->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000593 //FIXME: &f<int>; is overloaded and resolvable
594 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
595 << OverloadExpr::find(SrcExpr).Expression->getName()
596 << DestType << OpRange;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000597 Self.NoteAllOverloadCandidates(SrcExpr);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000598
John McCall909acf82011-02-14 18:34:10 +0000599 } else {
600 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr, DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000601 }
John McCall909acf82011-02-14 18:34:10 +0000602 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000603}
604
605
606/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
607/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
608/// implicit conversions explicit and getting rid of data loss warnings.
609void
610CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000611 ExprValueKind &VK, const SourceRange &OpRange,
612 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000613 // This test is outside everything else because it's the only case where
614 // a non-lvalue-reference target type does not lead to decay.
615 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000616 if (DestType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +0000617 Self.IgnoredValueConversions(SrcExpr);
Douglas Gregorb491ed32011-02-19 21:32:49 +0000618 if (SrcExpr->getType() == Self.Context.OverloadTy) {
619 ExprResult SingleFunctionExpression =
620 ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr,
621 false, // Decay Function to ptr
622 true, // Complain
623 OpRange, DestType, diag::err_bad_static_cast_overload);
624 if (SingleFunctionExpression.isUsable())
625 {
626 SrcExpr = SingleFunctionExpression.release();
627 Kind = CK_ToVoid;
628 }
629 }
630 else
631 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000632 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000633 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000634
John McCall7decc9e2010-11-18 06:31:45 +0000635 VK = Expr::getValueKindForType(DestType);
636 if (VK == VK_RValue && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000637 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000638
639 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000640 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000641 Kind, BasePath) != TC_Success && msg != 0) {
John McCall909acf82011-02-14 18:34:10 +0000642 if (SrcExpr->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000643 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
644 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
645 << oe->getName() << DestType << OpRange << oe->getQualifierRange();
Douglas Gregorb491ed32011-02-19 21:32:49 +0000646 Self.NoteAllOverloadCandidates(SrcExpr);
John McCall909acf82011-02-14 18:34:10 +0000647 } else {
648 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr, DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000649 }
Douglas Gregore81f58e2010-11-08 03:40:48 +0000650 }
John McCalld50a2712010-11-16 05:46:29 +0000651 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +0000652 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000653}
654
655/// TryStaticCast - Check if a static cast can be performed, and do so if
656/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
657/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000658static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000659 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000660 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000661 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000662 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000663 // The order the tests is not entirely arbitrary. There is one conversion
664 // that can be handled in two different ways. Given:
665 // struct A {};
666 // struct B : public A {
667 // B(); B(const A&);
668 // };
669 // const A &a = B();
670 // the cast static_cast<const B&>(a) could be seen as either a static
671 // reference downcast, or an explicit invocation of the user-defined
672 // conversion using B's conversion constructor.
673 // DR 427 specifies that the downcast is to be applied here.
674
675 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
676 // Done outside this function.
677
678 TryCastResult tcr;
679
680 // C++ 5.2.9p5, reference downcast.
681 // See the function for details.
682 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000683 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000684 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000685 if (tcr != TC_NotApplicable)
686 return tcr;
687
Douglas Gregor465184a2011-01-22 00:06:57 +0000688 // C++0x [expr.static.cast]p3:
689 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
690 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Douglas Gregorce950842011-01-26 21:04:06 +0000691 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, CStyle, Kind, BasePath,
692 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000693 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000694 return tcr;
695
696 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
697 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000698 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000699 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000700 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000701 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000702
Sebastian Redl9f831db2009-07-25 15:41:38 +0000703 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
704 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
705 // conversions, subject to further restrictions.
706 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
707 // of qualification conversions impossible.
708 // In the CStyle case, the earlier attempt to const_cast should have taken
709 // care of reverse qualification conversions.
710
Sebastian Redl9f831db2009-07-25 15:41:38 +0000711 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
712
Douglas Gregor0bf31402010-10-08 23:50:27 +0000713 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000714 // converted to an integral type. [...] A value of a scoped enumeration type
715 // can also be explicitly converted to a floating-point type [...].
716 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
717 if (Enum->getDecl()->isScoped()) {
718 if (DestType->isBooleanType()) {
719 Kind = CK_IntegralToBoolean;
720 return TC_Success;
721 } else if (DestType->isIntegralType(Self.Context)) {
722 Kind = CK_IntegralCast;
723 return TC_Success;
724 } else if (DestType->isRealFloatingType()) {
725 Kind = CK_IntegralToFloating;
726 return TC_Success;
727 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000728 }
729 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000730
Sebastian Redl9f831db2009-07-25 15:41:38 +0000731 // Reverse integral promotion/conversion. All such conversions are themselves
732 // again integral promotions or conversions and are thus already handled by
733 // p2 (TryDirectInitialization above).
734 // (Note: any data loss warnings should be suppressed.)
735 // The exception is the reverse of enum->integer, i.e. integer->enum (and
736 // enum->enum). See also C++ 5.2.9p7.
737 // The same goes for reverse floating point promotion/conversion and
738 // floating-integral conversions. Again, only floating->enum is relevant.
739 if (DestType->isEnumeralType()) {
740 if (SrcType->isComplexType() || SrcType->isVectorType()) {
741 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000742 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCalle3027922010-08-25 11:45:40 +0000743 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000744 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000745 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000746 }
747
748 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
749 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000750 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000751 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000752 if (tcr != TC_NotApplicable)
753 return tcr;
754
755 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
756 // conversion. C++ 5.2.9p9 has additional information.
757 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000758 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000759 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000760 if (tcr != TC_NotApplicable)
761 return tcr;
762
763 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
764 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
765 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000766 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000767 QualType SrcPointee = SrcPointer->getPointeeType();
768 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000769 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000770 QualType DestPointee = DestPointer->getPointeeType();
771 if (DestPointee->isIncompleteOrObjectType()) {
772 // This is definitely the intended conversion, but it might fail due
773 // to a const violation.
774 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
775 msg = diag::err_bad_cxx_cast_const_away;
776 return TC_Failed;
777 }
John McCalle3027922010-08-25 11:45:40 +0000778 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000779 return TC_Success;
780 }
781 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000782 else if (DestType->isObjCObjectPointerType()) {
783 // allow both c-style cast and static_cast of objective-c pointers as
784 // they are pervasive.
John McCalle3027922010-08-25 11:45:40 +0000785 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000786 return TC_Success;
787 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000788 else if (CStyle && DestType->isBlockPointerType()) {
789 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000790 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000791 return TC_Success;
792 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000793 }
794 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000795 // Allow arbitray objective-c pointer conversion with static casts.
796 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000797 DestType->isObjCObjectPointerType()) {
798 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000799 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000800 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000801
Sebastian Redl9f831db2009-07-25 15:41:38 +0000802 // We tried everything. Everything! Nothing works! :-(
803 return TC_NotApplicable;
804}
805
806/// Tests whether a conversion according to N2844 is valid.
807TryCastResult
808TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000809 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
810 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000811 // C++0x [expr.static.cast]p3:
812 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
813 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000814 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000815 if (!R)
816 return TC_NotApplicable;
817
Douglas Gregor465184a2011-01-22 00:06:57 +0000818 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000819 return TC_NotApplicable;
820
821 // Because we try the reference downcast before this function, from now on
822 // this is the only cast possibility, so we issue an error if we fail now.
823 // FIXME: Should allow casting away constness if CStyle.
824 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000825 bool ObjCConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000826 QualType FromType = SrcExpr->getType();
827 QualType ToType = R->getPointeeType();
828 if (CStyle) {
829 FromType = FromType.getUnqualifiedType();
830 ToType = ToType.getUnqualifiedType();
831 }
832
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000833 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000834 ToType, FromType,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000835 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000836 Sema::Ref_Compatible_With_Added_Qualification) {
837 msg = diag::err_bad_lvalue_to_rvalue_cast;
838 return TC_Failed;
839 }
840
Douglas Gregorba278e22011-01-25 16:13:26 +0000841 if (DerivedToBase) {
842 Kind = CK_DerivedToBase;
843 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
844 /*DetectVirtual=*/true);
845 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
846 return TC_NotApplicable;
847
848 Self.BuildBasePathArray(Paths, BasePath);
849 } else
850 Kind = CK_NoOp;
851
Sebastian Redl9f831db2009-07-25 15:41:38 +0000852 return TC_Success;
853}
854
855/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
856TryCastResult
857TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
858 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000859 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000860 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000861 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
862 // cast to type "reference to cv2 D", where D is a class derived from B,
863 // if a valid standard conversion from "pointer to D" to "pointer to B"
864 // exists, cv2 >= cv1, and B is not a virtual base class of D.
865 // In addition, DR54 clarifies that the base must be accessible in the
866 // current context. Although the wording of DR54 only applies to the pointer
867 // variant of this rule, the intent is clearly for it to apply to the this
868 // conversion as well.
869
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000870 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000871 if (!DestReference) {
872 return TC_NotApplicable;
873 }
874 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000875 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000876 // We know the left side is an lvalue reference, so we can suggest a reason.
877 msg = diag::err_bad_cxx_cast_rvalue;
878 return TC_NotApplicable;
879 }
880
881 QualType DestPointee = DestReference->getPointeeType();
882
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000883 return TryStaticDowncast(Self,
884 Self.Context.getCanonicalType(SrcExpr->getType()),
885 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000886 OpRange, SrcExpr->getType(), DestType, msg, Kind,
887 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000888}
889
890/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
891TryCastResult
892TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000893 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000894 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000895 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000896 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
897 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
898 // is a class derived from B, if a valid standard conversion from "pointer
899 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
900 // class of D.
901 // In addition, DR54 clarifies that the base must be accessible in the
902 // current context.
903
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000904 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000905 if (!DestPointer) {
906 return TC_NotApplicable;
907 }
908
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000909 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000910 if (!SrcPointer) {
911 msg = diag::err_bad_static_cast_pointer_nonpointer;
912 return TC_NotApplicable;
913 }
914
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000915 return TryStaticDowncast(Self,
916 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
917 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000918 CStyle, OpRange, SrcType, DestType, msg, Kind,
919 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000920}
921
922/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
923/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000924/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000925TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000926TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000927 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000928 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000929 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000930 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000931 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
932 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000933 return TC_NotApplicable;
934
Sebastian Redl9f831db2009-07-25 15:41:38 +0000935 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000936 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000937 return TC_NotApplicable;
938 }
939
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000940 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000941 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000942 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
943 return TC_NotApplicable;
944 }
945
946 // Target type does derive from source type. Now we're serious. If an error
947 // appears now, it's not ignored.
948 // This may not be entirely in line with the standard. Take for example:
949 // struct A {};
950 // struct B : virtual A {
951 // B(A&);
952 // };
Mike Stump11289f42009-09-09 15:08:12 +0000953 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000954 // void f()
955 // {
956 // (void)static_cast<const B&>(*((A*)0));
957 // }
958 // As far as the standard is concerned, p5 does not apply (A is virtual), so
959 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
960 // However, both GCC and Comeau reject this example, and accepting it would
961 // mean more complex code if we're to preserve the nice error message.
962 // FIXME: Being 100% compliant here would be nice to have.
963
964 // Must preserve cv, as always, unless we're in C-style mode.
965 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
966 msg = diag::err_bad_cxx_cast_const_away;
967 return TC_Failed;
968 }
969
970 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
971 // This code is analoguous to that in CheckDerivedToBaseConversion, except
972 // that it builds the paths in reverse order.
973 // To sum up: record all paths to the base and build a nice string from
974 // them. Use it to spice up the error message.
975 if (!Paths.isRecordingPaths()) {
976 Paths.clear();
977 Paths.setRecordingPaths(true);
978 Self.IsDerivedFrom(DestType, SrcType, Paths);
979 }
980 std::string PathDisplayStr;
981 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000982 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000983 PI != PE; ++PI) {
984 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
985 // We haven't displayed a path to this particular base
986 // class subobject yet.
987 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000988 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
989 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000990 EI != EE; ++EI)
991 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000992 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000993 }
994 }
995
996 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000997 << QualType(SrcType).getUnqualifiedType()
998 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000999 << PathDisplayStr << OpRange;
1000 msg = 0;
1001 return TC_Failed;
1002 }
1003
1004 if (Paths.getDetectedVirtual() != 0) {
1005 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1006 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1007 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1008 msg = 0;
1009 return TC_Failed;
1010 }
1011
John McCallfe9cf0a2011-02-14 23:21:33 +00001012 if (!CStyle) {
1013 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1014 SrcType, DestType,
1015 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001016 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001017 case Sema::AR_accessible:
1018 case Sema::AR_delayed: // be optimistic
1019 case Sema::AR_dependent: // be optimistic
1020 break;
1021
1022 case Sema::AR_inaccessible:
1023 msg = 0;
1024 return TC_Failed;
1025 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001026 }
1027
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001028 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001029 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001030 return TC_Success;
1031}
1032
1033/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1034/// C++ 5.2.9p9 is valid:
1035///
1036/// An rvalue of type "pointer to member of D of type cv1 T" can be
1037/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1038/// where B is a base class of D [...].
1039///
1040TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +00001041TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
1042 QualType DestType, bool CStyle,
1043 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001044 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001045 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001046 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001047 if (!DestMemPtr)
1048 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001049
1050 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001051 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +00001052 if (SrcExpr->getType() == Self.Context.OverloadTy) {
1053 if (FunctionDecl *Fn
1054 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
1055 FoundOverload)) {
1056 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1057 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1058 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1059 WasOverloadedFunction = true;
1060 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001061 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001062
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001063 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001064 if (!SrcMemPtr) {
1065 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1066 return TC_NotApplicable;
1067 }
1068
1069 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001070 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1071 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001072 return TC_NotApplicable;
1073
1074 // B base of D
1075 QualType SrcClass(SrcMemPtr->getClass(), 0);
1076 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001077 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001078 /*DetectVirtual=*/true);
1079 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1080 return TC_NotApplicable;
1081 }
1082
1083 // 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 +00001084 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001085 Paths.clear();
1086 Paths.setRecordingPaths(true);
1087 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1088 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001089 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001090 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1091 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1092 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1093 msg = 0;
1094 return TC_Failed;
1095 }
1096
1097 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1098 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1099 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1100 msg = 0;
1101 return TC_Failed;
1102 }
1103
John McCallfe9cf0a2011-02-14 23:21:33 +00001104 if (!CStyle) {
1105 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1106 DestClass, SrcClass,
1107 Paths.front(),
1108 diag::err_upcast_to_inaccessible_base)) {
1109 case Sema::AR_accessible:
1110 case Sema::AR_delayed:
1111 case Sema::AR_dependent:
1112 // Optimistically assume that the delayed and dependent cases
1113 // will work out.
1114 break;
1115
1116 case Sema::AR_inaccessible:
1117 msg = 0;
1118 return TC_Failed;
1119 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001120 }
1121
Douglas Gregorc934bc82010-03-07 23:24:59 +00001122 if (WasOverloadedFunction) {
1123 // Resolve the address of the overloaded function again, this time
1124 // allowing complaints if something goes wrong.
1125 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
1126 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001127 true,
1128 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001129 if (!Fn) {
1130 msg = 0;
1131 return TC_Failed;
1132 }
1133
John McCall16df1e52010-03-30 21:47:33 +00001134 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001135 if (!SrcExpr) {
1136 msg = 0;
1137 return TC_Failed;
1138 }
1139 }
1140
Anders Carlssonb78feca2010-04-24 19:22:20 +00001141 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001142 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001143 return TC_Success;
1144}
1145
1146/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1147/// is valid:
1148///
1149/// An expression e can be explicitly converted to a type T using a
1150/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1151TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +00001152TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001153 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001154 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001155 if (DestType->isRecordType()) {
1156 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1157 diag::err_bad_dynamic_cast_incomplete)) {
1158 msg = 0;
1159 return TC_Failed;
1160 }
1161 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001162
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001163 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1164 InitializationKind InitKind
Douglas Gregor58281352011-01-27 00:58:17 +00001165 = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001166 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001167
1168 // At this point of CheckStaticCast, if the destination is a reference,
1169 // or the expression is an overload expression this has to work.
1170 // There is no other way that works.
1171 // On the other hand, if we're checking a C-style cast, we've still got
1172 // the reinterpret_cast way.
1173
Douglas Gregorb33eed02010-04-16 22:09:46 +00001174 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregore81f58e2010-11-08 03:40:48 +00001175 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001176 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001177
John McCalldadc5752010-08-24 06:29:42 +00001178 ExprResult Result
John McCallfaf5fb42010-08-26 23:41:50 +00001179 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001180 if (Result.isInvalid()) {
1181 msg = 0;
1182 return TC_Failed;
1183 }
1184
Douglas Gregorb33eed02010-04-16 22:09:46 +00001185 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001186 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001187 else
John McCalle3027922010-08-25 11:45:40 +00001188 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001189
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001190 SrcExpr = Result.takeAs<Expr>();
1191 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001192}
1193
1194/// TryConstCast - See if a const_cast from source to destination is allowed,
1195/// and perform it if it is.
1196static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1197 bool CStyle, unsigned &msg) {
1198 DestType = Self.Context.getCanonicalType(DestType);
1199 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001200 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1201 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001202 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1203 // is C-style, static_cast might find a way, so we simply suggest a
1204 // message and tell the parent to keep searching.
1205 msg = diag::err_bad_cxx_cast_rvalue;
1206 return TC_NotApplicable;
1207 }
1208
1209 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1210 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1211 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1212 SrcType = Self.Context.getPointerType(SrcType);
1213 }
1214
1215 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1216 // the rules for const_cast are the same as those used for pointers.
1217
John McCall0e704f72010-05-18 09:35:29 +00001218 if (!DestType->isPointerType() &&
1219 !DestType->isMemberPointerType() &&
1220 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001221 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1222 // was a reference type, we converted it to a pointer above.
1223 // The status of rvalue references isn't entirely clear, but it looks like
1224 // conversion to them is simply invalid.
1225 // C++ 5.2.11p3: For two pointer types [...]
1226 if (!CStyle)
1227 msg = diag::err_bad_const_cast_dest;
1228 return TC_NotApplicable;
1229 }
1230 if (DestType->isFunctionPointerType() ||
1231 DestType->isMemberFunctionPointerType()) {
1232 // Cannot cast direct function pointers.
1233 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1234 // T is the ultimate pointee of source and target type.
1235 if (!CStyle)
1236 msg = diag::err_bad_const_cast_dest;
1237 return TC_NotApplicable;
1238 }
1239 SrcType = Self.Context.getCanonicalType(SrcType);
1240
1241 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1242 // completely equal.
1243 // FIXME: const_cast should probably not be able to convert between pointers
1244 // to different address spaces.
1245 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1246 // in multi-level pointers may change, but the level count must be the same,
1247 // as must be the final pointee type.
1248 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001249 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001250 Qualifiers Quals;
1251 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1252 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001253 }
1254
1255 // Since we're dealing in canonical types, the remainder must be the same.
1256 if (SrcType != DestType)
1257 return TC_NotApplicable;
1258
1259 return TC_Success;
1260}
1261
Douglas Gregorb491ed32011-02-19 21:32:49 +00001262// A helper function to resolve and fix an overloaded expression that
1263// can be resolved because it identifies a single function
1264// template specialization
1265// Last three arguments should only be supplied if Complain = true
1266static ExprResult ResolveAndFixSingleFunctionTemplateSpecialization(
1267 Sema &Self, Expr *SrcExpr,
1268 bool DoFunctionPointerConverion,
1269 bool Complain,
1270 const SourceRange& OpRangeForComplaining,
1271 QualType DestTypeForComplaining,
1272 unsigned DiagIDForComplaining) {
1273 assert(SrcExpr->getType() == Self.Context.OverloadTy);
1274 DeclAccessPair Found;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001275 Expr* SingleFunctionExpression = 0;
1276 if (FunctionDecl* Fn = Self.ResolveSingleFunctionTemplateSpecialization(
1277 SrcExpr, false, // false -> Complain
1278 &Found)) {
1279 if (!Self.DiagnoseUseOfDecl(Fn, SrcExpr->getSourceRange().getBegin())) {
1280 // mark the expression as resolved to Fn
1281 SingleFunctionExpression = Self.FixOverloadedFunctionReference(SrcExpr,
1282 Found, Fn);
1283
1284 if (DoFunctionPointerConverion)
1285 Self.DefaultFunctionArrayLvalueConversion(SingleFunctionExpression);
1286 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001287 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001288 if (!SingleFunctionExpression && Complain) {
1289 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
1290 Self.Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
1291 << oe->getName() << DestTypeForComplaining << OpRangeForComplaining
1292 << oe->getQualifierRange();
1293 Self.NoteAllOverloadCandidates(SrcExpr);
1294 }
1295 return SingleFunctionExpression;
Douglas Gregore81f58e2010-11-08 03:40:48 +00001296}
1297
Douglas Gregorb491ed32011-02-19 21:32:49 +00001298static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001299 QualType DestType, bool CStyle,
1300 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001301 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001302 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001303 bool IsLValueCast = false;
1304
Sebastian Redl9f831db2009-07-25 15:41:38 +00001305 DestType = Self.Context.getCanonicalType(DestType);
1306 QualType SrcType = SrcExpr->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001307
1308 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001309 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1310 if (SrcType == Self.Context.OverloadTy) {
1311 // ... unless foo<int> resolves to an lvalue unambiguously
1312 ExprResult SingleFunctionExpr =
1313 ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr,
1314 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1315 );
1316 if (SingleFunctionExpr.isUsable()) {
1317 SrcExpr = SingleFunctionExpr.release();
1318 SrcType = SrcExpr->getType();
1319 }
1320 else
1321 return TC_NotApplicable;
1322 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001323
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001324 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001325 bool LValue = DestTypeTmp->isLValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001326 if (LValue && !SrcExpr->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001327 // Cannot cast non-lvalue to lvalue reference type. See the similar
1328 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001329 msg = diag::err_bad_cxx_cast_rvalue;
1330 return TC_NotApplicable;
1331 }
1332
1333 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1334 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1335 // built-in & and * operators.
1336 // This code does this transformation for the checked types.
1337 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1338 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001339
Douglas Gregor51954272010-07-13 23:17:26 +00001340 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001341 }
1342
1343 // Canonicalize source for comparison.
1344 SrcType = Self.Context.getCanonicalType(SrcType);
1345
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001346 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1347 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001348 if (DestMemPtr && SrcMemPtr) {
1349 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1350 // can be explicitly converted to an rvalue of type "pointer to member
1351 // of Y of type T2" if T1 and T2 are both function types or both object
1352 // types.
1353 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1354 SrcMemPtr->getPointeeType()->isFunctionType())
1355 return TC_NotApplicable;
1356
1357 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1358 // constness.
1359 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1360 // we accept it.
1361 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1362 msg = diag::err_bad_cxx_cast_const_away;
1363 return TC_Failed;
1364 }
1365
Charles Davisebab1ed2010-08-16 05:30:44 +00001366 // Don't allow casting between member pointers of different sizes.
1367 if (Self.Context.getTypeSize(DestMemPtr) !=
1368 Self.Context.getTypeSize(SrcMemPtr)) {
1369 msg = diag::err_bad_cxx_cast_member_pointer_size;
1370 return TC_Failed;
1371 }
1372
Sebastian Redl9f831db2009-07-25 15:41:38 +00001373 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001374 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001375 return TC_Success;
1376 }
1377
1378 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001379 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001380 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1381 // type large enough to hold it. A value of std::nullptr_t can be
1382 // converted to an integral type; the conversion has the same meaning
1383 // and validity as a conversion of (void*)0 to the integral type.
1384 if (Self.Context.getTypeSize(SrcType) >
1385 Self.Context.getTypeSize(DestType)) {
1386 msg = diag::err_bad_reinterpret_cast_small_int;
1387 return TC_Failed;
1388 }
John McCalle3027922010-08-25 11:45:40 +00001389 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001390 return TC_Success;
1391 }
1392
Anders Carlsson570af5d2009-09-16 19:19:43 +00001393 bool destIsVector = DestType->isVectorType();
1394 bool srcIsVector = SrcType->isVectorType();
1395 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001396 // FIXME: Should this also apply to floating point types?
1397 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1398 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001399
1400 // Check if this is a cast between a vector and something else.
1401 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1402 !(srcIsVector && destIsVector))
1403 return TC_NotApplicable;
1404
1405 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001406 if (Self.Context.getTypeSize(SrcType)
1407 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001408 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001409 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001410 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001411
1412 if (destIsScalar)
1413 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1414 else if (srcIsScalar)
1415 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1416 else
1417 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1418
1419 return TC_Failed;
1420 }
1421
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001422 bool destIsPtr = DestType->isAnyPointerType() ||
1423 DestType->isBlockPointerType();
1424 bool srcIsPtr = SrcType->isAnyPointerType() ||
1425 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001426 if (!destIsPtr && !srcIsPtr) {
1427 // Except for std::nullptr_t->integer and lvalue->reference, which are
1428 // handled above, at least one of the two arguments must be a pointer.
1429 return TC_NotApplicable;
1430 }
1431
1432 if (SrcType == DestType) {
1433 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1434 // restrictions, a cast to the same type is allowed. The intent is not
1435 // entirely clear here, since all other paragraphs explicitly forbid casts
1436 // to the same type. However, the behavior of compilers is pretty consistent
1437 // on this point: allow same-type conversion if the involved types are
1438 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001439 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001440 return TC_Success;
1441 }
1442
Douglas Gregor6972a622010-06-16 00:35:25 +00001443 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001444 assert(srcIsPtr && "One type must be a pointer");
1445 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1446 // type large enough to hold it.
1447 if (Self.Context.getTypeSize(SrcType) >
1448 Self.Context.getTypeSize(DestType)) {
1449 msg = diag::err_bad_reinterpret_cast_small_int;
1450 return TC_Failed;
1451 }
John McCalle3027922010-08-25 11:45:40 +00001452 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001453 return TC_Success;
1454 }
1455
Douglas Gregorb90df602010-06-16 00:17:44 +00001456 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001457 assert(destIsPtr && "One type must be a pointer");
1458 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1459 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001460 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1461 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001462 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001463 return TC_Success;
1464 }
1465
1466 if (!destIsPtr || !srcIsPtr) {
1467 // With the valid non-pointer conversions out of the way, we can be even
1468 // more stringent.
1469 return TC_NotApplicable;
1470 }
1471
1472 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1473 // The C-style cast operator can.
1474 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1475 msg = diag::err_bad_cxx_cast_const_away;
1476 return TC_Failed;
1477 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001478
1479 // Cannot convert between block pointers and Objective-C object pointers.
1480 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1481 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1482 return TC_NotApplicable;
1483
1484 // Any pointer can be cast to an Objective-C pointer type with a C-style
1485 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001486 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001487 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001488 return TC_Success;
1489 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001490
Sebastian Redl9f831db2009-07-25 15:41:38 +00001491 // Not casting away constness, so the only remaining check is for compatible
1492 // pointer categories.
John McCalle3027922010-08-25 11:45:40 +00001493 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001494
1495 if (SrcType->isFunctionPointerType()) {
1496 if (DestType->isFunctionPointerType()) {
1497 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1498 // a pointer to a function of a different type.
1499 return TC_Success;
1500 }
1501
1502 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1503 // an object type or vice versa is conditionally-supported.
1504 // Compilers support it in C++03 too, though, because it's necessary for
1505 // casting the return value of dlsym() and GetProcAddress().
1506 // FIXME: Conditionally-supported behavior should be configurable in the
1507 // TargetInfo or similar.
1508 if (!Self.getLangOptions().CPlusPlus0x)
1509 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1510 return TC_Success;
1511 }
1512
1513 if (DestType->isFunctionPointerType()) {
1514 // See above.
1515 if (!Self.getLangOptions().CPlusPlus0x)
1516 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1517 return TC_Success;
1518 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001519
Sebastian Redl9f831db2009-07-25 15:41:38 +00001520 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1521 // a pointer to an object of different type.
1522 // Void pointers are not specified, but supported by every compiler out there.
1523 // So we finish by allowing everything that remains - it's got to be two
1524 // object pointers.
1525 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001526}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001527
Anders Carlssona70cff62010-04-24 19:06:50 +00001528bool
John McCall7decc9e2010-11-18 06:31:45 +00001529Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
1530 Expr *&CastExpr, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001531 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001532 bool FunctionalStyle) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001533 if (CastExpr->isBoundMemberFunction(Context))
1534 return Diag(CastExpr->getLocStart(),
1535 diag::err_invalid_use_of_bound_member_func)
1536 << CastExpr->getSourceRange();
1537
Sebastian Redl9f831db2009-07-25 15:41:38 +00001538 // This test is outside everything else because it's the only case where
1539 // a non-lvalue-reference target type does not lead to decay.
1540 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001541 if (CastTy->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00001542 IgnoredValueConversions(CastExpr);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001543 bool ret = false; // false is 'able to convert'
1544 if (CastExpr->getType() == Context.OverloadTy) {
1545 ExprResult SingleFunctionExpr =
1546 ResolveAndFixSingleFunctionTemplateSpecialization(*this,
1547 CastExpr,
1548 /* Decay Function to ptr */ false,
1549 /* Complain */ true,
1550 R, CastTy, diag::err_bad_cstyle_cast_overload);
1551 if (SingleFunctionExpr.isUsable()) {
1552 CastExpr = SingleFunctionExpr.release();
1553 Kind = CK_ToVoid;
1554 }
1555 else
1556 ret = true;
1557 }
1558 else
1559 Kind = CK_ToVoid;
1560 return ret;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001561 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001562
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;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001570 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001571 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001572
John McCall7decc9e2010-11-18 06:31:45 +00001573 if (VK == VK_RValue && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001574 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001575
1576 // C++ [expr.cast]p5: The conversions performed by
1577 // - a const_cast,
1578 // - a static_cast,
1579 // - a static_cast followed by a const_cast,
1580 // - a reinterpret_cast, or
1581 // - a reinterpret_cast followed by a const_cast,
1582 // can be performed using the cast notation of explicit type conversion.
1583 // [...] If a conversion can be interpreted in more than one of the ways
1584 // listed above, the interpretation that appears first in the list is used,
1585 // even if a cast resulting from that interpretation is ill-formed.
1586 // In plain language, this means trying a const_cast ...
1587 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001588 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1589 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001590 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001591 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001592
Sebastian Redl9f831db2009-07-25 15:41:38 +00001593 if (tcr == TC_NotApplicable) {
1594 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001595 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1596 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001597 if (tcr == TC_NotApplicable) {
1598 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001599 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1600 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001601 }
1602 }
1603
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001604 if (tcr != TC_Success && msg != 0) {
1605 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001606 DeclAccessPair Found;
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001607 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001608 CastTy,
1609 /* Complain */ true,
1610 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001611
1612 assert(!Fn
1613 && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001614 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001615
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001616 } else {
John McCall909acf82011-02-14 18:34:10 +00001617 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1618 R, CastExpr, CastTy);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001619 }
1620 }
John McCalld50a2712010-11-16 05:46:29 +00001621 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00001622 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001623
1624 return tcr != TC_Success;
1625}