blob: 40086d6eff764e0cef1eb35fa2a2df80d9419f72 [file] [log] [blame]
Sebastian Redl26d85b12008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000022using namespace clang;
23
Douglas Gregor8e960432010-11-08 03:40:48 +000024
Douglas Gregor8e960432010-11-08 03:40:48 +000025
Sebastian Redl9cc11e72009-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 Redl37d6de32008-11-08 13:00:26 +000040};
41
Douglas Gregor8e960432010-11-08 03:40:48 +000042
43
44
John Wiegley429bb272011-04-08 18:41:53 +000045static void CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000046 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000047 const SourceRange &OpRange,
48 const SourceRange &DestRange);
John Wiegley429bb272011-04-08 18:41:53 +000049static void CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000050 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000051 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000052 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000053 CastKind &Kind);
John Wiegley429bb272011-04-08 18:41:53 +000054static void CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000055 ExprValueKind &VK,
Anders Carlssoncdb61972009-08-07 22:21:05 +000056 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +000057 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000058 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +000059static void CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000060 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000061 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000062 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000063 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000064 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000065
John McCallf85e1932011-06-15 23:02:42 +000066static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
67 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000068
69// The Try functions attempt a specific way of casting. If they succeed, they
70// return TC_Success. If their way of casting is not appropriate for the given
71// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
72// to emit if no other way succeeds. If their way of casting is appropriate but
73// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
74// they emit a specialized diagnostic.
75// All diagnostics returned by these functions must expect the same three
76// arguments:
77// %0: Cast Type (a value from the CastType enumeration)
78// %1: Source Type
79// %2: Destination Type
80static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregor8ec14e62011-01-26 21:04:06 +000081 QualType DestType, bool CStyle,
82 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +000083 CXXCastPath &BasePath,
84 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000085static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000086 QualType DestType, bool CStyle,
87 const SourceRange &OpRange,
88 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000089 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000090 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000091static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
92 QualType DestType, bool CStyle,
93 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000094 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000095 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000096 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000097static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
98 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000099 const SourceRange &OpRange,
100 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000101 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000102 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000103 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000104static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000105 QualType SrcType,
106 QualType DestType,bool CStyle,
107 const SourceRange &OpRange,
108 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000109 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000110 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000111
John Wiegley429bb272011-04-08 18:41:53 +0000112static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000113 QualType DestType,
114 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000115 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000116 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000117 CastKind &Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000118static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000119 QualType DestType,
120 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000121 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000122 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000123 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000124 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000125static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
126 bool CStyle, unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000127static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000128 QualType DestType, bool CStyle,
129 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000130 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000131 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000132
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000133
Sebastian Redl26d85b12008-11-05 21:50:06 +0000134/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000135ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000136Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallb3d87482010-08-24 05:47:05 +0000137 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000138 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000139 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000140 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000141
John McCall9d125032010-01-15 18:39:57 +0000142 TypeSourceInfo *DestTInfo;
143 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
144 if (!DestTInfo)
145 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000146
147 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
148 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
149 SourceRange(LParenLoc, RParenLoc));
150}
151
John McCall60d7b3a2010-08-24 06:29:42 +0000152ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000153Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000154 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000155 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000156 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000157 QualType DestType = DestTInfo->getType();
158
159 SourceRange OpRange(OpLoc, Parens.getEnd());
160 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000161
Douglas Gregor9103bb22008-12-17 22:52:20 +0000162 // If the type is dependent, we won't do the semantic analysis now.
163 // FIXME: should we check this in a more fine-grained manner?
John Wiegley429bb272011-04-08 18:41:53 +0000164 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000165
John McCallf89e55a2010-11-18 06:31:45 +0000166 ExprValueKind VK = VK_RValue;
John McCalla21e06c2010-11-26 10:57:22 +0000167 if (TypeDependent)
168 VK = Expr::getValueKindForType(DestType);
169
Sebastian Redl26d85b12008-11-05 21:50:06 +0000170 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000171 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000172
173 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000174 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000175 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John Wiegley429bb272011-04-08 18:41:53 +0000176 if (Ex.isInvalid())
177 return ExprError();
178 }
John McCallf871d0c2010-08-07 06:22:56 +0000179 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000180 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000181 VK, Ex.take(), DestTInfo, OpLoc,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000182 Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000183
Anders Carlsson714179b2009-08-02 19:07:59 +0000184 case tok::kw_dynamic_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000185 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000186 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000187 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000188 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
189 Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000190 if (Ex.isInvalid())
191 return ExprError();
192 }
John McCallf871d0c2010-08-07 06:22:56 +0000193 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000194 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000195 VK, Kind, Ex.take(), &BasePath, DestTInfo,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000196 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000197 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000198 case tok::kw_reinterpret_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000199 CastKind Kind = CK_Dependent;
John Wiegley429bb272011-04-08 18:41:53 +0000200 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000201 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000202 if (Ex.isInvalid())
203 return ExprError();
204 }
John McCallf871d0c2010-08-07 06:22:56 +0000205 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000206 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000207 VK, Kind, Ex.take(), 0,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000208 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000209 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000210 case tok::kw_static_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000211 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000212 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000213 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000214 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000215 if (Ex.isInvalid())
216 return ExprError();
217 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000218
John McCallf871d0c2010-08-07 06:22:56 +0000219 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000220 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000221 VK, Kind, Ex.take(), &BasePath,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000222 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000223 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000224 }
225
Sebastian Redlf53597f2009-03-15 17:47:39 +0000226 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000227}
228
John McCall79ab2c82011-02-14 18:34:10 +0000229/// Try to diagnose a failed overloaded cast. Returns true if
230/// diagnostics were emitted.
231static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
232 SourceRange range, Expr *src,
233 QualType destType) {
234 switch (CT) {
235 // These cast kinds don't consider user-defined conversions.
236 case CT_Const:
237 case CT_Reinterpret:
238 case CT_Dynamic:
239 return false;
240
241 // These do.
242 case CT_Static:
243 case CT_CStyle:
244 case CT_Functional:
245 break;
246 }
247
248 QualType srcType = src->getType();
249 if (!destType->isRecordType() && !srcType->isRecordType())
250 return false;
251
252 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
253 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000254 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
255 range)
256 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
257 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall79ab2c82011-02-14 18:34:10 +0000258 InitializationSequence sequence(S, entity, initKind, &src, 1);
259
Sebastian Redl383616c2011-06-05 12:23:28 +0000260 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000261 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) {
John McCall864c0412011-04-26 20:42:42 +0000308 if (src->getType() == S.Context.BoundMemberTy) {
309 (void) S.CheckPlaceholderExpr(src); // will always fail
310 return;
311 }
312
John McCall79ab2c82011-02-14 18:34:10 +0000313 if (msg == diag::err_bad_cxx_cast_generic &&
314 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
315 return;
316
317 S.Diag(opRange.getBegin(), msg) << castType
318 << src->getType() << destType << opRange << src->getSourceRange();
319}
320
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000321/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
322/// this removes one level of indirection from both types, provided that they're
323/// the same kind of pointer (plain or to-member). Unlike the Sema function,
324/// this one doesn't care if the two pointers-to-member don't point into the
325/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000326static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000327 const PointerType *T1PtrType = T1->getAs<PointerType>(),
328 *T2PtrType = T2->getAs<PointerType>();
329 if (T1PtrType && T2PtrType) {
330 T1 = T1PtrType->getPointeeType();
331 T2 = T2PtrType->getPointeeType();
332 return true;
333 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000334 const ObjCObjectPointerType *T1ObjCPtrType =
335 T1->getAs<ObjCObjectPointerType>(),
336 *T2ObjCPtrType =
337 T2->getAs<ObjCObjectPointerType>();
338 if (T1ObjCPtrType) {
339 if (T2ObjCPtrType) {
340 T1 = T1ObjCPtrType->getPointeeType();
341 T2 = T2ObjCPtrType->getPointeeType();
342 return true;
343 }
344 else if (T2PtrType) {
345 T1 = T1ObjCPtrType->getPointeeType();
346 T2 = T2PtrType->getPointeeType();
347 return true;
348 }
349 }
350 else if (T2ObjCPtrType) {
351 if (T1PtrType) {
352 T2 = T2ObjCPtrType->getPointeeType();
353 T1 = T1PtrType->getPointeeType();
354 return true;
355 }
356 }
357
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000358 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
359 *T2MPType = T2->getAs<MemberPointerType>();
360 if (T1MPType && T2MPType) {
361 T1 = T1MPType->getPointeeType();
362 T2 = T2MPType->getPointeeType();
363 return true;
364 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000365
366 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
367 *T2BPType = T2->getAs<BlockPointerType>();
368 if (T1BPType && T2BPType) {
369 T1 = T1BPType->getPointeeType();
370 T2 = T2BPType->getPointeeType();
371 return true;
372 }
373
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000374 return false;
375}
376
Sebastian Redldb647282009-01-27 23:18:31 +0000377/// CastsAwayConstness - Check if the pointer conversion from SrcType to
378/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
379/// the cast checkers. Both arguments must denote pointer (possibly to member)
380/// types.
John McCallf85e1932011-06-15 23:02:42 +0000381///
382/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
383///
384/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000385static bool
John McCallf85e1932011-06-15 23:02:42 +0000386CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
387 bool CheckCVR, bool CheckObjCLifetime) {
388 // If the only checking we care about is for Objective-C lifetime qualifiers,
389 // and we're not in ARC mode, there's nothing to check.
390 if (!CheckCVR && CheckObjCLifetime &&
391 !Self.Context.getLangOptions().ObjCAutoRefCount)
392 return false;
393
Sebastian Redldb647282009-01-27 23:18:31 +0000394 // Casting away constness is defined in C++ 5.2.11p8 with reference to
395 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
396 // the rules are non-trivial. So first we construct Tcv *...cv* as described
397 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000398 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
399 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000400 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000401 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
402 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000403 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000404
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000405 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
406 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000407 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000408
Douglas Gregord4c5f842011-04-15 17:59:54 +0000409 // Find the qualifiers. We only care about cvr-qualifiers for the
410 // purpose of this check, because other qualifiers (address spaces,
411 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000412 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000413 // Determine the relevant qualifiers at this level.
414 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000415 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000416 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000417
418 Qualifiers RetainedSrcQuals, RetainedDestQuals;
419 if (CheckCVR) {
420 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
421 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
422 }
423
424 if (CheckObjCLifetime &&
425 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
426 return true;
427
428 cv1.push_back(RetainedSrcQuals);
429 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000430 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000431 if (cv1.empty())
432 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000433
434 // Construct void pointers with those qualifiers (in reverse order of
435 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000436 QualType SrcConstruct = Self.Context.VoidTy;
437 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000438 ASTContext &Context = Self.Context;
439 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
440 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000441 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000442 SrcConstruct
443 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
444 DestConstruct
445 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000446 }
447
448 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000449 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000450 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000451 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
452 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000453}
454
Sebastian Redl26d85b12008-11-05 21:50:06 +0000455/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
456/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
457/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000458static void
John Wiegley429bb272011-04-08 18:41:53 +0000459CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000460 ExprValueKind &VK, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000461 const SourceRange &DestRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000462 CXXCastPath &BasePath) {
John Wiegley429bb272011-04-08 18:41:53 +0000463 QualType OrigDestType = DestType, OrigSrcType = SrcExpr.get()->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000464 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000465
466 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
467 // or "pointer to cv void".
468
469 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000470 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000471 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000472 if (DestPointer) {
473 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000474 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000475 DestPointee = DestReference->getPointeeType();
Douglas Gregordc843f22011-01-22 00:06:57 +0000476 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
477 : isa<RValueReferenceType>(DestReference) ? VK_XValue
478 : VK_RValue;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000479 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000480 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000481 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000482 return;
483 }
484
Ted Kremenek6217b802009-07-29 21:53:49 +0000485 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000486 if (DestPointee->isVoidType()) {
487 assert(DestPointer && "Reference to void is not possible");
488 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000489 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000490 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000491 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000492 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000493 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000494 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000495 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000496 return;
497 }
498
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000499 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
500 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000501 // an lvalue of a complete class type, [...]. If T is an rvalue reference
502 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000503 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000504 QualType SrcPointee;
505 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000507 SrcPointee = SrcPointer->getPointeeType();
508 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000509 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000510 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000511 return;
512 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000513 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000514 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000515 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000516 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000517 }
518 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000519 } else {
520 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000521 }
522
Ted Kremenek6217b802009-07-29 21:53:49 +0000523 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000524 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000525 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000526 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley429bb272011-04-08 18:41:53 +0000527 << SrcExpr.get()->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000528 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000529 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000530 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000531 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000532 return;
533 }
534
535 assert((DestPointer || DestReference) &&
536 "Bad destination non-ptr/ref slipped through.");
537 assert((DestRecord || DestPointee->isVoidType()) &&
538 "Bad destination pointee slipped through.");
539 assert(SrcRecord && "Bad source pointee slipped through.");
540
541 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
542 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000543 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000544 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000545 return;
546 }
547
548 // C++ 5.2.7p3: If the type of v is the same as the required result type,
549 // [except for cv].
550 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000551 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000552 return;
553 }
554
555 // C++ 5.2.7p5
556 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000557 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000558 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
559 OpRange.getBegin(), OpRange,
560 &BasePath))
561 return;
562
John McCall2de56d12010-08-25 11:45:40 +0000563 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000564
565 // If we are casting to or through a virtual base class, we need a
566 // vtable.
567 if (Self.BasePathInvolvesVirtualBase(BasePath))
568 Self.MarkVTableUsed(OpRange.getBegin(),
569 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000570 return;
571 }
572
573 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000574 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000575 assert(SrcDecl && "Definition missing");
576 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000577 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000578 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000579 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000580 Self.MarkVTableUsed(OpRange.getBegin(),
581 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000582
583 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000584 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000585}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000586
587/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
588/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
589/// like this:
590/// const char *str = "literal";
591/// legacy_function(const_cast\<char*\>(str));
592void
John Wiegley429bb272011-04-08 18:41:53 +0000593CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump1eb44332009-09-09 15:08:12 +0000594 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCallf89e55a2010-11-18 06:31:45 +0000595 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000596 if (VK == VK_RValue) {
597 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
598 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
599 return;
600 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000601
602 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000603 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000604 && msg != 0)
605 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000606 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000607}
608
609/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
610/// valid.
611/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
612/// like this:
613/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
614void
John Wiegley429bb272011-04-08 18:41:53 +0000615CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000616 ExprValueKind &VK, const SourceRange &OpRange,
617 const SourceRange &DestRange, CastKind &Kind) {
618 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000619 if (VK == VK_RValue) {
620 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
621 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
622 return;
623 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000624
625 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000626 TryCastResult tcr =
627 TryReinterpretCast(Self, SrcExpr, DestType,
628 /*CStyle*/false, OpRange, msg, Kind);
629 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000630 {
John Wiegley429bb272011-04-08 18:41:53 +0000631 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
632 return;
633 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000634 //FIXME: &f<int>; is overloaded and resolvable
635 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000636 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000637 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000638 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000639
John McCall79ab2c82011-02-14 18:34:10 +0000640 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000641 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000642 }
John McCallf85e1932011-06-15 23:02:42 +0000643 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianaf975172011-06-21 17:38:29 +0000644 Expr *Exp = SrcExpr.get();
Fariborz Jahaniancccd6de2011-06-21 18:19:51 +0000645 // Note that Exp does not change with CCK_OtherCast cat type
John McCallf85e1932011-06-15 23:02:42 +0000646 Self.CheckObjCARCConversion(OpRange, DestType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +0000647 Exp, Sema::CCK_OtherCast);
John McCallf85e1932011-06-15 23:02:42 +0000648 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000649}
650
651
652/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
653/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
654/// implicit conversions explicit and getting rid of data loss warnings.
655void
John Wiegley429bb272011-04-08 18:41:53 +0000656CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000657 ExprValueKind &VK, const SourceRange &OpRange,
658 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000659 // This test is outside everything else because it's the only case where
660 // a non-lvalue-reference target type does not lead to decay.
661 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000662 if (DestType->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000663 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
664 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
665 return;
666 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000667 ExprResult SingleFunctionExpression =
John Wiegley429bb272011-04-08 18:41:53 +0000668 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000669 false, // Decay Function to ptr
670 true, // Complain
671 OpRange, DestType, diag::err_bad_static_cast_overload);
672 if (SingleFunctionExpression.isUsable())
673 {
John Wiegley429bb272011-04-08 18:41:53 +0000674 SrcExpr = SingleFunctionExpression;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000675 Kind = CK_ToVoid;
676 }
677 }
678 else
679 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000680 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000681 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000682
John McCallf89e55a2010-11-18 06:31:45 +0000683 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000684 if (VK == VK_RValue && !DestType->isRecordType()) {
685 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
686 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
687 return;
688 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000689
690 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000691 TryCastResult tcr
692 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
693 Kind, BasePath);
694 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000695 if (SrcExpr.isInvalid())
696 return;
697 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
698 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000699 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000700 << oe->getName() << DestType << OpRange
701 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000702 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000703 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000704 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000705 }
John McCallf85e1932011-06-15 23:02:42 +0000706 } else if (tcr == TC_Success) {
707 if (Kind == CK_BitCast)
708 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
Fariborz Jahanianaf975172011-06-21 17:38:29 +0000709 if (Self.getLangOptions().ObjCAutoRefCount) {
710 Expr *Exp = SrcExpr.get();
Fariborz Jahaniancccd6de2011-06-21 18:19:51 +0000711 // Note that Exp does not change with CCK_OtherCast cat type
John McCallf85e1932011-06-15 23:02:42 +0000712 Self.CheckObjCARCConversion(OpRange, DestType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +0000713 Exp, Sema::CCK_OtherCast);
714 }
Douglas Gregor8e960432010-11-08 03:40:48 +0000715 }
John McCalle2b76882010-11-16 05:46:29 +0000716 else if (Kind == CK_BitCast)
John Wiegley429bb272011-04-08 18:41:53 +0000717 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000718}
719
720/// TryStaticCast - Check if a static cast can be performed, and do so if
721/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
722/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000723static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000724 QualType DestType,
725 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000726 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000727 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000728 CXXCastPath &BasePath) {
John McCallf85e1932011-06-15 23:02:42 +0000729 // Determine whether we have the semantics of a C-style cast.
730 bool CStyle
731 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
732
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000733 // The order the tests is not entirely arbitrary. There is one conversion
734 // that can be handled in two different ways. Given:
735 // struct A {};
736 // struct B : public A {
737 // B(); B(const A&);
738 // };
739 // const A &a = B();
740 // the cast static_cast<const B&>(a) could be seen as either a static
741 // reference downcast, or an explicit invocation of the user-defined
742 // conversion using B's conversion constructor.
743 // DR 427 specifies that the downcast is to be applied here.
744
745 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
746 // Done outside this function.
747
748 TryCastResult tcr;
749
750 // C++ 5.2.9p5, reference downcast.
751 // See the function for details.
752 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley429bb272011-04-08 18:41:53 +0000753 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000754 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000755 if (tcr != TC_NotApplicable)
756 return tcr;
757
Douglas Gregordc843f22011-01-22 00:06:57 +0000758 // C++0x [expr.static.cast]p3:
759 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
760 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley429bb272011-04-08 18:41:53 +0000761 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000762 msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000763 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000764 return tcr;
765
766 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
767 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000768 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000769 Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000770 if (SrcExpr.isInvalid())
771 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000772 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000773 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000774
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000775 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
776 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
777 // conversions, subject to further restrictions.
778 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
779 // of qualification conversions impossible.
780 // In the CStyle case, the earlier attempt to const_cast should have taken
781 // care of reverse qualification conversions.
782
John Wiegley429bb272011-04-08 18:41:53 +0000783 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000784
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000785 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000786 // converted to an integral type. [...] A value of a scoped enumeration type
787 // can also be explicitly converted to a floating-point type [...].
788 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
789 if (Enum->getDecl()->isScoped()) {
790 if (DestType->isBooleanType()) {
791 Kind = CK_IntegralToBoolean;
792 return TC_Success;
793 } else if (DestType->isIntegralType(Self.Context)) {
794 Kind = CK_IntegralCast;
795 return TC_Success;
796 } else if (DestType->isRealFloatingType()) {
797 Kind = CK_IntegralToFloating;
798 return TC_Success;
799 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000800 }
801 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000802
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000803 // Reverse integral promotion/conversion. All such conversions are themselves
804 // again integral promotions or conversions and are thus already handled by
805 // p2 (TryDirectInitialization above).
806 // (Note: any data loss warnings should be suppressed.)
807 // The exception is the reverse of enum->integer, i.e. integer->enum (and
808 // enum->enum). See also C++ 5.2.9p7.
809 // The same goes for reverse floating point promotion/conversion and
810 // floating-integral conversions. Again, only floating->enum is relevant.
811 if (DestType->isEnumeralType()) {
812 if (SrcType->isComplexType() || SrcType->isVectorType()) {
813 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000814 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCall2de56d12010-08-25 11:45:40 +0000815 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000816 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000817 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000818 }
819
820 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
821 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000822 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000823 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000824 if (tcr != TC_NotApplicable)
825 return tcr;
826
827 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
828 // conversion. C++ 5.2.9p9 has additional information.
829 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000830 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000831 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000832 if (tcr != TC_NotApplicable)
833 return tcr;
834
835 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
836 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
837 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000838 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000839 QualType SrcPointee = SrcPointer->getPointeeType();
840 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000841 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000842 QualType DestPointee = DestPointer->getPointeeType();
843 if (DestPointee->isIncompleteOrObjectType()) {
844 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +0000845 // to a qualifier violation. Note that we permit Objective-C lifetime
846 // and GC qualifier mismatches here.
847 if (!CStyle) {
848 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
849 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
850 DestPointeeQuals.removeObjCGCAttr();
851 DestPointeeQuals.removeObjCLifetime();
852 SrcPointeeQuals.removeObjCGCAttr();
853 SrcPointeeQuals.removeObjCLifetime();
854 if (DestPointeeQuals != SrcPointeeQuals &&
855 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
856 msg = diag::err_bad_cxx_cast_qualifiers_away;
857 return TC_Failed;
858 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000859 }
John McCall2de56d12010-08-25 11:45:40 +0000860 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000861 return TC_Success;
862 }
863 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000864 else if (DestType->isObjCObjectPointerType()) {
865 // allow both c-style cast and static_cast of objective-c pointers as
866 // they are pervasive.
John McCall2de56d12010-08-25 11:45:40 +0000867 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000868 return TC_Success;
869 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000870 else if (CStyle && DestType->isBlockPointerType()) {
871 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000872 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000873 return TC_Success;
874 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000875 }
876 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000877 // Allow arbitray objective-c pointer conversion with static casts.
878 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000879 DestType->isObjCObjectPointerType()) {
880 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000881 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000882 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000883
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000884 // We tried everything. Everything! Nothing works! :-(
885 return TC_NotApplicable;
886}
887
888/// Tests whether a conversion according to N2844 is valid.
889TryCastResult
890TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000891 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
892 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000893 // C++0x [expr.static.cast]p3:
894 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
895 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000896 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000897 if (!R)
898 return TC_NotApplicable;
899
Douglas Gregordc843f22011-01-22 00:06:57 +0000900 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000901 return TC_NotApplicable;
902
903 // Because we try the reference downcast before this function, from now on
904 // this is the only cast possibility, so we issue an error if we fail now.
905 // FIXME: Should allow casting away constness if CStyle.
906 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000907 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +0000908 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000909 QualType FromType = SrcExpr->getType();
910 QualType ToType = R->getPointeeType();
911 if (CStyle) {
912 FromType = FromType.getUnqualifiedType();
913 ToType = ToType.getUnqualifiedType();
914 }
915
Douglas Gregor393896f2009-11-05 13:06:35 +0000916 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000917 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +0000918 DerivedToBase, ObjCConversion,
919 ObjCLifetimeConversion)
920 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000921 msg = diag::err_bad_lvalue_to_rvalue_cast;
922 return TC_Failed;
923 }
924
Douglas Gregor88b22a42011-01-25 16:13:26 +0000925 if (DerivedToBase) {
926 Kind = CK_DerivedToBase;
927 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
928 /*DetectVirtual=*/true);
929 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
930 return TC_NotApplicable;
931
932 Self.BuildBasePathArray(Paths, BasePath);
933 } else
934 Kind = CK_NoOp;
935
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000936 return TC_Success;
937}
938
939/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
940TryCastResult
941TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
942 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000943 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000944 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000945 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
946 // cast to type "reference to cv2 D", where D is a class derived from B,
947 // if a valid standard conversion from "pointer to D" to "pointer to B"
948 // exists, cv2 >= cv1, and B is not a virtual base class of D.
949 // In addition, DR54 clarifies that the base must be accessible in the
950 // current context. Although the wording of DR54 only applies to the pointer
951 // variant of this rule, the intent is clearly for it to apply to the this
952 // conversion as well.
953
Ted Kremenek6217b802009-07-29 21:53:49 +0000954 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000955 if (!DestReference) {
956 return TC_NotApplicable;
957 }
958 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +0000959 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000960 // We know the left side is an lvalue reference, so we can suggest a reason.
961 msg = diag::err_bad_cxx_cast_rvalue;
962 return TC_NotApplicable;
963 }
964
965 QualType DestPointee = DestReference->getPointeeType();
966
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000967 return TryStaticDowncast(Self,
968 Self.Context.getCanonicalType(SrcExpr->getType()),
969 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000970 OpRange, SrcExpr->getType(), DestType, msg, Kind,
971 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000972}
973
974/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
975TryCastResult
976TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000977 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000978 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000979 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000980 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
981 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
982 // is a class derived from B, if a valid standard conversion from "pointer
983 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
984 // class of D.
985 // In addition, DR54 clarifies that the base must be accessible in the
986 // current context.
987
Ted Kremenek6217b802009-07-29 21:53:49 +0000988 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000989 if (!DestPointer) {
990 return TC_NotApplicable;
991 }
992
Ted Kremenek6217b802009-07-29 21:53:49 +0000993 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000994 if (!SrcPointer) {
995 msg = diag::err_bad_static_cast_pointer_nonpointer;
996 return TC_NotApplicable;
997 }
998
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000999 return TryStaticDowncast(Self,
1000 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1001 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001002 CStyle, OpRange, SrcType, DestType, msg, Kind,
1003 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001004}
1005
1006/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1007/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001008/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001009TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001010TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001011 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001012 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001013 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001014 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00001015 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1016 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001017 return TC_NotApplicable;
1018
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001019 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001020 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001021 return TC_NotApplicable;
1022 }
1023
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001024 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001025 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001026 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1027 return TC_NotApplicable;
1028 }
1029
1030 // Target type does derive from source type. Now we're serious. If an error
1031 // appears now, it's not ignored.
1032 // This may not be entirely in line with the standard. Take for example:
1033 // struct A {};
1034 // struct B : virtual A {
1035 // B(A&);
1036 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001037 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001038 // void f()
1039 // {
1040 // (void)static_cast<const B&>(*((A*)0));
1041 // }
1042 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1043 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1044 // However, both GCC and Comeau reject this example, and accepting it would
1045 // mean more complex code if we're to preserve the nice error message.
1046 // FIXME: Being 100% compliant here would be nice to have.
1047
1048 // Must preserve cv, as always, unless we're in C-style mode.
1049 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001050 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001051 return TC_Failed;
1052 }
1053
1054 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1055 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1056 // that it builds the paths in reverse order.
1057 // To sum up: record all paths to the base and build a nice string from
1058 // them. Use it to spice up the error message.
1059 if (!Paths.isRecordingPaths()) {
1060 Paths.clear();
1061 Paths.setRecordingPaths(true);
1062 Self.IsDerivedFrom(DestType, SrcType, Paths);
1063 }
1064 std::string PathDisplayStr;
1065 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001066 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001067 PI != PE; ++PI) {
1068 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1069 // We haven't displayed a path to this particular base
1070 // class subobject yet.
1071 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001072 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1073 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001074 EI != EE; ++EI)
1075 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001076 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001077 }
1078 }
1079
1080 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001081 << QualType(SrcType).getUnqualifiedType()
1082 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001083 << PathDisplayStr << OpRange;
1084 msg = 0;
1085 return TC_Failed;
1086 }
1087
1088 if (Paths.getDetectedVirtual() != 0) {
1089 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1090 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1091 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1092 msg = 0;
1093 return TC_Failed;
1094 }
1095
John McCall417d39f2011-02-14 23:21:33 +00001096 if (!CStyle) {
1097 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1098 SrcType, DestType,
1099 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001100 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001101 case Sema::AR_accessible:
1102 case Sema::AR_delayed: // be optimistic
1103 case Sema::AR_dependent: // be optimistic
1104 break;
1105
1106 case Sema::AR_inaccessible:
1107 msg = 0;
1108 return TC_Failed;
1109 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001110 }
1111
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001112 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001113 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001114 return TC_Success;
1115}
1116
1117/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1118/// C++ 5.2.9p9 is valid:
1119///
1120/// An rvalue of type "pointer to member of D of type cv1 T" can be
1121/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1122/// where B is a base class of D [...].
1123///
1124TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001125TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001126 QualType DestType, bool CStyle,
1127 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001128 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001129 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001130 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001131 if (!DestMemPtr)
1132 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001133
1134 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001135 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001136 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001137 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001138 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001139 FoundOverload)) {
1140 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1141 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1142 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1143 WasOverloadedFunction = true;
1144 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001145 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001146
Ted Kremenek6217b802009-07-29 21:53:49 +00001147 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001148 if (!SrcMemPtr) {
1149 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1150 return TC_NotApplicable;
1151 }
1152
1153 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001154 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1155 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001156 return TC_NotApplicable;
1157
1158 // B base of D
1159 QualType SrcClass(SrcMemPtr->getClass(), 0);
1160 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001161 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001162 /*DetectVirtual=*/true);
1163 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1164 return TC_NotApplicable;
1165 }
1166
1167 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +00001168 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001169 Paths.clear();
1170 Paths.setRecordingPaths(true);
1171 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1172 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001173 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001174 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1175 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1176 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1177 msg = 0;
1178 return TC_Failed;
1179 }
1180
1181 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1182 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1183 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1184 msg = 0;
1185 return TC_Failed;
1186 }
1187
John McCall417d39f2011-02-14 23:21:33 +00001188 if (!CStyle) {
1189 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1190 DestClass, SrcClass,
1191 Paths.front(),
1192 diag::err_upcast_to_inaccessible_base)) {
1193 case Sema::AR_accessible:
1194 case Sema::AR_delayed:
1195 case Sema::AR_dependent:
1196 // Optimistically assume that the delayed and dependent cases
1197 // will work out.
1198 break;
1199
1200 case Sema::AR_inaccessible:
1201 msg = 0;
1202 return TC_Failed;
1203 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001204 }
1205
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001206 if (WasOverloadedFunction) {
1207 // Resolve the address of the overloaded function again, this time
1208 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001209 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001210 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001211 true,
1212 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001213 if (!Fn) {
1214 msg = 0;
1215 return TC_Failed;
1216 }
1217
John McCall6bb80172010-03-30 21:47:33 +00001218 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001219 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001220 msg = 0;
1221 return TC_Failed;
1222 }
1223 }
1224
Anders Carlssoncee22422010-04-24 19:22:20 +00001225 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001226 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001227 return TC_Success;
1228}
1229
1230/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1231/// is valid:
1232///
1233/// An expression e can be explicitly converted to a type T using a
1234/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1235TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001236TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001237 Sema::CheckedConversionKind CCK,
1238 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001239 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +00001240 if (DestType->isRecordType()) {
1241 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1242 diag::err_bad_dynamic_cast_incomplete)) {
1243 msg = 0;
1244 return TC_Failed;
1245 }
1246 }
Douglas Gregord6e44a32010-04-16 22:09:46 +00001247
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001248 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1249 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001250 = (CCK == Sema::CCK_CStyleCast)
1251 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1252 : (CCK == Sema::CCK_FunctionalCast)
1253 ? InitializationKind::CreateFunctionalCast(OpRange)
1254 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001255 Expr *SrcExprRaw = SrcExpr.get();
1256 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001257
1258 // At this point of CheckStaticCast, if the destination is a reference,
1259 // or the expression is an overload expression this has to work.
1260 // There is no other way that works.
1261 // On the other hand, if we're checking a C-style cast, we've still got
1262 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001263 bool CStyle
1264 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001265 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001266 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001267
John McCall60d7b3a2010-08-24 06:29:42 +00001268 ExprResult Result
John Wiegley429bb272011-04-08 18:41:53 +00001269 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001270 if (Result.isInvalid()) {
1271 msg = 0;
1272 return TC_Failed;
1273 }
1274
Douglas Gregord6e44a32010-04-16 22:09:46 +00001275 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001276 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001277 else
John McCall2de56d12010-08-25 11:45:40 +00001278 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001279
John Wiegley429bb272011-04-08 18:41:53 +00001280 SrcExpr = move(Result);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001281 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001282}
1283
1284/// TryConstCast - See if a const_cast from source to destination is allowed,
1285/// and perform it if it is.
1286static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1287 bool CStyle, unsigned &msg) {
1288 DestType = Self.Context.getCanonicalType(DestType);
1289 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001290 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1291 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001292 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1293 // is C-style, static_cast might find a way, so we simply suggest a
1294 // message and tell the parent to keep searching.
1295 msg = diag::err_bad_cxx_cast_rvalue;
1296 return TC_NotApplicable;
1297 }
1298
1299 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1300 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1301 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1302 SrcType = Self.Context.getPointerType(SrcType);
1303 }
1304
1305 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1306 // the rules for const_cast are the same as those used for pointers.
1307
John McCalld425d2b2010-05-18 09:35:29 +00001308 if (!DestType->isPointerType() &&
1309 !DestType->isMemberPointerType() &&
1310 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001311 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1312 // was a reference type, we converted it to a pointer above.
1313 // The status of rvalue references isn't entirely clear, but it looks like
1314 // conversion to them is simply invalid.
1315 // C++ 5.2.11p3: For two pointer types [...]
1316 if (!CStyle)
1317 msg = diag::err_bad_const_cast_dest;
1318 return TC_NotApplicable;
1319 }
1320 if (DestType->isFunctionPointerType() ||
1321 DestType->isMemberFunctionPointerType()) {
1322 // Cannot cast direct function pointers.
1323 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1324 // T is the ultimate pointee of source and target type.
1325 if (!CStyle)
1326 msg = diag::err_bad_const_cast_dest;
1327 return TC_NotApplicable;
1328 }
1329 SrcType = Self.Context.getCanonicalType(SrcType);
1330
1331 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1332 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001333 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1334 // in multi-level pointers may change, but the level count must be the same,
1335 // as must be the final pointee type.
1336 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001337 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001338 Qualifiers SrcQuals, DestQuals;
1339 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1340 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1341
1342 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1343 // the other qualifiers (e.g., address spaces) are identical.
1344 SrcQuals.removeCVRQualifiers();
1345 DestQuals.removeCVRQualifiers();
1346 if (SrcQuals != DestQuals)
1347 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001348 }
1349
1350 // Since we're dealing in canonical types, the remainder must be the same.
1351 if (SrcType != DestType)
1352 return TC_NotApplicable;
1353
1354 return TC_Success;
1355}
1356
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001357// Checks for undefined behavior in reinterpret_cast.
1358// The cases that is checked for is:
1359// *reinterpret_cast<T*>(&a)
1360// reinterpret_cast<T&>(a)
1361// where accessing 'a' as type 'T' will result in undefined behavior.
1362void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1363 bool IsDereference,
1364 SourceRange Range) {
1365 unsigned DiagID = IsDereference ?
1366 diag::warn_pointer_indirection_from_incompatible_type :
1367 diag::warn_undefined_reinterpret_cast;
1368
1369 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
1370 Diagnostic::Ignored) {
1371 return;
1372 }
1373
1374 QualType SrcTy, DestTy;
1375 if (IsDereference) {
1376 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1377 return;
1378 }
1379 SrcTy = SrcType->getPointeeType();
1380 DestTy = DestType->getPointeeType();
1381 } else {
1382 if (!DestType->getAs<ReferenceType>()) {
1383 return;
1384 }
1385 SrcTy = SrcType;
1386 DestTy = DestType->getPointeeType();
1387 }
1388
1389 // Cast is compatible if the types are the same.
1390 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1391 return;
1392 }
1393 // or one of the types is a char or void type
1394 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1395 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1396 return;
1397 }
1398 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001399 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001400 return;
1401 }
1402
Douglas Gregor575a1c92011-05-20 16:38:50 +00001403 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001404 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1405 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1406 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1407 return;
1408 }
1409 }
1410
1411 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1412}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001413
John Wiegley429bb272011-04-08 18:41:53 +00001414static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001415 QualType DestType, bool CStyle,
1416 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001417 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001418 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001419 bool IsLValueCast = false;
1420
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001421 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001422 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001423
1424 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001425 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1426 if (SrcType == Self.Context.OverloadTy) {
1427 // ... unless foo<int> resolves to an lvalue unambiguously
1428 ExprResult SingleFunctionExpr =
John Wiegley429bb272011-04-08 18:41:53 +00001429 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001430 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1431 );
1432 if (SingleFunctionExpr.isUsable()) {
John Wiegley429bb272011-04-08 18:41:53 +00001433 SrcExpr = move(SingleFunctionExpr);
1434 SrcType = SrcExpr.get()->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001435 }
1436 else
1437 return TC_NotApplicable;
1438 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001439
Ted Kremenek6217b802009-07-29 21:53:49 +00001440 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001441 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00001442 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregor575d2a32011-01-22 00:19:52 +00001443 // Cannot cast non-lvalue to lvalue reference type. See the similar
1444 // comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001445 msg = diag::err_bad_cxx_cast_rvalue;
1446 return TC_NotApplicable;
1447 }
1448
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001449 if (!CStyle) {
1450 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1451 /*isDereference=*/false, OpRange);
1452 }
1453
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001454 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1455 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1456 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001457
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001458 const char *inappropriate = 0;
1459 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001460 case OK_Ordinary:
1461 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001462 case OK_BitField: inappropriate = "bit-field"; break;
1463 case OK_VectorComponent: inappropriate = "vector element"; break;
1464 case OK_ObjCProperty: inappropriate = "property expression"; break;
1465 }
1466 if (inappropriate) {
1467 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1468 << inappropriate << DestType
1469 << OpRange << SrcExpr.get()->getSourceRange();
1470 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001471 return TC_NotApplicable;
1472 }
1473
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001474 // This code does this transformation for the checked types.
1475 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1476 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001477
Douglas Gregore39a3892010-07-13 23:17:26 +00001478 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001479 }
1480
1481 // Canonicalize source for comparison.
1482 SrcType = Self.Context.getCanonicalType(SrcType);
1483
Ted Kremenek6217b802009-07-29 21:53:49 +00001484 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1485 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001486 if (DestMemPtr && SrcMemPtr) {
1487 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1488 // can be explicitly converted to an rvalue of type "pointer to member
1489 // of Y of type T2" if T1 and T2 are both function types or both object
1490 // types.
1491 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1492 SrcMemPtr->getPointeeType()->isFunctionType())
1493 return TC_NotApplicable;
1494
1495 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1496 // constness.
1497 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1498 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001499 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1500 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001501 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001502 return TC_Failed;
1503 }
1504
Charles Davisf231df32010-08-16 05:30:44 +00001505 // Don't allow casting between member pointers of different sizes.
1506 if (Self.Context.getTypeSize(DestMemPtr) !=
1507 Self.Context.getTypeSize(SrcMemPtr)) {
1508 msg = diag::err_bad_cxx_cast_member_pointer_size;
1509 return TC_Failed;
1510 }
1511
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001512 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001513 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001514 return TC_Success;
1515 }
1516
1517 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001518 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001519 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1520 // type large enough to hold it. A value of std::nullptr_t can be
1521 // converted to an integral type; the conversion has the same meaning
1522 // and validity as a conversion of (void*)0 to the integral type.
1523 if (Self.Context.getTypeSize(SrcType) >
1524 Self.Context.getTypeSize(DestType)) {
1525 msg = diag::err_bad_reinterpret_cast_small_int;
1526 return TC_Failed;
1527 }
John McCall2de56d12010-08-25 11:45:40 +00001528 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001529 return TC_Success;
1530 }
1531
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001532 bool destIsVector = DestType->isVectorType();
1533 bool srcIsVector = SrcType->isVectorType();
1534 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001535 // FIXME: Should this also apply to floating point types?
1536 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1537 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001538
1539 // Check if this is a cast between a vector and something else.
1540 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1541 !(srcIsVector && destIsVector))
1542 return TC_NotApplicable;
1543
1544 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001545 if (Self.Context.getTypeSize(SrcType)
1546 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001547 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001548 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001549 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001550
1551 if (destIsScalar)
1552 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1553 else if (srcIsScalar)
1554 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1555 else
1556 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1557
1558 return TC_Failed;
1559 }
1560
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001561 bool destIsPtr = DestType->isAnyPointerType() ||
1562 DestType->isBlockPointerType();
1563 bool srcIsPtr = SrcType->isAnyPointerType() ||
1564 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001565 if (!destIsPtr && !srcIsPtr) {
1566 // Except for std::nullptr_t->integer and lvalue->reference, which are
1567 // handled above, at least one of the two arguments must be a pointer.
1568 return TC_NotApplicable;
1569 }
1570
1571 if (SrcType == DestType) {
1572 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1573 // restrictions, a cast to the same type is allowed. The intent is not
1574 // entirely clear here, since all other paragraphs explicitly forbid casts
1575 // to the same type. However, the behavior of compilers is pretty consistent
1576 // on this point: allow same-type conversion if the involved types are
1577 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001578 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001579 return TC_Success;
1580 }
1581
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001582 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001583 assert(srcIsPtr && "One type must be a pointer");
1584 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001585 // type large enough to hold it; except in Microsoft mode, where the
1586 // integral type size doesn't matter.
1587 if ((Self.Context.getTypeSize(SrcType) >
1588 Self.Context.getTypeSize(DestType)) &&
1589 !Self.getLangOptions().Microsoft) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001590 msg = diag::err_bad_reinterpret_cast_small_int;
1591 return TC_Failed;
1592 }
John McCall2de56d12010-08-25 11:45:40 +00001593 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001594 return TC_Success;
1595 }
1596
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001597 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001598 assert(destIsPtr && "One type must be a pointer");
1599 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1600 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001601 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1602 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001603 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001604 return TC_Success;
1605 }
1606
1607 if (!destIsPtr || !srcIsPtr) {
1608 // With the valid non-pointer conversions out of the way, we can be even
1609 // more stringent.
1610 return TC_NotApplicable;
1611 }
1612
1613 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1614 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001615 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1616 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001617 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001618 return TC_Failed;
1619 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001620
1621 // Cannot convert between block pointers and Objective-C object pointers.
1622 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1623 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1624 return TC_NotApplicable;
1625
1626 // Any pointer can be cast to an Objective-C pointer type with a C-style
1627 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001628 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001629 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001630 return TC_Success;
1631 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001632
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001633 // Not casting away constness, so the only remaining check is for compatible
1634 // pointer categories.
John McCall2de56d12010-08-25 11:45:40 +00001635 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001636
1637 if (SrcType->isFunctionPointerType()) {
1638 if (DestType->isFunctionPointerType()) {
1639 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1640 // a pointer to a function of a different type.
1641 return TC_Success;
1642 }
1643
1644 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1645 // an object type or vice versa is conditionally-supported.
1646 // Compilers support it in C++03 too, though, because it's necessary for
1647 // casting the return value of dlsym() and GetProcAddress().
1648 // FIXME: Conditionally-supported behavior should be configurable in the
1649 // TargetInfo or similar.
1650 if (!Self.getLangOptions().CPlusPlus0x)
1651 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1652 return TC_Success;
1653 }
1654
1655 if (DestType->isFunctionPointerType()) {
1656 // See above.
1657 if (!Self.getLangOptions().CPlusPlus0x)
1658 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1659 return TC_Success;
1660 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001661
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001662 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1663 // a pointer to an object of different type.
1664 // Void pointers are not specified, but supported by every compiler out there.
1665 // So we finish by allowing everything that remains - it's got to be two
1666 // object pointers.
1667 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001668}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001669
John Wiegley429bb272011-04-08 18:41:53 +00001670ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001671Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00001672 Expr *CastExpr, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001673 CXXCastPath &BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001674 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001675 // This test is outside everything else because it's the only case where
1676 // a non-lvalue-reference target type does not lead to decay.
1677 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001678 if (CastTy->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001679 Kind = CK_ToVoid;
1680
John Wiegley429bb272011-04-08 18:41:53 +00001681 ExprResult CastExprRes = IgnoredValueConversions(CastExpr);
1682 if (CastExprRes.isInvalid())
1683 return ExprError();
1684 CastExpr = CastExprRes.take();
John McCallfb8721c2011-04-10 19:13:55 +00001685
John McCall864c0412011-04-26 20:42:42 +00001686 if (CastExpr->getType() == Context.BoundMemberTy)
1687 return CheckPlaceholderExpr(CastExpr); // will always fail
1688
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001689 if (CastExpr->getType() == Context.OverloadTy) {
1690 ExprResult SingleFunctionExpr =
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001691 ResolveAndFixSingleFunctionTemplateSpecialization(
1692 CastExpr, /* Decay Function to ptr */ false,
1693 /* Complain */ true, R, CastTy,
1694 diag::err_bad_cstyle_cast_overload);
John McCallfb8721c2011-04-10 19:13:55 +00001695 if (SingleFunctionExpr.isInvalid())
1696 return ExprError();
1697 CastExpr = SingleFunctionExpr.take();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001698 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001699
John McCallfb8721c2011-04-10 19:13:55 +00001700 assert(!CastExpr->getType()->isPlaceholderType());
1701
John Wiegley429bb272011-04-08 18:41:53 +00001702 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00001703 }
1704
John McCall9b4b9d62010-11-30 02:05:44 +00001705 // Make sure we determine the value kind before we bail out for
1706 // dependent types.
1707 VK = Expr::getValueKindForType(CastTy);
1708
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001709 // If the type is dependent, we won't do any other semantic analysis now.
John McCalldaa8e4e2010-11-15 09:13:47 +00001710 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1711 Kind = CK_Dependent;
John Wiegley429bb272011-04-08 18:41:53 +00001712 return Owned(CastExpr);
John McCalldaa8e4e2010-11-15 09:13:47 +00001713 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001714
John Wiegley429bb272011-04-08 18:41:53 +00001715 if (VK == VK_RValue && !CastTy->isRecordType()) {
1716 ExprResult CastExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
1717 if (CastExprRes.isInvalid())
1718 return ExprError();
1719 CastExpr = CastExprRes.take();
1720 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001721
John McCallfb8721c2011-04-10 19:13:55 +00001722 // AltiVec vector initialization with a single literal.
1723 if (const VectorType *vecTy = CastTy->getAs<VectorType>())
1724 if (vecTy->getVectorKind() == VectorType::AltiVecVector
1725 && (CastExpr->getType()->isIntegerType()
1726 || CastExpr->getType()->isFloatingType())) {
1727 Kind = CK_VectorSplat;
1728 return Owned(CastExpr);
1729 }
1730
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001731 // C++ [expr.cast]p5: The conversions performed by
1732 // - a const_cast,
1733 // - a static_cast,
1734 // - a static_cast followed by a const_cast,
1735 // - a reinterpret_cast, or
1736 // - a reinterpret_cast followed by a const_cast,
1737 // can be performed using the cast notation of explicit type conversion.
1738 // [...] If a conversion can be interpreted in more than one of the ways
1739 // listed above, the interpretation that appears first in the list is used,
1740 // even if a cast resulting from that interpretation is ill-formed.
1741 // In plain language, this means trying a const_cast ...
1742 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001743 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1744 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001745 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001746 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001747
John McCallf85e1932011-06-15 23:02:42 +00001748 Sema::CheckedConversionKind CCK
1749 = FunctionalStyle? Sema::CCK_FunctionalCast
1750 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001751 if (tcr == TC_NotApplicable) {
1752 // ... or if that is not possible, a static_cast, ignoring const, ...
John Wiegley429bb272011-04-08 18:41:53 +00001753 ExprResult CastExprRes = Owned(CastExpr);
John McCallf85e1932011-06-15 23:02:42 +00001754 tcr = TryStaticCast(*this, CastExprRes, CastTy, CCK, R, msg, Kind,
1755 BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00001756 if (CastExprRes.isInvalid())
1757 return ExprError();
1758 CastExpr = CastExprRes.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001759 if (tcr == TC_NotApplicable) {
1760 // ... and finally a reinterpret_cast, ignoring const.
John Wiegley429bb272011-04-08 18:41:53 +00001761 CastExprRes = Owned(CastExpr);
Richard Trieu32ac00d2011-04-16 01:09:30 +00001762 tcr = TryReinterpretCast(*this, CastExprRes, CastTy, /*CStyle*/true, R,
1763 msg, Kind);
John Wiegley429bb272011-04-08 18:41:53 +00001764 if (CastExprRes.isInvalid())
1765 return ExprError();
1766 CastExpr = CastExprRes.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001767 }
1768 }
1769
John McCallf85e1932011-06-15 23:02:42 +00001770 if (getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1771 CheckObjCARCConversion(R, CastTy, CastExpr, CCK);
1772
Nick Lewycky43328e92010-11-09 00:19:31 +00001773 if (tcr != TC_Success && msg != 0) {
1774 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001775 DeclAccessPair Found;
John Wiegley429bb272011-04-08 18:41:53 +00001776 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregor8e960432010-11-08 03:40:48 +00001777 CastTy,
1778 /* Complain */ true,
1779 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001780
Richard Trieu32ac00d2011-04-16 01:09:30 +00001781 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001782 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001783
Nick Lewycky43328e92010-11-09 00:19:31 +00001784 } else {
John McCall79ab2c82011-02-14 18:34:10 +00001785 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1786 R, CastExpr, CastTy);
Douglas Gregor8e960432010-11-08 03:40:48 +00001787 }
1788 }
John McCalle2b76882010-11-16 05:46:29 +00001789 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00001790 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001791
John Wiegley429bb272011-04-08 18:41:53 +00001792 if (tcr != TC_Success)
1793 return ExprError();
1794
1795 return Owned(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001796}