blob: e57e89e4a48914ab4f20465e77b2ab7f2adf995f [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,
47 const SourceRange &OpRange,
48 const SourceRange &DestRange);
49static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
50 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000051 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000052 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000053static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000054 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +000055 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000056 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000057static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
58 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000059 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000060 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000061 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000062
63static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000064
65// The Try functions attempt a specific way of casting. If they succeed, they
66// return TC_Success. If their way of casting is not appropriate for the given
67// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
68// to emit if no other way succeeds. If their way of casting is appropriate but
69// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
70// they emit a specialized diagnostic.
71// All diagnostics returned by these functions must expect the same three
72// arguments:
73// %0: Cast Type (a value from the CastType enumeration)
74// %1: Source Type
75// %2: Destination Type
76static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
77 QualType DestType, unsigned &msg);
78static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000079 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
81 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000082 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000083 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000084static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
85 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000087 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000088 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000089 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000090static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
91 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000092 const SourceRange &OpRange,
93 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000094 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000095 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000096 CXXCastPath &BasePath);
Douglas Gregor4ce46c22010-03-07 23:24:59 +000097static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +000098 QualType SrcType,
99 QualType DestType,bool CStyle,
100 const SourceRange &OpRange,
101 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000102 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000103 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000104
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000105static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000106 QualType DestType, bool CStyle,
107 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000108 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000109 CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000110static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000111 QualType DestType, bool CStyle,
112 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000113 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000114 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000115 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000116static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
117 bool CStyle, unsigned &msg);
118static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
119 QualType DestType, bool CStyle,
120 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000121 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000122 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000123
Sebastian Redl26d85b12008-11-05 21:50:06 +0000124/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000125ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000126Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallb3d87482010-08-24 05:47:05 +0000127 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000128 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000129 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000130 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000131
John McCall9d125032010-01-15 18:39:57 +0000132 TypeSourceInfo *DestTInfo;
133 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
134 if (!DestTInfo)
135 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000136
137 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
138 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
139 SourceRange(LParenLoc, RParenLoc));
140}
141
John McCall60d7b3a2010-08-24 06:29:42 +0000142ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000143Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallf312b1e2010-08-26 23:41:50 +0000144 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCallc89724c2010-01-15 19:13:16 +0000145 SourceRange AngleBrackets, SourceRange Parens) {
John McCallc89724c2010-01-15 19:13:16 +0000146 QualType DestType = DestTInfo->getType();
147
148 SourceRange OpRange(OpLoc, Parens.getEnd());
149 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000150
Douglas Gregor9103bb22008-12-17 22:52:20 +0000151 // If the type is dependent, we won't do the semantic analysis now.
152 // FIXME: should we check this in a more fine-grained manner?
153 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
154
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +0000155 if (Ex->isBoundMemberFunction(Context))
156 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
157 << Ex->getSourceRange();
158
Sebastian Redl26d85b12008-11-05 21:50:06 +0000159 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000160 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000161
162 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000163 if (!TypeDependent)
164 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
John McCallf871d0c2010-08-07 06:22:56 +0000165 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000166 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000167 Ex, DestTInfo, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000168
Anders Carlsson714179b2009-08-02 19:07:59 +0000169 case tok::kw_dynamic_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000170 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000171 CXXCastPath BasePath;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000172 if (!TypeDependent)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000173 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
John McCallf871d0c2010-08-07 06:22:56 +0000174 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000175 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000176 Kind, Ex, &BasePath, DestTInfo,
177 OpLoc));
Anders Carlsson714179b2009-08-02 19:07:59 +0000178 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000179 case tok::kw_reinterpret_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000180 CastKind Kind = CK_Dependent;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000181 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000182 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
John McCallf871d0c2010-08-07 06:22:56 +0000183 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000184 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000185 Kind, Ex, 0,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000186 DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000187 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000188 case tok::kw_static_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000189 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000190 CXXCastPath BasePath;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000191 if (!TypeDependent)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000192 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000193
John McCallf871d0c2010-08-07 06:22:56 +0000194 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000195 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000196 Kind, Ex, &BasePath,
197 DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000198 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000199 }
200
Sebastian Redlf53597f2009-03-15 17:47:39 +0000201 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000202}
203
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000204/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
205/// this removes one level of indirection from both types, provided that they're
206/// the same kind of pointer (plain or to-member). Unlike the Sema function,
207/// this one doesn't care if the two pointers-to-member don't point into the
208/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000209static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000210 const PointerType *T1PtrType = T1->getAs<PointerType>(),
211 *T2PtrType = T2->getAs<PointerType>();
212 if (T1PtrType && T2PtrType) {
213 T1 = T1PtrType->getPointeeType();
214 T2 = T2PtrType->getPointeeType();
215 return true;
216 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000217 const ObjCObjectPointerType *T1ObjCPtrType =
218 T1->getAs<ObjCObjectPointerType>(),
219 *T2ObjCPtrType =
220 T2->getAs<ObjCObjectPointerType>();
221 if (T1ObjCPtrType) {
222 if (T2ObjCPtrType) {
223 T1 = T1ObjCPtrType->getPointeeType();
224 T2 = T2ObjCPtrType->getPointeeType();
225 return true;
226 }
227 else if (T2PtrType) {
228 T1 = T1ObjCPtrType->getPointeeType();
229 T2 = T2PtrType->getPointeeType();
230 return true;
231 }
232 }
233 else if (T2ObjCPtrType) {
234 if (T1PtrType) {
235 T2 = T2ObjCPtrType->getPointeeType();
236 T1 = T1PtrType->getPointeeType();
237 return true;
238 }
239 }
240
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000241 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
242 *T2MPType = T2->getAs<MemberPointerType>();
243 if (T1MPType && T2MPType) {
244 T1 = T1MPType->getPointeeType();
245 T2 = T2MPType->getPointeeType();
246 return true;
247 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000248
249 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
250 *T2BPType = T2->getAs<BlockPointerType>();
251 if (T1BPType && T2BPType) {
252 T1 = T1BPType->getPointeeType();
253 T2 = T2BPType->getPointeeType();
254 return true;
255 }
256
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000257 return false;
258}
259
Sebastian Redldb647282009-01-27 23:18:31 +0000260/// CastsAwayConstness - Check if the pointer conversion from SrcType to
261/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
262/// the cast checkers. Both arguments must denote pointer (possibly to member)
263/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000264static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000265CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000266 // Casting away constness is defined in C++ 5.2.11p8 with reference to
267 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
268 // the rules are non-trivial. So first we construct Tcv *...cv* as described
269 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000270 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
271 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000272 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000273 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
274 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000275 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000276
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000277 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
278 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000279 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280
281 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000282 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson52647c62010-06-04 22:47:55 +0000283 Qualifiers SrcQuals;
284 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
285 cv1.push_back(SrcQuals);
286
287 Qualifiers DestQuals;
288 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
289 cv2.push_back(DestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000291 if (cv1.empty())
292 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000293
294 // Construct void pointers with those qualifiers (in reverse order of
295 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000296 QualType SrcConstruct = Self.Context.VoidTy;
297 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000298 ASTContext &Context = Self.Context;
299 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
300 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000301 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000302 SrcConstruct
303 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
304 DestConstruct
305 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306 }
307
308 // Test if they're compatible.
309 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000310 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000311}
312
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
314/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
315/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000316static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000317CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
318 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000319 const SourceRange &DestRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000320 CXXCastPath &BasePath) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000322 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000323
324 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
325 // or "pointer to cv void".
326
327 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000328 const PointerType *DestPointer = DestType->getAs<PointerType>();
329 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000330 if (DestPointer) {
331 DestPointee = DestPointer->getPointeeType();
332 } else if (DestReference) {
333 DestPointee = DestReference->getPointeeType();
334 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000335 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000336 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000337 return;
338 }
339
Ted Kremenek6217b802009-07-29 21:53:49 +0000340 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000341 if (DestPointee->isVoidType()) {
342 assert(DestPointer && "Reference to void is not possible");
343 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000344 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000345 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000346 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000347 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000348 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000349 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000350 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000351 return;
352 }
353
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000354 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
355 // complete class type, [...]. If T is an lvalue reference type, v shall be
356 // an lvalue of a complete class type, [...]. If T is an rvalue reference
357 // type, v shall be an expression having a complete effective class type,
358 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000359
Sebastian Redl37d6de32008-11-08 13:00:26 +0000360 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000361 QualType SrcPointee;
362 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000363 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000364 SrcPointee = SrcPointer->getPointeeType();
365 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000366 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000367 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000368 return;
369 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000370 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000371 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000372 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000373 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000374 }
375 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000376 } else {
377 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000378 }
379
Ted Kremenek6217b802009-07-29 21:53:49 +0000380 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000381 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000382 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000383 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000384 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000385 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000386 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000387 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000388 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000389 return;
390 }
391
392 assert((DestPointer || DestReference) &&
393 "Bad destination non-ptr/ref slipped through.");
394 assert((DestRecord || DestPointee->isVoidType()) &&
395 "Bad destination pointee slipped through.");
396 assert(SrcRecord && "Bad source pointee slipped through.");
397
398 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
399 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000400 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000401 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000402 return;
403 }
404
405 // C++ 5.2.7p3: If the type of v is the same as the required result type,
406 // [except for cv].
407 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000408 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000409 return;
410 }
411
412 // C++ 5.2.7p5
413 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000414 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000415 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
416 OpRange.getBegin(), OpRange,
417 &BasePath))
418 return;
419
John McCall2de56d12010-08-25 11:45:40 +0000420 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000421
422 // If we are casting to or through a virtual base class, we need a
423 // vtable.
424 if (Self.BasePathInvolvesVirtualBase(BasePath))
425 Self.MarkVTableUsed(OpRange.getBegin(),
426 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000427 return;
428 }
429
430 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000431 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000432 assert(SrcDecl && "Definition missing");
433 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000434 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000435 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000436 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000437 Self.MarkVTableUsed(OpRange.getBegin(),
438 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000439
440 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000441 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000442}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000443
444/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
445/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
446/// like this:
447/// const char *str = "literal";
448/// legacy_function(const_cast\<char*\>(str));
449void
450CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000451 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000452 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000453 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000454
455 unsigned msg = diag::err_bad_cxx_cast_generic;
456 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
457 && msg != 0)
458 Self.Diag(OpRange.getBegin(), msg) << CT_Const
459 << SrcExpr->getType() << DestType << OpRange;
460}
461
462/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
463/// valid.
464/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
465/// like this:
466/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
467void
468CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000469 const SourceRange &OpRange, const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +0000470 CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000471 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000472 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000473
474 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000475 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
476 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000477 != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000478 {
479 if (SrcExpr->getType() == Self.Context.OverloadTy)
480 {
481 //FIXME: &f<int>; is overloaded and resolvable
482 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
483 << OverloadExpr::find(SrcExpr).Expression->getName()
484 << DestType << OpRange;
485 NoteAllOverloadCandidates(SrcExpr, Self);
486
487 }
488 else
489 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000490 << SrcExpr->getType() << DestType << OpRange;
Douglas Gregor8e960432010-11-08 03:40:48 +0000491 }
492
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000493}
494
495
496/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
497/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
498/// implicit conversions explicit and getting rid of data loss warnings.
499void
500CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall2de56d12010-08-25 11:45:40 +0000501 const SourceRange &OpRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000502 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000503 // This test is outside everything else because it's the only case where
504 // a non-lvalue-reference target type does not lead to decay.
505 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000506 if (DestType->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +0000507 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000508 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000509 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000510
Douglas Gregorb653c522009-11-06 01:14:41 +0000511 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000512 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000513
514 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000515 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000516 Kind, BasePath) != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000517 {
John McCalldaa8e4e2010-11-15 09:13:47 +0000518 if (SrcExpr->getType() == Self.Context.OverloadTy)
Douglas Gregor8e960432010-11-08 03:40:48 +0000519 {
520 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
521 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
522 << oe->getName() << DestType << OpRange << oe->getQualifierRange();
523 NoteAllOverloadCandidates(SrcExpr, Self);
524 }
525 else
526 Self.Diag(OpRange.getBegin(), msg) << CT_Static
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000527 << SrcExpr->getType() << DestType << OpRange;
Douglas Gregor8e960432010-11-08 03:40:48 +0000528 }
John McCalle2b76882010-11-16 05:46:29 +0000529 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +0000530 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000531}
532
533/// TryStaticCast - Check if a static cast can be performed, and do so if
534/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
535/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000536static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000537 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000538 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000539 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000540 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000541 // The order the tests is not entirely arbitrary. There is one conversion
542 // that can be handled in two different ways. Given:
543 // struct A {};
544 // struct B : public A {
545 // B(); B(const A&);
546 // };
547 // const A &a = B();
548 // the cast static_cast<const B&>(a) could be seen as either a static
549 // reference downcast, or an explicit invocation of the user-defined
550 // conversion using B's conversion constructor.
551 // DR 427 specifies that the downcast is to be applied here.
552
553 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
554 // Done outside this function.
555
556 TryCastResult tcr;
557
558 // C++ 5.2.9p5, reference downcast.
559 // See the function for details.
560 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000561 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000562 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000563 if (tcr != TC_NotApplicable)
564 return tcr;
565
566 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
567 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
568 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000569 if (tcr != TC_NotApplicable) {
John McCall2de56d12010-08-25 11:45:40 +0000570 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000571 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000572 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000573
574 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
575 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000576 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000577 Kind);
Anders Carlsson3c31a392009-09-26 00:12:34 +0000578 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000579 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000580
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000581 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
582 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
583 // conversions, subject to further restrictions.
584 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
585 // of qualification conversions impossible.
586 // In the CStyle case, the earlier attempt to const_cast should have taken
587 // care of reverse qualification conversions.
588
589 QualType OrigSrcType = SrcExpr->getType();
590
591 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
592
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000593 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
594 // converted to an integral type.
595 if (Self.getLangOptions().CPlusPlus0x && SrcType->isEnumeralType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000596 assert(SrcType->getAs<EnumType>()->getDecl()->isScoped());
597 if (DestType->isBooleanType()) {
598 Kind = CK_IntegralToBoolean;
599 return TC_Success;
600 } else if (DestType->isIntegralType(Self.Context)) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000601 Kind = CK_IntegralCast;
602 return TC_Success;
603 }
604 }
605
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000606 // Reverse integral promotion/conversion. All such conversions are themselves
607 // again integral promotions or conversions and are thus already handled by
608 // p2 (TryDirectInitialization above).
609 // (Note: any data loss warnings should be suppressed.)
610 // The exception is the reverse of enum->integer, i.e. integer->enum (and
611 // enum->enum). See also C++ 5.2.9p7.
612 // The same goes for reverse floating point promotion/conversion and
613 // floating-integral conversions. Again, only floating->enum is relevant.
614 if (DestType->isEnumeralType()) {
615 if (SrcType->isComplexType() || SrcType->isVectorType()) {
616 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000617 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCall2de56d12010-08-25 11:45:40 +0000618 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000619 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000620 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000621 }
622
623 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
624 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000625 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000626 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000627 if (tcr != TC_NotApplicable)
628 return tcr;
629
630 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
631 // conversion. C++ 5.2.9p9 has additional information.
632 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000633 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000634 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000635 if (tcr != TC_NotApplicable)
636 return tcr;
637
638 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
639 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
640 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000641 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000642 QualType SrcPointee = SrcPointer->getPointeeType();
643 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000644 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000645 QualType DestPointee = DestPointer->getPointeeType();
646 if (DestPointee->isIncompleteOrObjectType()) {
647 // This is definitely the intended conversion, but it might fail due
648 // to a const violation.
649 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
650 msg = diag::err_bad_cxx_cast_const_away;
651 return TC_Failed;
652 }
John McCall2de56d12010-08-25 11:45:40 +0000653 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000654 return TC_Success;
655 }
656 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000657 else if (DestType->isObjCObjectPointerType()) {
658 // allow both c-style cast and static_cast of objective-c pointers as
659 // they are pervasive.
John McCall2de56d12010-08-25 11:45:40 +0000660 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000661 return TC_Success;
662 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000663 else if (CStyle && DestType->isBlockPointerType()) {
664 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000665 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000666 return TC_Success;
667 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000668 }
669 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000670 // Allow arbitray objective-c pointer conversion with static casts.
671 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000672 DestType->isObjCObjectPointerType()) {
673 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000674 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000675 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000676
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000677 // We tried everything. Everything! Nothing works! :-(
678 return TC_NotApplicable;
679}
680
681/// Tests whether a conversion according to N2844 is valid.
682TryCastResult
683TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000685 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
686 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000687 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000688 if (!R)
689 return TC_NotApplicable;
690
691 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
692 return TC_NotApplicable;
693
694 // Because we try the reference downcast before this function, from now on
695 // this is the only cast possibility, so we issue an error if we fail now.
696 // FIXME: Should allow casting away constness if CStyle.
697 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000698 bool ObjCConversion;
Douglas Gregor393896f2009-11-05 13:06:35 +0000699 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
700 SrcExpr->getType(), R->getPointeeType(),
Douglas Gregor569c3162010-08-07 11:51:51 +0000701 DerivedToBase, ObjCConversion) <
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000702 Sema::Ref_Compatible_With_Added_Qualification) {
703 msg = diag::err_bad_lvalue_to_rvalue_cast;
704 return TC_Failed;
705 }
706
Douglas Gregorf0e0b172010-03-25 00:20:38 +0000707 // FIXME: We should probably have an AST node for lvalue-to-rvalue
708 // conversions.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000709 return TC_Success;
710}
711
712/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
713TryCastResult
714TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
715 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000716 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000717 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000718 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
719 // cast to type "reference to cv2 D", where D is a class derived from B,
720 // if a valid standard conversion from "pointer to D" to "pointer to B"
721 // exists, cv2 >= cv1, and B is not a virtual base class of D.
722 // In addition, DR54 clarifies that the base must be accessible in the
723 // current context. Although the wording of DR54 only applies to the pointer
724 // variant of this rule, the intent is clearly for it to apply to the this
725 // conversion as well.
726
Ted Kremenek6217b802009-07-29 21:53:49 +0000727 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000728 if (!DestReference) {
729 return TC_NotApplicable;
730 }
731 bool RValueRef = DestReference->isRValueReferenceType();
732 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
733 // We know the left side is an lvalue reference, so we can suggest a reason.
734 msg = diag::err_bad_cxx_cast_rvalue;
735 return TC_NotApplicable;
736 }
737
738 QualType DestPointee = DestReference->getPointeeType();
739
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000740 return TryStaticDowncast(Self,
741 Self.Context.getCanonicalType(SrcExpr->getType()),
742 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000743 OpRange, SrcExpr->getType(), DestType, msg, Kind,
744 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000745}
746
747/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
748TryCastResult
749TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000750 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000751 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000752 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000753 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
754 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
755 // is a class derived from B, if a valid standard conversion from "pointer
756 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
757 // class of D.
758 // In addition, DR54 clarifies that the base must be accessible in the
759 // current context.
760
Ted Kremenek6217b802009-07-29 21:53:49 +0000761 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000762 if (!DestPointer) {
763 return TC_NotApplicable;
764 }
765
Ted Kremenek6217b802009-07-29 21:53:49 +0000766 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000767 if (!SrcPointer) {
768 msg = diag::err_bad_static_cast_pointer_nonpointer;
769 return TC_NotApplicable;
770 }
771
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000772 return TryStaticDowncast(Self,
773 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
774 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000775 CStyle, OpRange, SrcType, DestType, msg, Kind,
776 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000777}
778
779/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
780/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000781/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000782TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000783TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000784 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000785 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000786 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000787 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000788 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
789 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000790 return TC_NotApplicable;
791
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000792 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000793 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000794 return TC_NotApplicable;
795 }
796
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000797 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000798 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000799 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
800 return TC_NotApplicable;
801 }
802
803 // Target type does derive from source type. Now we're serious. If an error
804 // appears now, it's not ignored.
805 // This may not be entirely in line with the standard. Take for example:
806 // struct A {};
807 // struct B : virtual A {
808 // B(A&);
809 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000810 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000811 // void f()
812 // {
813 // (void)static_cast<const B&>(*((A*)0));
814 // }
815 // As far as the standard is concerned, p5 does not apply (A is virtual), so
816 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
817 // However, both GCC and Comeau reject this example, and accepting it would
818 // mean more complex code if we're to preserve the nice error message.
819 // FIXME: Being 100% compliant here would be nice to have.
820
821 // Must preserve cv, as always, unless we're in C-style mode.
822 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
823 msg = diag::err_bad_cxx_cast_const_away;
824 return TC_Failed;
825 }
826
827 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
828 // This code is analoguous to that in CheckDerivedToBaseConversion, except
829 // that it builds the paths in reverse order.
830 // To sum up: record all paths to the base and build a nice string from
831 // them. Use it to spice up the error message.
832 if (!Paths.isRecordingPaths()) {
833 Paths.clear();
834 Paths.setRecordingPaths(true);
835 Self.IsDerivedFrom(DestType, SrcType, Paths);
836 }
837 std::string PathDisplayStr;
838 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000839 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000840 PI != PE; ++PI) {
841 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
842 // We haven't displayed a path to this particular base
843 // class subobject yet.
844 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
846 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000847 EI != EE; ++EI)
848 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000849 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000850 }
851 }
852
853 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000854 << QualType(SrcType).getUnqualifiedType()
855 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000856 << PathDisplayStr << OpRange;
857 msg = 0;
858 return TC_Failed;
859 }
860
861 if (Paths.getDetectedVirtual() != 0) {
862 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
863 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
864 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
865 msg = 0;
866 return TC_Failed;
867 }
868
John McCall6b2accb2010-02-10 09:31:12 +0000869 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000870 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000871 Paths.front(),
872 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000873 msg = 0;
874 return TC_Failed;
875 }
876
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000877 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +0000878 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000879 return TC_Success;
880}
881
882/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
883/// C++ 5.2.9p9 is valid:
884///
885/// An rvalue of type "pointer to member of D of type cv1 T" can be
886/// converted to an rvalue of type "pointer to member of B of type cv2 T",
887/// where B is a base class of D [...].
888///
889TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000890TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
891 QualType DestType, bool CStyle,
892 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000893 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000894 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000895 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000896 if (!DestMemPtr)
897 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000898
899 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +0000900 DeclAccessPair FoundOverload;
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000901 if (SrcExpr->getType() == Self.Context.OverloadTy) {
902 if (FunctionDecl *Fn
903 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
904 FoundOverload)) {
905 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
906 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
907 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
908 WasOverloadedFunction = true;
909 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000910 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000911
Ted Kremenek6217b802009-07-29 21:53:49 +0000912 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000913 if (!SrcMemPtr) {
914 msg = diag::err_bad_static_cast_member_pointer_nonmp;
915 return TC_NotApplicable;
916 }
917
918 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000919 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
920 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000921 return TC_NotApplicable;
922
923 // B base of D
924 QualType SrcClass(SrcMemPtr->getClass(), 0);
925 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +0000926 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000927 /*DetectVirtual=*/true);
928 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
929 return TC_NotApplicable;
930 }
931
932 // 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 +0000933 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000934 Paths.clear();
935 Paths.setRecordingPaths(true);
936 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
937 assert(StillOkay);
938 StillOkay = StillOkay;
939 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
940 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
941 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
942 msg = 0;
943 return TC_Failed;
944 }
945
946 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
947 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
948 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
949 msg = 0;
950 return TC_Failed;
951 }
952
John McCall6b2accb2010-02-10 09:31:12 +0000953 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedman0fab8cd2010-07-23 19:25:41 +0000954 DestClass, SrcClass,
John McCall58e6f342010-03-16 05:22:47 +0000955 Paths.front(),
956 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000957 msg = 0;
958 return TC_Failed;
959 }
960
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000961 if (WasOverloadedFunction) {
962 // Resolve the address of the overloaded function again, this time
963 // allowing complaints if something goes wrong.
964 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
965 DestType,
John McCall6bb80172010-03-30 21:47:33 +0000966 true,
967 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000968 if (!Fn) {
969 msg = 0;
970 return TC_Failed;
971 }
972
John McCall6bb80172010-03-30 21:47:33 +0000973 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000974 if (!SrcExpr) {
975 msg = 0;
976 return TC_Failed;
977 }
978 }
979
Anders Carlssoncee22422010-04-24 19:22:20 +0000980 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +0000981 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000982 return TC_Success;
983}
984
985/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
986/// is valid:
987///
988/// An expression e can be explicitly converted to a type T using a
989/// @c static_cast if the declaration "T t(e);" is well-formed [...].
990TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000991TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000992 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000993 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +0000994 if (DestType->isRecordType()) {
995 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
996 diag::err_bad_dynamic_cast_incomplete)) {
997 msg = 0;
998 return TC_Failed;
999 }
1000 }
Douglas Gregord6e44a32010-04-16 22:09:46 +00001001
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001002 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1003 InitializationKind InitKind
Douglas Gregord6e44a32010-04-16 22:09:46 +00001004 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
1005 CStyle);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001006 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001007
1008 // At this point of CheckStaticCast, if the destination is a reference,
1009 // or the expression is an overload expression this has to work.
1010 // There is no other way that works.
1011 // On the other hand, if we're checking a C-style cast, we've still got
1012 // the reinterpret_cast way.
1013
Douglas Gregord6e44a32010-04-16 22:09:46 +00001014 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregor8e960432010-11-08 03:40:48 +00001015 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001016 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001017
John McCall60d7b3a2010-08-24 06:29:42 +00001018 ExprResult Result
John McCallf312b1e2010-08-26 23:41:50 +00001019 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001020 if (Result.isInvalid()) {
1021 msg = 0;
1022 return TC_Failed;
1023 }
1024
Douglas Gregord6e44a32010-04-16 22:09:46 +00001025 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001026 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001027 else
John McCall2de56d12010-08-25 11:45:40 +00001028 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001029
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001030 SrcExpr = Result.takeAs<Expr>();
1031 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001032}
1033
1034/// TryConstCast - See if a const_cast from source to destination is allowed,
1035/// and perform it if it is.
1036static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1037 bool CStyle, unsigned &msg) {
1038 DestType = Self.Context.getCanonicalType(DestType);
1039 QualType SrcType = SrcExpr->getType();
1040 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +00001041 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001042 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1043 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1044 // is C-style, static_cast might find a way, so we simply suggest a
1045 // message and tell the parent to keep searching.
1046 msg = diag::err_bad_cxx_cast_rvalue;
1047 return TC_NotApplicable;
1048 }
1049
1050 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1051 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1052 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1053 SrcType = Self.Context.getPointerType(SrcType);
1054 }
1055
1056 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1057 // the rules for const_cast are the same as those used for pointers.
1058
John McCalld425d2b2010-05-18 09:35:29 +00001059 if (!DestType->isPointerType() &&
1060 !DestType->isMemberPointerType() &&
1061 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001062 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1063 // was a reference type, we converted it to a pointer above.
1064 // The status of rvalue references isn't entirely clear, but it looks like
1065 // conversion to them is simply invalid.
1066 // C++ 5.2.11p3: For two pointer types [...]
1067 if (!CStyle)
1068 msg = diag::err_bad_const_cast_dest;
1069 return TC_NotApplicable;
1070 }
1071 if (DestType->isFunctionPointerType() ||
1072 DestType->isMemberFunctionPointerType()) {
1073 // Cannot cast direct function pointers.
1074 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1075 // T is the ultimate pointee of source and target type.
1076 if (!CStyle)
1077 msg = diag::err_bad_const_cast_dest;
1078 return TC_NotApplicable;
1079 }
1080 SrcType = Self.Context.getCanonicalType(SrcType);
1081
1082 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1083 // completely equal.
1084 // FIXME: const_cast should probably not be able to convert between pointers
1085 // to different address spaces.
1086 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1087 // in multi-level pointers may change, but the level count must be the same,
1088 // as must be the final pointee type.
1089 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001090 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +00001091 Qualifiers Quals;
1092 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1093 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001094 }
1095
1096 // Since we're dealing in canonical types, the remainder must be the same.
1097 if (SrcType != DestType)
1098 return TC_NotApplicable;
1099
1100 return TC_Success;
1101}
1102
Douglas Gregor8e960432010-11-08 03:40:48 +00001103
1104static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema)
1105{
1106
1107 assert(Expr->getType() == sema.Context.OverloadTy);
1108
1109 OverloadExpr::FindResult Ovl = OverloadExpr::find(Expr);
1110 OverloadExpr *const OvlExpr = Ovl.Expression;
1111
1112 for (UnresolvedSetIterator it = OvlExpr->decls_begin(),
1113 end = OvlExpr->decls_end(); it != end; ++it) {
1114 if ( FunctionTemplateDecl *ftd =
1115 dyn_cast<FunctionTemplateDecl>((*it)->getUnderlyingDecl()) )
1116 {
1117 sema.NoteOverloadCandidate(ftd->getTemplatedDecl());
1118 }
1119 else if ( FunctionDecl *f =
1120 dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl()) )
1121 {
1122 sema.NoteOverloadCandidate(f);
1123 }
1124 }
1125}
1126
1127
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001128static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1129 QualType DestType, bool CStyle,
1130 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001131 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001132 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001133 bool IsLValueCast = false;
1134
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001135 DestType = Self.Context.getCanonicalType(DestType);
1136 QualType SrcType = SrcExpr->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001137
1138 // Is the source an overloaded name? (i.e. &foo)
1139 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
John McCall404cd162010-11-13 01:35:44 +00001140 if (SrcType == Self.Context.OverloadTy)
Douglas Gregor8e960432010-11-08 03:40:48 +00001141 return TC_NotApplicable;
1142
Ted Kremenek6217b802009-07-29 21:53:49 +00001143 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001144 bool LValue = DestTypeTmp->isLValueReferenceType();
1145 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1146 // Cannot cast non-lvalue to reference type. See the similar comment in
1147 // const_cast.
1148 msg = diag::err_bad_cxx_cast_rvalue;
1149 return TC_NotApplicable;
1150 }
1151
1152 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1153 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1154 // built-in & and * operators.
1155 // This code does this transformation for the checked types.
1156 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1157 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001158
Douglas Gregore39a3892010-07-13 23:17:26 +00001159 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001160 }
1161
1162 // Canonicalize source for comparison.
1163 SrcType = Self.Context.getCanonicalType(SrcType);
1164
Ted Kremenek6217b802009-07-29 21:53:49 +00001165 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1166 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001167 if (DestMemPtr && SrcMemPtr) {
1168 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1169 // can be explicitly converted to an rvalue of type "pointer to member
1170 // of Y of type T2" if T1 and T2 are both function types or both object
1171 // types.
1172 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1173 SrcMemPtr->getPointeeType()->isFunctionType())
1174 return TC_NotApplicable;
1175
1176 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1177 // constness.
1178 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1179 // we accept it.
1180 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1181 msg = diag::err_bad_cxx_cast_const_away;
1182 return TC_Failed;
1183 }
1184
Charles Davisf231df32010-08-16 05:30:44 +00001185 // Don't allow casting between member pointers of different sizes.
1186 if (Self.Context.getTypeSize(DestMemPtr) !=
1187 Self.Context.getTypeSize(SrcMemPtr)) {
1188 msg = diag::err_bad_cxx_cast_member_pointer_size;
1189 return TC_Failed;
1190 }
1191
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001192 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001193 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001194 return TC_Success;
1195 }
1196
1197 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001198 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001199 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1200 // type large enough to hold it. A value of std::nullptr_t can be
1201 // converted to an integral type; the conversion has the same meaning
1202 // and validity as a conversion of (void*)0 to the integral type.
1203 if (Self.Context.getTypeSize(SrcType) >
1204 Self.Context.getTypeSize(DestType)) {
1205 msg = diag::err_bad_reinterpret_cast_small_int;
1206 return TC_Failed;
1207 }
John McCall2de56d12010-08-25 11:45:40 +00001208 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001209 return TC_Success;
1210 }
1211
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001212 bool destIsVector = DestType->isVectorType();
1213 bool srcIsVector = SrcType->isVectorType();
1214 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001215 // FIXME: Should this also apply to floating point types?
1216 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1217 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001218
1219 // Check if this is a cast between a vector and something else.
1220 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1221 !(srcIsVector && destIsVector))
1222 return TC_NotApplicable;
1223
1224 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001225 if (Self.Context.getTypeSize(SrcType)
1226 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001227 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001228 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001229 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001230
1231 if (destIsScalar)
1232 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1233 else if (srcIsScalar)
1234 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1235 else
1236 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1237
1238 return TC_Failed;
1239 }
1240
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001241 bool destIsPtr = DestType->isAnyPointerType() ||
1242 DestType->isBlockPointerType();
1243 bool srcIsPtr = SrcType->isAnyPointerType() ||
1244 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001245 if (!destIsPtr && !srcIsPtr) {
1246 // Except for std::nullptr_t->integer and lvalue->reference, which are
1247 // handled above, at least one of the two arguments must be a pointer.
1248 return TC_NotApplicable;
1249 }
1250
1251 if (SrcType == DestType) {
1252 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1253 // restrictions, a cast to the same type is allowed. The intent is not
1254 // entirely clear here, since all other paragraphs explicitly forbid casts
1255 // to the same type. However, the behavior of compilers is pretty consistent
1256 // on this point: allow same-type conversion if the involved types are
1257 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001258 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001259 return TC_Success;
1260 }
1261
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001262 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001263 assert(srcIsPtr && "One type must be a pointer");
1264 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1265 // type large enough to hold it.
1266 if (Self.Context.getTypeSize(SrcType) >
1267 Self.Context.getTypeSize(DestType)) {
1268 msg = diag::err_bad_reinterpret_cast_small_int;
1269 return TC_Failed;
1270 }
John McCall2de56d12010-08-25 11:45:40 +00001271 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001272 return TC_Success;
1273 }
1274
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001275 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001276 assert(destIsPtr && "One type must be a pointer");
1277 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1278 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001279 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1280 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001281 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001282 return TC_Success;
1283 }
1284
1285 if (!destIsPtr || !srcIsPtr) {
1286 // With the valid non-pointer conversions out of the way, we can be even
1287 // more stringent.
1288 return TC_NotApplicable;
1289 }
1290
1291 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1292 // The C-style cast operator can.
1293 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1294 msg = diag::err_bad_cxx_cast_const_away;
1295 return TC_Failed;
1296 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001297
1298 // Cannot convert between block pointers and Objective-C object pointers.
1299 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1300 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1301 return TC_NotApplicable;
1302
1303 // Any pointer can be cast to an Objective-C pointer type with a C-style
1304 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001305 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001306 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001307 return TC_Success;
1308 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001309
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001310 // Not casting away constness, so the only remaining check is for compatible
1311 // pointer categories.
John McCall2de56d12010-08-25 11:45:40 +00001312 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001313
1314 if (SrcType->isFunctionPointerType()) {
1315 if (DestType->isFunctionPointerType()) {
1316 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1317 // a pointer to a function of a different type.
1318 return TC_Success;
1319 }
1320
1321 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1322 // an object type or vice versa is conditionally-supported.
1323 // Compilers support it in C++03 too, though, because it's necessary for
1324 // casting the return value of dlsym() and GetProcAddress().
1325 // FIXME: Conditionally-supported behavior should be configurable in the
1326 // TargetInfo or similar.
1327 if (!Self.getLangOptions().CPlusPlus0x)
1328 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1329 return TC_Success;
1330 }
1331
1332 if (DestType->isFunctionPointerType()) {
1333 // See above.
1334 if (!Self.getLangOptions().CPlusPlus0x)
1335 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1336 return TC_Success;
1337 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001338
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001339 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1340 // a pointer to an object of different type.
1341 // Void pointers are not specified, but supported by every compiler out there.
1342 // So we finish by allowing everything that remains - it's got to be two
1343 // object pointers.
1344 return TC_Success;
1345}
1346
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001347bool
1348Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00001349 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001350 CXXCastPath &BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001351 bool FunctionalStyle) {
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001352 if (CastExpr->isBoundMemberFunction(Context))
1353 return Diag(CastExpr->getLocStart(),
1354 diag::err_invalid_use_of_bound_member_func)
1355 << CastExpr->getSourceRange();
1356
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001357 // This test is outside everything else because it's the only case where
1358 // a non-lvalue-reference target type does not lead to decay.
1359 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001360 if (CastTy->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00001361 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001362 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001363 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001364
1365 // If the type is dependent, we won't do any other semantic analysis now.
John McCalldaa8e4e2010-11-15 09:13:47 +00001366 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1367 Kind = CK_Dependent;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001368 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001369 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001370
Douglas Gregorb653c522009-11-06 01:14:41 +00001371 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001372 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001373
1374 // C++ [expr.cast]p5: The conversions performed by
1375 // - a const_cast,
1376 // - a static_cast,
1377 // - a static_cast followed by a const_cast,
1378 // - a reinterpret_cast, or
1379 // - a reinterpret_cast followed by a const_cast,
1380 // can be performed using the cast notation of explicit type conversion.
1381 // [...] If a conversion can be interpreted in more than one of the ways
1382 // listed above, the interpretation that appears first in the list is used,
1383 // even if a cast resulting from that interpretation is ill-formed.
1384 // In plain language, this means trying a const_cast ...
1385 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001386 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1387 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001388 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001389 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001390
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001391 if (tcr == TC_NotApplicable) {
1392 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001393 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1394 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001395 if (tcr == TC_NotApplicable) {
1396 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001397 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1398 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001399 }
1400 }
1401
Nick Lewycky43328e92010-11-09 00:19:31 +00001402 if (tcr != TC_Success && msg != 0) {
1403 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001404 DeclAccessPair Found;
Nick Lewycky43328e92010-11-09 00:19:31 +00001405 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregor8e960432010-11-08 03:40:48 +00001406 CastTy,
1407 /* Complain */ true,
1408 Found);
1409 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001410 (void)Fn;
1411 } else {
Douglas Gregor8e960432010-11-08 03:40:48 +00001412 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
1413 << CastExpr->getType() << CastTy << R;
1414 }
1415 }
John McCalle2b76882010-11-16 05:46:29 +00001416 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00001417 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001418
1419 return tcr != TC_Success;
1420}