blob: c492c2ac7dec573732744d662b73e3dfffa1d7db [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
25static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema);
26
Sebastian Redl9cc11e72009-07-25 15:41:38 +000027enum TryCastResult {
28 TC_NotApplicable, ///< The cast method is not applicable.
29 TC_Success, ///< The cast method is appropriate and successful.
30 TC_Failed ///< The cast method is appropriate, but failed. A
31 ///< diagnostic has been emitted.
32};
33
34enum CastType {
35 CT_Const, ///< const_cast
36 CT_Static, ///< static_cast
37 CT_Reinterpret, ///< reinterpret_cast
38 CT_Dynamic, ///< dynamic_cast
39 CT_CStyle, ///< (Type)expr
40 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000041};
42
Douglas Gregor8e960432010-11-08 03:40:48 +000043
44
45
Sebastian Redl37d6de32008-11-08 13:00:26 +000046static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000047 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000048 const SourceRange &OpRange,
49 const SourceRange &DestRange);
50static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000051 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000052 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000053 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000054 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000055static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000056 ExprValueKind &VK,
Anders Carlssoncdb61972009-08-07 22:21:05 +000057 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +000058 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000059 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000060static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000061 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000062 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000063 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000064 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000065 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000066
67static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
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);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000104static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&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
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000112static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000113 QualType DestType, bool CStyle,
114 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000115 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000116 CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000117static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000118 QualType DestType, bool CStyle,
119 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000120 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000121 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000122 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000123static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
124 bool CStyle, unsigned &msg);
125static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
126 QualType DestType, bool CStyle,
127 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000128 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000129 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000130
Sebastian Redl26d85b12008-11-05 21:50:06 +0000131/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000132ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000133Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallb3d87482010-08-24 05:47:05 +0000134 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000135 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000136 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000137 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000138
John McCall9d125032010-01-15 18:39:57 +0000139 TypeSourceInfo *DestTInfo;
140 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
141 if (!DestTInfo)
142 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000143
144 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
145 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
146 SourceRange(LParenLoc, RParenLoc));
147}
148
John McCall60d7b3a2010-08-24 06:29:42 +0000149ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000150Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallf312b1e2010-08-26 23:41:50 +0000151 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCallc89724c2010-01-15 19:13:16 +0000152 SourceRange AngleBrackets, SourceRange Parens) {
John McCallc89724c2010-01-15 19:13:16 +0000153 QualType DestType = DestTInfo->getType();
154
155 SourceRange OpRange(OpLoc, Parens.getEnd());
156 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000157
Douglas Gregor9103bb22008-12-17 22:52:20 +0000158 // If the type is dependent, we won't do the semantic analysis now.
159 // FIXME: should we check this in a more fine-grained manner?
160 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
161
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +0000162 if (Ex->isBoundMemberFunction(Context))
163 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
164 << Ex->getSourceRange();
165
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:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000174 if (!TypeDependent)
John McCallf89e55a2010-11-18 06:31:45 +0000175 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John McCallf871d0c2010-08-07 06:22:56 +0000176 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000177 DestType.getNonLValueExprType(Context),
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000178 VK, Ex, DestTInfo, OpLoc,
179 Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000180
Anders Carlsson714179b2009-08-02 19:07:59 +0000181 case tok::kw_dynamic_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000182 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000183 CXXCastPath BasePath;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000184 if (!TypeDependent)
John McCallf89e55a2010-11-18 06:31:45 +0000185 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
186 Kind, BasePath);
John McCallf871d0c2010-08-07 06:22:56 +0000187 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000188 DestType.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000189 VK, Kind, Ex, &BasePath, DestTInfo,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000190 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000191 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000192 case tok::kw_reinterpret_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000193 CastKind Kind = CK_Dependent;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000194 if (!TypeDependent)
John McCallf89e55a2010-11-18 06:31:45 +0000195 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John McCallf871d0c2010-08-07 06:22:56 +0000196 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000197 DestType.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000198 VK, Kind, Ex, 0,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000199 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000200 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000201 case tok::kw_static_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000202 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000203 CXXCastPath BasePath;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000204 if (!TypeDependent)
John McCallf89e55a2010-11-18 06:31:45 +0000205 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000206
John McCallf871d0c2010-08-07 06:22:56 +0000207 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000208 DestType.getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +0000209 VK, Kind, Ex, &BasePath,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000210 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000211 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000212 }
213
Sebastian Redlf53597f2009-03-15 17:47:39 +0000214 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215}
216
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000217/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
218/// this removes one level of indirection from both types, provided that they're
219/// the same kind of pointer (plain or to-member). Unlike the Sema function,
220/// this one doesn't care if the two pointers-to-member don't point into the
221/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000222static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000223 const PointerType *T1PtrType = T1->getAs<PointerType>(),
224 *T2PtrType = T2->getAs<PointerType>();
225 if (T1PtrType && T2PtrType) {
226 T1 = T1PtrType->getPointeeType();
227 T2 = T2PtrType->getPointeeType();
228 return true;
229 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000230 const ObjCObjectPointerType *T1ObjCPtrType =
231 T1->getAs<ObjCObjectPointerType>(),
232 *T2ObjCPtrType =
233 T2->getAs<ObjCObjectPointerType>();
234 if (T1ObjCPtrType) {
235 if (T2ObjCPtrType) {
236 T1 = T1ObjCPtrType->getPointeeType();
237 T2 = T2ObjCPtrType->getPointeeType();
238 return true;
239 }
240 else if (T2PtrType) {
241 T1 = T1ObjCPtrType->getPointeeType();
242 T2 = T2PtrType->getPointeeType();
243 return true;
244 }
245 }
246 else if (T2ObjCPtrType) {
247 if (T1PtrType) {
248 T2 = T2ObjCPtrType->getPointeeType();
249 T1 = T1PtrType->getPointeeType();
250 return true;
251 }
252 }
253
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000254 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
255 *T2MPType = T2->getAs<MemberPointerType>();
256 if (T1MPType && T2MPType) {
257 T1 = T1MPType->getPointeeType();
258 T2 = T2MPType->getPointeeType();
259 return true;
260 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000261
262 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
263 *T2BPType = T2->getAs<BlockPointerType>();
264 if (T1BPType && T2BPType) {
265 T1 = T1BPType->getPointeeType();
266 T2 = T2BPType->getPointeeType();
267 return true;
268 }
269
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000270 return false;
271}
272
Sebastian Redldb647282009-01-27 23:18:31 +0000273/// CastsAwayConstness - Check if the pointer conversion from SrcType to
274/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
275/// the cast checkers. Both arguments must denote pointer (possibly to member)
276/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000277static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000278CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000279 // Casting away constness is defined in C++ 5.2.11p8 with reference to
280 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
281 // the rules are non-trivial. So first we construct Tcv *...cv* as described
282 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000283 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
284 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000285 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000286 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
287 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000288 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000289
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000290 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
291 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000292 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000293
294 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000295 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson52647c62010-06-04 22:47:55 +0000296 Qualifiers SrcQuals;
297 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
298 cv1.push_back(SrcQuals);
299
300 Qualifiers DestQuals;
301 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
302 cv2.push_back(DestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000303 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000304 if (cv1.empty())
305 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306
307 // Construct void pointers with those qualifiers (in reverse order of
308 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000309 QualType SrcConstruct = Self.Context.VoidTy;
310 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000311 ASTContext &Context = Self.Context;
312 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
313 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000314 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000315 SrcConstruct
316 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
317 DestConstruct
318 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000319 }
320
321 // Test if they're compatible.
322 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000323 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000324}
325
Sebastian Redl26d85b12008-11-05 21:50:06 +0000326/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
327/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
328/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000329static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000330CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000331 ExprValueKind &VK, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000332 const SourceRange &DestRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000333 CXXCastPath &BasePath) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000334 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000335 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000336
337 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
338 // or "pointer to cv void".
339
340 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000341 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000342 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000343 if (DestPointer) {
344 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000345 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000346 DestPointee = DestReference->getPointeeType();
Douglas Gregordc843f22011-01-22 00:06:57 +0000347 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
348 : isa<RValueReferenceType>(DestReference) ? VK_XValue
349 : VK_RValue;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000350 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000351 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000352 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000353 return;
354 }
355
Ted Kremenek6217b802009-07-29 21:53:49 +0000356 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000357 if (DestPointee->isVoidType()) {
358 assert(DestPointer && "Reference to void is not possible");
359 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000360 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000361 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000362 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000363 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000364 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000365 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000366 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000367 return;
368 }
369
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000370 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
371 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000372 // an lvalue of a complete class type, [...]. If T is an rvalue reference
373 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000374 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000375 QualType SrcPointee;
376 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000377 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000378 SrcPointee = SrcPointer->getPointeeType();
379 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000380 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000381 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000382 return;
383 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000384 } else if (DestReference->isLValueReferenceType()) {
John McCall7eb0a9e2010-11-24 05:12:34 +0000385 if (!SrcExpr->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000386 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000387 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000388 }
389 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000390 } else {
391 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000392 }
393
Ted Kremenek6217b802009-07-29 21:53:49 +0000394 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000395 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000396 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000397 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000398 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000399 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000400 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000401 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000402 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000403 return;
404 }
405
406 assert((DestPointer || DestReference) &&
407 "Bad destination non-ptr/ref slipped through.");
408 assert((DestRecord || DestPointee->isVoidType()) &&
409 "Bad destination pointee slipped through.");
410 assert(SrcRecord && "Bad source pointee slipped through.");
411
412 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
413 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000414 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000415 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000416 return;
417 }
418
419 // C++ 5.2.7p3: If the type of v is the same as the required result type,
420 // [except for cv].
421 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000422 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000423 return;
424 }
425
426 // C++ 5.2.7p5
427 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000428 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000429 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
430 OpRange.getBegin(), OpRange,
431 &BasePath))
432 return;
433
John McCall2de56d12010-08-25 11:45:40 +0000434 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000435
436 // If we are casting to or through a virtual base class, we need a
437 // vtable.
438 if (Self.BasePathInvolvesVirtualBase(BasePath))
439 Self.MarkVTableUsed(OpRange.getBegin(),
440 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000441 return;
442 }
443
444 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000445 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000446 assert(SrcDecl && "Definition missing");
447 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000448 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000449 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000450 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000451 Self.MarkVTableUsed(OpRange.getBegin(),
452 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000453
454 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000455 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000456}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000457
458/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
459/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
460/// like this:
461/// const char *str = "literal";
462/// legacy_function(const_cast\<char*\>(str));
463void
John McCallf89e55a2010-11-18 06:31:45 +0000464CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump1eb44332009-09-09 15:08:12 +0000465 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCallf89e55a2010-11-18 06:31:45 +0000466 VK = Expr::getValueKindForType(DestType);
467 if (VK == VK_RValue)
Douglas Gregora873dfc2010-02-03 00:27:59 +0000468 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000469
470 unsigned msg = diag::err_bad_cxx_cast_generic;
471 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
472 && msg != 0)
473 Self.Diag(OpRange.getBegin(), msg) << CT_Const
474 << SrcExpr->getType() << DestType << OpRange;
475}
476
477/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
478/// valid.
479/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
480/// like this:
481/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
482void
483CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000484 ExprValueKind &VK, const SourceRange &OpRange,
485 const SourceRange &DestRange, CastKind &Kind) {
486 VK = Expr::getValueKindForType(DestType);
487 if (VK == VK_RValue)
Douglas Gregora873dfc2010-02-03 00:27:59 +0000488 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000489
490 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000491 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
492 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000493 != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000494 {
495 if (SrcExpr->getType() == Self.Context.OverloadTy)
496 {
497 //FIXME: &f<int>; is overloaded and resolvable
498 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
499 << OverloadExpr::find(SrcExpr).Expression->getName()
500 << DestType << OpRange;
501 NoteAllOverloadCandidates(SrcExpr, Self);
502
503 }
504 else
505 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000506 << SrcExpr->getType() << DestType << OpRange;
Douglas Gregor8e960432010-11-08 03:40:48 +0000507 }
508
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000509}
510
511
512/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
513/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
514/// implicit conversions explicit and getting rid of data loss warnings.
515void
516CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000517 ExprValueKind &VK, const SourceRange &OpRange,
518 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000519 // This test is outside everything else because it's the only case where
520 // a non-lvalue-reference target type does not lead to decay.
521 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000522 if (DestType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +0000523 Self.IgnoredValueConversions(SrcExpr);
John McCall2de56d12010-08-25 11:45:40 +0000524 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000525 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000526 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000527
John McCallf89e55a2010-11-18 06:31:45 +0000528 VK = Expr::getValueKindForType(DestType);
529 if (VK == VK_RValue && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000530 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000531
532 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000533 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000534 Kind, BasePath) != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000535 {
John McCalldaa8e4e2010-11-15 09:13:47 +0000536 if (SrcExpr->getType() == Self.Context.OverloadTy)
Douglas Gregor8e960432010-11-08 03:40:48 +0000537 {
538 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
539 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
540 << oe->getName() << DestType << OpRange << oe->getQualifierRange();
541 NoteAllOverloadCandidates(SrcExpr, Self);
542 }
543 else
544 Self.Diag(OpRange.getBegin(), msg) << CT_Static
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000545 << SrcExpr->getType() << DestType << OpRange;
Douglas Gregor8e960432010-11-08 03:40:48 +0000546 }
John McCalle2b76882010-11-16 05:46:29 +0000547 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +0000548 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000549}
550
551/// TryStaticCast - Check if a static cast can be performed, and do so if
552/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
553/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000554static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000555 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000556 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000557 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000558 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000559 // The order the tests is not entirely arbitrary. There is one conversion
560 // that can be handled in two different ways. Given:
561 // struct A {};
562 // struct B : public A {
563 // B(); B(const A&);
564 // };
565 // const A &a = B();
566 // the cast static_cast<const B&>(a) could be seen as either a static
567 // reference downcast, or an explicit invocation of the user-defined
568 // conversion using B's conversion constructor.
569 // DR 427 specifies that the downcast is to be applied here.
570
571 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
572 // Done outside this function.
573
574 TryCastResult tcr;
575
576 // C++ 5.2.9p5, reference downcast.
577 // See the function for details.
578 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000579 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000580 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000581 if (tcr != TC_NotApplicable)
582 return tcr;
583
Douglas Gregordc843f22011-01-22 00:06:57 +0000584 // C++0x [expr.static.cast]p3:
585 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
586 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000587 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, CStyle, Kind, BasePath,
588 msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000589 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000590 return tcr;
591
592 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
593 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000594 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000595 Kind);
Anders Carlsson3c31a392009-09-26 00:12:34 +0000596 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000597 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000598
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000599 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
600 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
601 // conversions, subject to further restrictions.
602 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
603 // of qualification conversions impossible.
604 // In the CStyle case, the earlier attempt to const_cast should have taken
605 // care of reverse qualification conversions.
606
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000607 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
608
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000609 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
610 // converted to an integral type.
611 if (Self.getLangOptions().CPlusPlus0x && SrcType->isEnumeralType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000612 assert(SrcType->getAs<EnumType>()->getDecl()->isScoped());
613 if (DestType->isBooleanType()) {
614 Kind = CK_IntegralToBoolean;
615 return TC_Success;
616 } else if (DestType->isIntegralType(Self.Context)) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000617 Kind = CK_IntegralCast;
618 return TC_Success;
619 }
620 }
621
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000622 // Reverse integral promotion/conversion. All such conversions are themselves
623 // again integral promotions or conversions and are thus already handled by
624 // p2 (TryDirectInitialization above).
625 // (Note: any data loss warnings should be suppressed.)
626 // The exception is the reverse of enum->integer, i.e. integer->enum (and
627 // enum->enum). See also C++ 5.2.9p7.
628 // The same goes for reverse floating point promotion/conversion and
629 // floating-integral conversions. Again, only floating->enum is relevant.
630 if (DestType->isEnumeralType()) {
631 if (SrcType->isComplexType() || SrcType->isVectorType()) {
632 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000633 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCall2de56d12010-08-25 11:45:40 +0000634 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000635 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000636 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000637 }
638
639 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
640 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000641 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000642 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000643 if (tcr != TC_NotApplicable)
644 return tcr;
645
646 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
647 // conversion. C++ 5.2.9p9 has additional information.
648 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000649 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000650 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000651 if (tcr != TC_NotApplicable)
652 return tcr;
653
654 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
655 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
656 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000657 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000658 QualType SrcPointee = SrcPointer->getPointeeType();
659 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000660 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000661 QualType DestPointee = DestPointer->getPointeeType();
662 if (DestPointee->isIncompleteOrObjectType()) {
663 // This is definitely the intended conversion, but it might fail due
664 // to a const violation.
665 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
666 msg = diag::err_bad_cxx_cast_const_away;
667 return TC_Failed;
668 }
John McCall2de56d12010-08-25 11:45:40 +0000669 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000670 return TC_Success;
671 }
672 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000673 else if (DestType->isObjCObjectPointerType()) {
674 // allow both c-style cast and static_cast of objective-c pointers as
675 // they are pervasive.
John McCall2de56d12010-08-25 11:45:40 +0000676 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000677 return TC_Success;
678 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000679 else if (CStyle && DestType->isBlockPointerType()) {
680 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000681 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000682 return TC_Success;
683 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000684 }
685 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000686 // Allow arbitray objective-c pointer conversion with static casts.
687 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000688 DestType->isObjCObjectPointerType()) {
689 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000690 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000691 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000692
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000693 // We tried everything. Everything! Nothing works! :-(
694 return TC_NotApplicable;
695}
696
697/// Tests whether a conversion according to N2844 is valid.
698TryCastResult
699TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000700 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
701 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000702 // C++0x [expr.static.cast]p3:
703 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
704 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000705 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000706 if (!R)
707 return TC_NotApplicable;
708
Douglas Gregordc843f22011-01-22 00:06:57 +0000709 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000710 return TC_NotApplicable;
711
712 // Because we try the reference downcast before this function, from now on
713 // this is the only cast possibility, so we issue an error if we fail now.
714 // FIXME: Should allow casting away constness if CStyle.
715 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000716 bool ObjCConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000717 QualType FromType = SrcExpr->getType();
718 QualType ToType = R->getPointeeType();
719 if (CStyle) {
720 FromType = FromType.getUnqualifiedType();
721 ToType = ToType.getUnqualifiedType();
722 }
723
Douglas Gregor393896f2009-11-05 13:06:35 +0000724 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000725 ToType, FromType,
Douglas Gregor569c3162010-08-07 11:51:51 +0000726 DerivedToBase, ObjCConversion) <
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000727 Sema::Ref_Compatible_With_Added_Qualification) {
728 msg = diag::err_bad_lvalue_to_rvalue_cast;
729 return TC_Failed;
730 }
731
Douglas Gregor88b22a42011-01-25 16:13:26 +0000732 if (DerivedToBase) {
733 Kind = CK_DerivedToBase;
734 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
735 /*DetectVirtual=*/true);
736 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
737 return TC_NotApplicable;
738
739 Self.BuildBasePathArray(Paths, BasePath);
740 } else
741 Kind = CK_NoOp;
742
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000743 return TC_Success;
744}
745
746/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
747TryCastResult
748TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
749 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000750 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000751 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000752 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
753 // cast to type "reference to cv2 D", where D is a class derived from B,
754 // if a valid standard conversion from "pointer to D" to "pointer to B"
755 // exists, cv2 >= cv1, and B is not a virtual base class of D.
756 // In addition, DR54 clarifies that the base must be accessible in the
757 // current context. Although the wording of DR54 only applies to the pointer
758 // variant of this rule, the intent is clearly for it to apply to the this
759 // conversion as well.
760
Ted Kremenek6217b802009-07-29 21:53:49 +0000761 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000762 if (!DestReference) {
763 return TC_NotApplicable;
764 }
765 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +0000766 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000767 // We know the left side is an lvalue reference, so we can suggest a reason.
768 msg = diag::err_bad_cxx_cast_rvalue;
769 return TC_NotApplicable;
770 }
771
772 QualType DestPointee = DestReference->getPointeeType();
773
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000774 return TryStaticDowncast(Self,
775 Self.Context.getCanonicalType(SrcExpr->getType()),
776 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000777 OpRange, SrcExpr->getType(), DestType, msg, Kind,
778 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000779}
780
781/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
782TryCastResult
783TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000784 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000785 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000786 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000787 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
788 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
789 // is a class derived from B, if a valid standard conversion from "pointer
790 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
791 // class of D.
792 // In addition, DR54 clarifies that the base must be accessible in the
793 // current context.
794
Ted Kremenek6217b802009-07-29 21:53:49 +0000795 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000796 if (!DestPointer) {
797 return TC_NotApplicable;
798 }
799
Ted Kremenek6217b802009-07-29 21:53:49 +0000800 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000801 if (!SrcPointer) {
802 msg = diag::err_bad_static_cast_pointer_nonpointer;
803 return TC_NotApplicable;
804 }
805
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000806 return TryStaticDowncast(Self,
807 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
808 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000809 CStyle, OpRange, SrcType, DestType, msg, Kind,
810 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000811}
812
813/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
814/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000815/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000816TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000817TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000818 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000819 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000820 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000821 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000822 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
823 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000824 return TC_NotApplicable;
825
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000826 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000827 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000828 return TC_NotApplicable;
829 }
830
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000831 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000832 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000833 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
834 return TC_NotApplicable;
835 }
836
837 // Target type does derive from source type. Now we're serious. If an error
838 // appears now, it's not ignored.
839 // This may not be entirely in line with the standard. Take for example:
840 // struct A {};
841 // struct B : virtual A {
842 // B(A&);
843 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000844 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000845 // void f()
846 // {
847 // (void)static_cast<const B&>(*((A*)0));
848 // }
849 // As far as the standard is concerned, p5 does not apply (A is virtual), so
850 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
851 // However, both GCC and Comeau reject this example, and accepting it would
852 // mean more complex code if we're to preserve the nice error message.
853 // FIXME: Being 100% compliant here would be nice to have.
854
855 // Must preserve cv, as always, unless we're in C-style mode.
856 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
857 msg = diag::err_bad_cxx_cast_const_away;
858 return TC_Failed;
859 }
860
861 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
862 // This code is analoguous to that in CheckDerivedToBaseConversion, except
863 // that it builds the paths in reverse order.
864 // To sum up: record all paths to the base and build a nice string from
865 // them. Use it to spice up the error message.
866 if (!Paths.isRecordingPaths()) {
867 Paths.clear();
868 Paths.setRecordingPaths(true);
869 Self.IsDerivedFrom(DestType, SrcType, Paths);
870 }
871 std::string PathDisplayStr;
872 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000873 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000874 PI != PE; ++PI) {
875 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
876 // We haven't displayed a path to this particular base
877 // class subobject yet.
878 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000879 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
880 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000881 EI != EE; ++EI)
882 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000883 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000884 }
885 }
886
887 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000888 << QualType(SrcType).getUnqualifiedType()
889 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000890 << PathDisplayStr << OpRange;
891 msg = 0;
892 return TC_Failed;
893 }
894
895 if (Paths.getDetectedVirtual() != 0) {
896 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
897 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
898 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
899 msg = 0;
900 return TC_Failed;
901 }
902
John McCall6b2accb2010-02-10 09:31:12 +0000903 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000904 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000905 Paths.front(),
906 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000907 msg = 0;
908 return TC_Failed;
909 }
910
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000911 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +0000912 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000913 return TC_Success;
914}
915
916/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
917/// C++ 5.2.9p9 is valid:
918///
919/// An rvalue of type "pointer to member of D of type cv1 T" can be
920/// converted to an rvalue of type "pointer to member of B of type cv2 T",
921/// where B is a base class of D [...].
922///
923TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000924TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
925 QualType DestType, bool CStyle,
926 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000927 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000928 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000929 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000930 if (!DestMemPtr)
931 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000932
933 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +0000934 DeclAccessPair FoundOverload;
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000935 if (SrcExpr->getType() == Self.Context.OverloadTy) {
936 if (FunctionDecl *Fn
937 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
938 FoundOverload)) {
939 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
940 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
941 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
942 WasOverloadedFunction = true;
943 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000944 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000945
Ted Kremenek6217b802009-07-29 21:53:49 +0000946 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000947 if (!SrcMemPtr) {
948 msg = diag::err_bad_static_cast_member_pointer_nonmp;
949 return TC_NotApplicable;
950 }
951
952 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000953 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
954 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000955 return TC_NotApplicable;
956
957 // B base of D
958 QualType SrcClass(SrcMemPtr->getClass(), 0);
959 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +0000960 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000961 /*DetectVirtual=*/true);
962 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
963 return TC_NotApplicable;
964 }
965
966 // 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 +0000967 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000968 Paths.clear();
969 Paths.setRecordingPaths(true);
970 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
971 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +0000972 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000973 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
974 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
975 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
976 msg = 0;
977 return TC_Failed;
978 }
979
980 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
981 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
982 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
983 msg = 0;
984 return TC_Failed;
985 }
986
John McCall6b2accb2010-02-10 09:31:12 +0000987 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedman0fab8cd2010-07-23 19:25:41 +0000988 DestClass, SrcClass,
John McCall58e6f342010-03-16 05:22:47 +0000989 Paths.front(),
990 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000991 msg = 0;
992 return TC_Failed;
993 }
994
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000995 if (WasOverloadedFunction) {
996 // Resolve the address of the overloaded function again, this time
997 // allowing complaints if something goes wrong.
998 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
999 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001000 true,
1001 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001002 if (!Fn) {
1003 msg = 0;
1004 return TC_Failed;
1005 }
1006
John McCall6bb80172010-03-30 21:47:33 +00001007 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001008 if (!SrcExpr) {
1009 msg = 0;
1010 return TC_Failed;
1011 }
1012 }
1013
Anders Carlssoncee22422010-04-24 19:22:20 +00001014 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001015 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001016 return TC_Success;
1017}
1018
1019/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1020/// is valid:
1021///
1022/// An expression e can be explicitly converted to a type T using a
1023/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1024TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001025TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001026 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001027 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +00001028 if (DestType->isRecordType()) {
1029 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1030 diag::err_bad_dynamic_cast_incomplete)) {
1031 msg = 0;
1032 return TC_Failed;
1033 }
1034 }
Douglas Gregord6e44a32010-04-16 22:09:46 +00001035
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001036 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1037 InitializationKind InitKind
Douglas Gregord6e44a32010-04-16 22:09:46 +00001038 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
1039 CStyle);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001040 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001041
1042 // At this point of CheckStaticCast, if the destination is a reference,
1043 // or the expression is an overload expression this has to work.
1044 // There is no other way that works.
1045 // On the other hand, if we're checking a C-style cast, we've still got
1046 // the reinterpret_cast way.
1047
Douglas Gregord6e44a32010-04-16 22:09:46 +00001048 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregor8e960432010-11-08 03:40:48 +00001049 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001050 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001051
John McCall60d7b3a2010-08-24 06:29:42 +00001052 ExprResult Result
John McCallf312b1e2010-08-26 23:41:50 +00001053 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001054 if (Result.isInvalid()) {
1055 msg = 0;
1056 return TC_Failed;
1057 }
1058
Douglas Gregord6e44a32010-04-16 22:09:46 +00001059 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001060 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001061 else
John McCall2de56d12010-08-25 11:45:40 +00001062 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001063
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001064 SrcExpr = Result.takeAs<Expr>();
1065 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001066}
1067
1068/// TryConstCast - See if a const_cast from source to destination is allowed,
1069/// and perform it if it is.
1070static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1071 bool CStyle, unsigned &msg) {
1072 DestType = Self.Context.getCanonicalType(DestType);
1073 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001074 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1075 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001076 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1077 // is C-style, static_cast might find a way, so we simply suggest a
1078 // message and tell the parent to keep searching.
1079 msg = diag::err_bad_cxx_cast_rvalue;
1080 return TC_NotApplicable;
1081 }
1082
1083 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1084 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1085 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1086 SrcType = Self.Context.getPointerType(SrcType);
1087 }
1088
1089 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1090 // the rules for const_cast are the same as those used for pointers.
1091
John McCalld425d2b2010-05-18 09:35:29 +00001092 if (!DestType->isPointerType() &&
1093 !DestType->isMemberPointerType() &&
1094 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001095 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1096 // was a reference type, we converted it to a pointer above.
1097 // The status of rvalue references isn't entirely clear, but it looks like
1098 // conversion to them is simply invalid.
1099 // C++ 5.2.11p3: For two pointer types [...]
1100 if (!CStyle)
1101 msg = diag::err_bad_const_cast_dest;
1102 return TC_NotApplicable;
1103 }
1104 if (DestType->isFunctionPointerType() ||
1105 DestType->isMemberFunctionPointerType()) {
1106 // Cannot cast direct function pointers.
1107 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1108 // T is the ultimate pointee of source and target type.
1109 if (!CStyle)
1110 msg = diag::err_bad_const_cast_dest;
1111 return TC_NotApplicable;
1112 }
1113 SrcType = Self.Context.getCanonicalType(SrcType);
1114
1115 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1116 // completely equal.
1117 // FIXME: const_cast should probably not be able to convert between pointers
1118 // to different address spaces.
1119 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1120 // in multi-level pointers may change, but the level count must be the same,
1121 // as must be the final pointee type.
1122 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001123 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +00001124 Qualifiers Quals;
1125 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1126 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 }
1128
1129 // Since we're dealing in canonical types, the remainder must be the same.
1130 if (SrcType != DestType)
1131 return TC_NotApplicable;
1132
1133 return TC_Success;
1134}
1135
Douglas Gregor8e960432010-11-08 03:40:48 +00001136
1137static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema)
1138{
1139
1140 assert(Expr->getType() == sema.Context.OverloadTy);
1141
1142 OverloadExpr::FindResult Ovl = OverloadExpr::find(Expr);
1143 OverloadExpr *const OvlExpr = Ovl.Expression;
1144
1145 for (UnresolvedSetIterator it = OvlExpr->decls_begin(),
1146 end = OvlExpr->decls_end(); it != end; ++it) {
1147 if ( FunctionTemplateDecl *ftd =
1148 dyn_cast<FunctionTemplateDecl>((*it)->getUnderlyingDecl()) )
1149 {
1150 sema.NoteOverloadCandidate(ftd->getTemplatedDecl());
1151 }
1152 else if ( FunctionDecl *f =
1153 dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl()) )
1154 {
1155 sema.NoteOverloadCandidate(f);
1156 }
1157 }
1158}
1159
1160
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001161static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1162 QualType DestType, bool CStyle,
1163 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001164 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001165 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001166 bool IsLValueCast = false;
1167
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001168 DestType = Self.Context.getCanonicalType(DestType);
1169 QualType SrcType = SrcExpr->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001170
1171 // Is the source an overloaded name? (i.e. &foo)
1172 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
John McCall404cd162010-11-13 01:35:44 +00001173 if (SrcType == Self.Context.OverloadTy)
Douglas Gregor8e960432010-11-08 03:40:48 +00001174 return TC_NotApplicable;
1175
Ted Kremenek6217b802009-07-29 21:53:49 +00001176 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001177 bool LValue = DestTypeTmp->isLValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001178 if (LValue && !SrcExpr->isLValue()) {
Douglas Gregor575d2a32011-01-22 00:19:52 +00001179 // Cannot cast non-lvalue to lvalue reference type. See the similar
1180 // comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001181 msg = diag::err_bad_cxx_cast_rvalue;
1182 return TC_NotApplicable;
1183 }
1184
1185 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1186 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1187 // built-in & and * operators.
1188 // This code does this transformation for the checked types.
1189 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1190 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001191
Douglas Gregore39a3892010-07-13 23:17:26 +00001192 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001193 }
1194
1195 // Canonicalize source for comparison.
1196 SrcType = Self.Context.getCanonicalType(SrcType);
1197
Ted Kremenek6217b802009-07-29 21:53:49 +00001198 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1199 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001200 if (DestMemPtr && SrcMemPtr) {
1201 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1202 // can be explicitly converted to an rvalue of type "pointer to member
1203 // of Y of type T2" if T1 and T2 are both function types or both object
1204 // types.
1205 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1206 SrcMemPtr->getPointeeType()->isFunctionType())
1207 return TC_NotApplicable;
1208
1209 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1210 // constness.
1211 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1212 // we accept it.
1213 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1214 msg = diag::err_bad_cxx_cast_const_away;
1215 return TC_Failed;
1216 }
1217
Charles Davisf231df32010-08-16 05:30:44 +00001218 // Don't allow casting between member pointers of different sizes.
1219 if (Self.Context.getTypeSize(DestMemPtr) !=
1220 Self.Context.getTypeSize(SrcMemPtr)) {
1221 msg = diag::err_bad_cxx_cast_member_pointer_size;
1222 return TC_Failed;
1223 }
1224
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001225 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001226 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001227 return TC_Success;
1228 }
1229
1230 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001231 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001232 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1233 // type large enough to hold it. A value of std::nullptr_t can be
1234 // converted to an integral type; the conversion has the same meaning
1235 // and validity as a conversion of (void*)0 to the integral type.
1236 if (Self.Context.getTypeSize(SrcType) >
1237 Self.Context.getTypeSize(DestType)) {
1238 msg = diag::err_bad_reinterpret_cast_small_int;
1239 return TC_Failed;
1240 }
John McCall2de56d12010-08-25 11:45:40 +00001241 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001242 return TC_Success;
1243 }
1244
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001245 bool destIsVector = DestType->isVectorType();
1246 bool srcIsVector = SrcType->isVectorType();
1247 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001248 // FIXME: Should this also apply to floating point types?
1249 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1250 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001251
1252 // Check if this is a cast between a vector and something else.
1253 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1254 !(srcIsVector && destIsVector))
1255 return TC_NotApplicable;
1256
1257 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001258 if (Self.Context.getTypeSize(SrcType)
1259 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001260 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001261 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001262 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001263
1264 if (destIsScalar)
1265 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1266 else if (srcIsScalar)
1267 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1268 else
1269 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1270
1271 return TC_Failed;
1272 }
1273
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001274 bool destIsPtr = DestType->isAnyPointerType() ||
1275 DestType->isBlockPointerType();
1276 bool srcIsPtr = SrcType->isAnyPointerType() ||
1277 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001278 if (!destIsPtr && !srcIsPtr) {
1279 // Except for std::nullptr_t->integer and lvalue->reference, which are
1280 // handled above, at least one of the two arguments must be a pointer.
1281 return TC_NotApplicable;
1282 }
1283
1284 if (SrcType == DestType) {
1285 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1286 // restrictions, a cast to the same type is allowed. The intent is not
1287 // entirely clear here, since all other paragraphs explicitly forbid casts
1288 // to the same type. However, the behavior of compilers is pretty consistent
1289 // on this point: allow same-type conversion if the involved types are
1290 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001291 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001292 return TC_Success;
1293 }
1294
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001295 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001296 assert(srcIsPtr && "One type must be a pointer");
1297 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1298 // type large enough to hold it.
1299 if (Self.Context.getTypeSize(SrcType) >
1300 Self.Context.getTypeSize(DestType)) {
1301 msg = diag::err_bad_reinterpret_cast_small_int;
1302 return TC_Failed;
1303 }
John McCall2de56d12010-08-25 11:45:40 +00001304 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001305 return TC_Success;
1306 }
1307
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001308 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001309 assert(destIsPtr && "One type must be a pointer");
1310 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1311 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001312 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1313 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001314 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001315 return TC_Success;
1316 }
1317
1318 if (!destIsPtr || !srcIsPtr) {
1319 // With the valid non-pointer conversions out of the way, we can be even
1320 // more stringent.
1321 return TC_NotApplicable;
1322 }
1323
1324 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1325 // The C-style cast operator can.
1326 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1327 msg = diag::err_bad_cxx_cast_const_away;
1328 return TC_Failed;
1329 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001330
1331 // Cannot convert between block pointers and Objective-C object pointers.
1332 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1333 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1334 return TC_NotApplicable;
1335
1336 // Any pointer can be cast to an Objective-C pointer type with a C-style
1337 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001338 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001339 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001340 return TC_Success;
1341 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001342
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001343 // Not casting away constness, so the only remaining check is for compatible
1344 // pointer categories.
John McCall2de56d12010-08-25 11:45:40 +00001345 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001346
1347 if (SrcType->isFunctionPointerType()) {
1348 if (DestType->isFunctionPointerType()) {
1349 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1350 // a pointer to a function of a different type.
1351 return TC_Success;
1352 }
1353
1354 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1355 // an object type or vice versa is conditionally-supported.
1356 // Compilers support it in C++03 too, though, because it's necessary for
1357 // casting the return value of dlsym() and GetProcAddress().
1358 // FIXME: Conditionally-supported behavior should be configurable in the
1359 // TargetInfo or similar.
1360 if (!Self.getLangOptions().CPlusPlus0x)
1361 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1362 return TC_Success;
1363 }
1364
1365 if (DestType->isFunctionPointerType()) {
1366 // See above.
1367 if (!Self.getLangOptions().CPlusPlus0x)
1368 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1369 return TC_Success;
1370 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001371
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001372 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1373 // a pointer to an object of different type.
1374 // Void pointers are not specified, but supported by every compiler out there.
1375 // So we finish by allowing everything that remains - it's got to be two
1376 // object pointers.
1377 return TC_Success;
1378}
1379
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001380bool
John McCallf89e55a2010-11-18 06:31:45 +00001381Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
1382 Expr *&CastExpr, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001383 CXXCastPath &BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001384 bool FunctionalStyle) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001385 if (CastExpr->isBoundMemberFunction(Context))
1386 return Diag(CastExpr->getLocStart(),
1387 diag::err_invalid_use_of_bound_member_func)
1388 << CastExpr->getSourceRange();
1389
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001390 // This test is outside everything else because it's the only case where
1391 // a non-lvalue-reference target type does not lead to decay.
1392 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001393 if (CastTy->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00001394 IgnoredValueConversions(CastExpr);
John McCall2de56d12010-08-25 11:45:40 +00001395 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001396 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001397 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001398
John McCall9b4b9d62010-11-30 02:05:44 +00001399 // Make sure we determine the value kind before we bail out for
1400 // dependent types.
1401 VK = Expr::getValueKindForType(CastTy);
1402
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001403 // If the type is dependent, we won't do any other semantic analysis now.
John McCalldaa8e4e2010-11-15 09:13:47 +00001404 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1405 Kind = CK_Dependent;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001406 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001407 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001408
John McCallf89e55a2010-11-18 06:31:45 +00001409 if (VK == VK_RValue && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001410 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001411
1412 // C++ [expr.cast]p5: The conversions performed by
1413 // - a const_cast,
1414 // - a static_cast,
1415 // - a static_cast followed by a const_cast,
1416 // - a reinterpret_cast, or
1417 // - a reinterpret_cast followed by a const_cast,
1418 // can be performed using the cast notation of explicit type conversion.
1419 // [...] If a conversion can be interpreted in more than one of the ways
1420 // listed above, the interpretation that appears first in the list is used,
1421 // even if a cast resulting from that interpretation is ill-formed.
1422 // In plain language, this means trying a const_cast ...
1423 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001424 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1425 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001426 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001427 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001428
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001429 if (tcr == TC_NotApplicable) {
1430 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001431 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1432 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001433 if (tcr == TC_NotApplicable) {
1434 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001435 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1436 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001437 }
1438 }
1439
Nick Lewycky43328e92010-11-09 00:19:31 +00001440 if (tcr != TC_Success && msg != 0) {
1441 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001442 DeclAccessPair Found;
Nick Lewycky43328e92010-11-09 00:19:31 +00001443 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregor8e960432010-11-08 03:40:48 +00001444 CastTy,
1445 /* Complain */ true,
1446 Found);
1447 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001448 (void)Fn;
1449 } else {
Douglas Gregor8e960432010-11-08 03:40:48 +00001450 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
1451 << CastExpr->getType() << CastTy << R;
1452 }
1453 }
John McCalle2b76882010-11-16 05:46:29 +00001454 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00001455 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001456
1457 return tcr != TC_Success;
1458}