blob: 7b1e34a7c38c6523c37771a84fcdb0fc5709b969 [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
Sebastian Redl9cc11e72009-07-25 15:41:38 +000024enum TryCastResult {
25 TC_NotApplicable, ///< The cast method is not applicable.
26 TC_Success, ///< The cast method is appropriate and successful.
27 TC_Failed ///< The cast method is appropriate, but failed. A
28 ///< diagnostic has been emitted.
29};
30
31enum CastType {
32 CT_Const, ///< const_cast
33 CT_Static, ///< static_cast
34 CT_Reinterpret, ///< reinterpret_cast
35 CT_Dynamic, ///< dynamic_cast
36 CT_CStyle, ///< (Type)expr
37 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000038};
39
40static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
41 const SourceRange &OpRange,
42 const SourceRange &DestRange);
43static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
44 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000045 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000046 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000047static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000048 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +000049 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000050 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000051static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
52 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000053 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000054 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000055 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000056
57static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000058
59// The Try functions attempt a specific way of casting. If they succeed, they
60// return TC_Success. If their way of casting is not appropriate for the given
61// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
62// to emit if no other way succeeds. If their way of casting is appropriate but
63// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
64// they emit a specialized diagnostic.
65// All diagnostics returned by these functions must expect the same three
66// arguments:
67// %0: Cast Type (a value from the CastType enumeration)
68// %1: Source Type
69// %2: Destination Type
70static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, unsigned &msg);
72static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000073 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
75 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000076 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000077 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000078static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000081 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000082 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000083 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000084static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
85 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000086 const SourceRange &OpRange,
87 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000088 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000089 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000090 CXXCastPath &BasePath);
Douglas Gregor4ce46c22010-03-07 23:24:59 +000091static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +000092 QualType SrcType,
93 QualType DestType,bool CStyle,
94 const SourceRange &OpRange,
95 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000096 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000097 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +000098
Sebastian Redla82e4ae2009-11-14 21:15:49 +000099static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000102 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000103 CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000104static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000105 QualType DestType, bool CStyle,
106 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000107 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000108 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000109 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000110static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
111 bool CStyle, unsigned &msg);
112static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
113 QualType DestType, bool CStyle,
114 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000115 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000116 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000117
Sebastian Redl26d85b12008-11-05 21:50:06 +0000118/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000119ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000120Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallb3d87482010-08-24 05:47:05 +0000121 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000122 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000123 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000124 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000125
John McCall9d125032010-01-15 18:39:57 +0000126 TypeSourceInfo *DestTInfo;
127 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
128 if (!DestTInfo)
129 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000130
131 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
132 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
133 SourceRange(LParenLoc, RParenLoc));
134}
135
John McCall60d7b3a2010-08-24 06:29:42 +0000136ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000137Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallf312b1e2010-08-26 23:41:50 +0000138 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCallc89724c2010-01-15 19:13:16 +0000139 SourceRange AngleBrackets, SourceRange Parens) {
John McCallc89724c2010-01-15 19:13:16 +0000140 QualType DestType = DestTInfo->getType();
141
142 SourceRange OpRange(OpLoc, Parens.getEnd());
143 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000144
Douglas Gregor9103bb22008-12-17 22:52:20 +0000145 // If the type is dependent, we won't do the semantic analysis now.
146 // FIXME: should we check this in a more fine-grained manner?
147 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
148
Sebastian Redl26d85b12008-11-05 21:50:06 +0000149 switch (Kind) {
150 default: assert(0 && "Unknown C++ cast!");
151
152 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000153 if (!TypeDependent)
154 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
John McCallf871d0c2010-08-07 06:22:56 +0000155 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000156 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000157 Ex, DestTInfo, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000158
Anders Carlsson714179b2009-08-02 19:07:59 +0000159 case tok::kw_dynamic_cast: {
John McCall2de56d12010-08-25 11:45:40 +0000160 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000161 CXXCastPath BasePath;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000162 if (!TypeDependent)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000163 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
John McCallf871d0c2010-08-07 06:22:56 +0000164 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000165 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000166 Kind, Ex, &BasePath, DestTInfo,
167 OpLoc));
Anders Carlsson714179b2009-08-02 19:07:59 +0000168 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000169 case tok::kw_reinterpret_cast: {
John McCall2de56d12010-08-25 11:45:40 +0000170 CastKind Kind = CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000171 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000172 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
John McCallf871d0c2010-08-07 06:22:56 +0000173 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000174 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000175 Kind, Ex, 0,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000176 DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000177 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000178 case tok::kw_static_cast: {
John McCall2de56d12010-08-25 11:45:40 +0000179 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000180 CXXCastPath BasePath;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000181 if (!TypeDependent)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000182 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000183
John McCallf871d0c2010-08-07 06:22:56 +0000184 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000185 DestType.getNonLValueExprType(Context),
John McCallf871d0c2010-08-07 06:22:56 +0000186 Kind, Ex, &BasePath,
187 DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000188 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000189 }
190
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000192}
193
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000194/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
195/// this removes one level of indirection from both types, provided that they're
196/// the same kind of pointer (plain or to-member). Unlike the Sema function,
197/// this one doesn't care if the two pointers-to-member don't point into the
198/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000199static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000200 const PointerType *T1PtrType = T1->getAs<PointerType>(),
201 *T2PtrType = T2->getAs<PointerType>();
202 if (T1PtrType && T2PtrType) {
203 T1 = T1PtrType->getPointeeType();
204 T2 = T2PtrType->getPointeeType();
205 return true;
206 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000207 const ObjCObjectPointerType *T1ObjCPtrType =
208 T1->getAs<ObjCObjectPointerType>(),
209 *T2ObjCPtrType =
210 T2->getAs<ObjCObjectPointerType>();
211 if (T1ObjCPtrType) {
212 if (T2ObjCPtrType) {
213 T1 = T1ObjCPtrType->getPointeeType();
214 T2 = T2ObjCPtrType->getPointeeType();
215 return true;
216 }
217 else if (T2PtrType) {
218 T1 = T1ObjCPtrType->getPointeeType();
219 T2 = T2PtrType->getPointeeType();
220 return true;
221 }
222 }
223 else if (T2ObjCPtrType) {
224 if (T1PtrType) {
225 T2 = T2ObjCPtrType->getPointeeType();
226 T1 = T1PtrType->getPointeeType();
227 return true;
228 }
229 }
230
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000231 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
232 *T2MPType = T2->getAs<MemberPointerType>();
233 if (T1MPType && T2MPType) {
234 T1 = T1MPType->getPointeeType();
235 T2 = T2MPType->getPointeeType();
236 return true;
237 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000238
239 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
240 *T2BPType = T2->getAs<BlockPointerType>();
241 if (T1BPType && T2BPType) {
242 T1 = T1BPType->getPointeeType();
243 T2 = T2BPType->getPointeeType();
244 return true;
245 }
246
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000247 return false;
248}
249
Sebastian Redldb647282009-01-27 23:18:31 +0000250/// CastsAwayConstness - Check if the pointer conversion from SrcType to
251/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
252/// the cast checkers. Both arguments must denote pointer (possibly to member)
253/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000254static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000255CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000256 // Casting away constness is defined in C++ 5.2.11p8 with reference to
257 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
258 // the rules are non-trivial. So first we construct Tcv *...cv* as described
259 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000260 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
261 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000262 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000263 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
264 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000265 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000266
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000267 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
268 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000269 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000270
271 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000272 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson52647c62010-06-04 22:47:55 +0000273 Qualifiers SrcQuals;
274 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
275 cv1.push_back(SrcQuals);
276
277 Qualifiers DestQuals;
278 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
279 cv2.push_back(DestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000281 if (cv1.empty())
282 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000283
284 // Construct void pointers with those qualifiers (in reverse order of
285 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000286 QualType SrcConstruct = Self.Context.VoidTy;
287 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000288 ASTContext &Context = Self.Context;
289 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
290 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000291 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000292 SrcConstruct
293 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
294 DestConstruct
295 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000296 }
297
298 // Test if they're compatible.
299 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000300 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000301}
302
Sebastian Redl26d85b12008-11-05 21:50:06 +0000303/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
304/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
305/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000306static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000307CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
308 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000309 const SourceRange &DestRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000310 CXXCastPath &BasePath) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000311 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000312 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313
314 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
315 // or "pointer to cv void".
316
317 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000318 const PointerType *DestPointer = DestType->getAs<PointerType>();
319 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000320 if (DestPointer) {
321 DestPointee = DestPointer->getPointeeType();
322 } else if (DestReference) {
323 DestPointee = DestReference->getPointeeType();
324 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000325 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000326 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000327 return;
328 }
329
Ted Kremenek6217b802009-07-29 21:53:49 +0000330 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000331 if (DestPointee->isVoidType()) {
332 assert(DestPointer && "Reference to void is not possible");
333 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000334 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000335 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000336 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000337 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000338 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000339 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000340 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000341 return;
342 }
343
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000344 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
345 // complete class type, [...]. If T is an lvalue reference type, v shall be
346 // an lvalue of a complete class type, [...]. If T is an rvalue reference
347 // type, v shall be an expression having a complete effective class type,
348 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000349
Sebastian Redl37d6de32008-11-08 13:00:26 +0000350 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000351 QualType SrcPointee;
352 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000353 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000354 SrcPointee = SrcPointer->getPointeeType();
355 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000356 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000357 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000358 return;
359 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000360 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000361 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000362 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000363 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000364 }
365 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000366 } else {
367 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000368 }
369
Ted Kremenek6217b802009-07-29 21:53:49 +0000370 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000371 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000372 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000373 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000374 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000375 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000376 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000377 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000378 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000379 return;
380 }
381
382 assert((DestPointer || DestReference) &&
383 "Bad destination non-ptr/ref slipped through.");
384 assert((DestRecord || DestPointee->isVoidType()) &&
385 "Bad destination pointee slipped through.");
386 assert(SrcRecord && "Bad source pointee slipped through.");
387
388 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
389 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000390 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000391 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000392 return;
393 }
394
395 // C++ 5.2.7p3: If the type of v is the same as the required result type,
396 // [except for cv].
397 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000398 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000399 return;
400 }
401
402 // C++ 5.2.7p5
403 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000404 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000405 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
406 OpRange.getBegin(), OpRange,
407 &BasePath))
408 return;
409
John McCall2de56d12010-08-25 11:45:40 +0000410 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000411
412 // If we are casting to or through a virtual base class, we need a
413 // vtable.
414 if (Self.BasePathInvolvesVirtualBase(BasePath))
415 Self.MarkVTableUsed(OpRange.getBegin(),
416 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000417 return;
418 }
419
420 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000421 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000422 assert(SrcDecl && "Definition missing");
423 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000424 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000425 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000426 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000427 Self.MarkVTableUsed(OpRange.getBegin(),
428 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000429
430 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000431 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000432}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000433
434/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
435/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
436/// like this:
437/// const char *str = "literal";
438/// legacy_function(const_cast\<char*\>(str));
439void
440CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000441 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000442 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000443 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000444
445 unsigned msg = diag::err_bad_cxx_cast_generic;
446 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
447 && msg != 0)
448 Self.Diag(OpRange.getBegin(), msg) << CT_Const
449 << SrcExpr->getType() << DestType << OpRange;
450}
451
452/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
453/// valid.
454/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
455/// like this:
456/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
457void
458CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000459 const SourceRange &OpRange, const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +0000460 CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000461 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000462 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000463
464 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000465 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
466 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000467 != TC_Success && msg != 0)
468 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
469 << SrcExpr->getType() << DestType << OpRange;
470}
471
472
473/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
474/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
475/// implicit conversions explicit and getting rid of data loss warnings.
476void
477CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall2de56d12010-08-25 11:45:40 +0000478 const SourceRange &OpRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000479 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000480 // This test is outside everything else because it's the only case where
481 // a non-lvalue-reference target type does not lead to decay.
482 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000483 if (DestType->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +0000484 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000485 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000486 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000487
Douglas Gregorb653c522009-11-06 01:14:41 +0000488 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000489 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000490
491 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000492 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000493 Kind, BasePath) != TC_Success && msg != 0)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000494 Self.Diag(OpRange.getBegin(), msg) << CT_Static
495 << SrcExpr->getType() << DestType << OpRange;
John McCall2de56d12010-08-25 11:45:40 +0000496 else if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +0000497 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000498}
499
500/// TryStaticCast - Check if a static cast can be performed, and do so if
501/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
502/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000503static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000504 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000505 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000506 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000507 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000508 // The order the tests is not entirely arbitrary. There is one conversion
509 // that can be handled in two different ways. Given:
510 // struct A {};
511 // struct B : public A {
512 // B(); B(const A&);
513 // };
514 // const A &a = B();
515 // the cast static_cast<const B&>(a) could be seen as either a static
516 // reference downcast, or an explicit invocation of the user-defined
517 // conversion using B's conversion constructor.
518 // DR 427 specifies that the downcast is to be applied here.
519
520 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
521 // Done outside this function.
522
523 TryCastResult tcr;
524
525 // C++ 5.2.9p5, reference downcast.
526 // See the function for details.
527 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000528 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000529 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000530 if (tcr != TC_NotApplicable)
531 return tcr;
532
533 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
534 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
535 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000536 if (tcr != TC_NotApplicable) {
John McCall2de56d12010-08-25 11:45:40 +0000537 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000538 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000539 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000540
541 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
542 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000543 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000544 Kind);
Anders Carlsson3c31a392009-09-26 00:12:34 +0000545 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000546 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000547
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000548 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
549 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
550 // conversions, subject to further restrictions.
551 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
552 // of qualification conversions impossible.
553 // In the CStyle case, the earlier attempt to const_cast should have taken
554 // care of reverse qualification conversions.
555
556 QualType OrigSrcType = SrcExpr->getType();
557
558 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
559
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000560 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
561 // converted to an integral type.
562 if (Self.getLangOptions().CPlusPlus0x && SrcType->isEnumeralType()) {
563 if (DestType->isIntegralType(Self.Context)) {
564 Kind = CK_IntegralCast;
565 return TC_Success;
566 }
567 }
568
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000569 // Reverse integral promotion/conversion. All such conversions are themselves
570 // again integral promotions or conversions and are thus already handled by
571 // p2 (TryDirectInitialization above).
572 // (Note: any data loss warnings should be suppressed.)
573 // The exception is the reverse of enum->integer, i.e. integer->enum (and
574 // enum->enum). See also C++ 5.2.9p7.
575 // The same goes for reverse floating point promotion/conversion and
576 // floating-integral conversions. Again, only floating->enum is relevant.
577 if (DestType->isEnumeralType()) {
578 if (SrcType->isComplexType() || SrcType->isVectorType()) {
579 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000580 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCall2de56d12010-08-25 11:45:40 +0000581 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000582 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000583 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000584 }
585
586 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
587 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000588 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000589 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000590 if (tcr != TC_NotApplicable)
591 return tcr;
592
593 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
594 // conversion. C++ 5.2.9p9 has additional information.
595 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000596 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000597 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000598 if (tcr != TC_NotApplicable)
599 return tcr;
600
601 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
602 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
603 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000604 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000605 QualType SrcPointee = SrcPointer->getPointeeType();
606 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000607 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000608 QualType DestPointee = DestPointer->getPointeeType();
609 if (DestPointee->isIncompleteOrObjectType()) {
610 // This is definitely the intended conversion, but it might fail due
611 // to a const violation.
612 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
613 msg = diag::err_bad_cxx_cast_const_away;
614 return TC_Failed;
615 }
John McCall2de56d12010-08-25 11:45:40 +0000616 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000617 return TC_Success;
618 }
619 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000620 else if (DestType->isObjCObjectPointerType()) {
621 // allow both c-style cast and static_cast of objective-c pointers as
622 // they are pervasive.
John McCall2de56d12010-08-25 11:45:40 +0000623 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000624 return TC_Success;
625 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000626 else if (CStyle && DestType->isBlockPointerType()) {
627 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000628 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000629 return TC_Success;
630 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000631 }
632 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000633 // Allow arbitray objective-c pointer conversion with static casts.
634 if (SrcType->isObjCObjectPointerType() &&
635 DestType->isObjCObjectPointerType())
636 return TC_Success;
637
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000638 // We tried everything. Everything! Nothing works! :-(
639 return TC_NotApplicable;
640}
641
642/// Tests whether a conversion according to N2844 is valid.
643TryCastResult
644TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000646 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
647 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000648 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000649 if (!R)
650 return TC_NotApplicable;
651
652 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
653 return TC_NotApplicable;
654
655 // Because we try the reference downcast before this function, from now on
656 // this is the only cast possibility, so we issue an error if we fail now.
657 // FIXME: Should allow casting away constness if CStyle.
658 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000659 bool ObjCConversion;
Douglas Gregor393896f2009-11-05 13:06:35 +0000660 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
661 SrcExpr->getType(), R->getPointeeType(),
Douglas Gregor569c3162010-08-07 11:51:51 +0000662 DerivedToBase, ObjCConversion) <
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000663 Sema::Ref_Compatible_With_Added_Qualification) {
664 msg = diag::err_bad_lvalue_to_rvalue_cast;
665 return TC_Failed;
666 }
667
Douglas Gregorf0e0b172010-03-25 00:20:38 +0000668 // FIXME: We should probably have an AST node for lvalue-to-rvalue
669 // conversions.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000670 return TC_Success;
671}
672
673/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
674TryCastResult
675TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
676 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000677 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000678 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
680 // cast to type "reference to cv2 D", where D is a class derived from B,
681 // if a valid standard conversion from "pointer to D" to "pointer to B"
682 // exists, cv2 >= cv1, and B is not a virtual base class of D.
683 // In addition, DR54 clarifies that the base must be accessible in the
684 // current context. Although the wording of DR54 only applies to the pointer
685 // variant of this rule, the intent is clearly for it to apply to the this
686 // conversion as well.
687
Ted Kremenek6217b802009-07-29 21:53:49 +0000688 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000689 if (!DestReference) {
690 return TC_NotApplicable;
691 }
692 bool RValueRef = DestReference->isRValueReferenceType();
693 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
694 // We know the left side is an lvalue reference, so we can suggest a reason.
695 msg = diag::err_bad_cxx_cast_rvalue;
696 return TC_NotApplicable;
697 }
698
699 QualType DestPointee = DestReference->getPointeeType();
700
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000701 return TryStaticDowncast(Self,
702 Self.Context.getCanonicalType(SrcExpr->getType()),
703 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000704 OpRange, SrcExpr->getType(), DestType, msg, Kind,
705 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000706}
707
708/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
709TryCastResult
710TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000711 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000712 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000713 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000714 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
715 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
716 // is a class derived from B, if a valid standard conversion from "pointer
717 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
718 // class of D.
719 // In addition, DR54 clarifies that the base must be accessible in the
720 // current context.
721
Ted Kremenek6217b802009-07-29 21:53:49 +0000722 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000723 if (!DestPointer) {
724 return TC_NotApplicable;
725 }
726
Ted Kremenek6217b802009-07-29 21:53:49 +0000727 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000728 if (!SrcPointer) {
729 msg = diag::err_bad_static_cast_pointer_nonpointer;
730 return TC_NotApplicable;
731 }
732
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000733 return TryStaticDowncast(Self,
734 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
735 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000736 CStyle, OpRange, SrcType, DestType, msg, Kind,
737 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000738}
739
740/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
741/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000742/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000743TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000744TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000745 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000746 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000747 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000748 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000749 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
750 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000751 return TC_NotApplicable;
752
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000753 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000754 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000755 return TC_NotApplicable;
756 }
757
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000759 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000760 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
761 return TC_NotApplicable;
762 }
763
764 // Target type does derive from source type. Now we're serious. If an error
765 // appears now, it's not ignored.
766 // This may not be entirely in line with the standard. Take for example:
767 // struct A {};
768 // struct B : virtual A {
769 // B(A&);
770 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000771 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000772 // void f()
773 // {
774 // (void)static_cast<const B&>(*((A*)0));
775 // }
776 // As far as the standard is concerned, p5 does not apply (A is virtual), so
777 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
778 // However, both GCC and Comeau reject this example, and accepting it would
779 // mean more complex code if we're to preserve the nice error message.
780 // FIXME: Being 100% compliant here would be nice to have.
781
782 // Must preserve cv, as always, unless we're in C-style mode.
783 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
784 msg = diag::err_bad_cxx_cast_const_away;
785 return TC_Failed;
786 }
787
788 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
789 // This code is analoguous to that in CheckDerivedToBaseConversion, except
790 // that it builds the paths in reverse order.
791 // To sum up: record all paths to the base and build a nice string from
792 // them. Use it to spice up the error message.
793 if (!Paths.isRecordingPaths()) {
794 Paths.clear();
795 Paths.setRecordingPaths(true);
796 Self.IsDerivedFrom(DestType, SrcType, Paths);
797 }
798 std::string PathDisplayStr;
799 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000800 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000801 PI != PE; ++PI) {
802 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
803 // We haven't displayed a path to this particular base
804 // class subobject yet.
805 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
807 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000808 EI != EE; ++EI)
809 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000810 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000811 }
812 }
813
814 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000815 << QualType(SrcType).getUnqualifiedType()
816 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000817 << PathDisplayStr << OpRange;
818 msg = 0;
819 return TC_Failed;
820 }
821
822 if (Paths.getDetectedVirtual() != 0) {
823 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
824 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
825 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
826 msg = 0;
827 return TC_Failed;
828 }
829
John McCall6b2accb2010-02-10 09:31:12 +0000830 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000831 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000832 Paths.front(),
833 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000834 msg = 0;
835 return TC_Failed;
836 }
837
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000838 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +0000839 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000840 return TC_Success;
841}
842
843/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
844/// C++ 5.2.9p9 is valid:
845///
846/// An rvalue of type "pointer to member of D of type cv1 T" can be
847/// converted to an rvalue of type "pointer to member of B of type cv2 T",
848/// where B is a base class of D [...].
849///
850TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000851TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
852 QualType DestType, bool CStyle,
853 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000854 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000856 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000857 if (!DestMemPtr)
858 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000859
860 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +0000861 DeclAccessPair FoundOverload;
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000862 if (SrcExpr->getType() == Self.Context.OverloadTy) {
863 if (FunctionDecl *Fn
864 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
865 FoundOverload)) {
866 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
867 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
868 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
869 WasOverloadedFunction = true;
870 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000871 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000872
Ted Kremenek6217b802009-07-29 21:53:49 +0000873 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000874 if (!SrcMemPtr) {
875 msg = diag::err_bad_static_cast_member_pointer_nonmp;
876 return TC_NotApplicable;
877 }
878
879 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000880 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
881 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000882 return TC_NotApplicable;
883
884 // B base of D
885 QualType SrcClass(SrcMemPtr->getClass(), 0);
886 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +0000887 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000888 /*DetectVirtual=*/true);
889 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
890 return TC_NotApplicable;
891 }
892
893 // 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 +0000894 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000895 Paths.clear();
896 Paths.setRecordingPaths(true);
897 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
898 assert(StillOkay);
899 StillOkay = StillOkay;
900 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
901 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
902 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
903 msg = 0;
904 return TC_Failed;
905 }
906
907 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
908 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
909 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
910 msg = 0;
911 return TC_Failed;
912 }
913
John McCall6b2accb2010-02-10 09:31:12 +0000914 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedman0fab8cd2010-07-23 19:25:41 +0000915 DestClass, SrcClass,
John McCall58e6f342010-03-16 05:22:47 +0000916 Paths.front(),
917 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000918 msg = 0;
919 return TC_Failed;
920 }
921
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000922 if (WasOverloadedFunction) {
923 // Resolve the address of the overloaded function again, this time
924 // allowing complaints if something goes wrong.
925 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
926 DestType,
John McCall6bb80172010-03-30 21:47:33 +0000927 true,
928 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000929 if (!Fn) {
930 msg = 0;
931 return TC_Failed;
932 }
933
John McCall6bb80172010-03-30 21:47:33 +0000934 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000935 if (!SrcExpr) {
936 msg = 0;
937 return TC_Failed;
938 }
939 }
940
Anders Carlssoncee22422010-04-24 19:22:20 +0000941 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +0000942 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000943 return TC_Success;
944}
945
946/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
947/// is valid:
948///
949/// An expression e can be explicitly converted to a type T using a
950/// @c static_cast if the declaration "T t(e);" is well-formed [...].
951TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000952TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000953 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000954 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +0000955 if (DestType->isRecordType()) {
956 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
957 diag::err_bad_dynamic_cast_incomplete)) {
958 msg = 0;
959 return TC_Failed;
960 }
961 }
Douglas Gregord6e44a32010-04-16 22:09:46 +0000962
963 // At this point of CheckStaticCast, if the destination is a reference,
964 // this has to work. There is no other way that works.
965 // On the other hand, if we're checking a C-style cast, we've still got
966 // the reinterpret_cast way.
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000967 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
968 InitializationKind InitKind
Douglas Gregord6e44a32010-04-16 22:09:46 +0000969 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
970 CStyle);
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000971 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregord6e44a32010-04-16 22:09:46 +0000972 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
973 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +0000974 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000975
John McCall60d7b3a2010-08-24 06:29:42 +0000976 ExprResult Result
John McCallf312b1e2010-08-26 23:41:50 +0000977 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000978 if (Result.isInvalid()) {
979 msg = 0;
980 return TC_Failed;
981 }
982
Douglas Gregord6e44a32010-04-16 22:09:46 +0000983 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +0000984 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000985 else
John McCall2de56d12010-08-25 11:45:40 +0000986 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000987
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000988 SrcExpr = Result.takeAs<Expr>();
989 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000990}
991
992/// TryConstCast - See if a const_cast from source to destination is allowed,
993/// and perform it if it is.
994static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
995 bool CStyle, unsigned &msg) {
996 DestType = Self.Context.getCanonicalType(DestType);
997 QualType SrcType = SrcExpr->getType();
998 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000999 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001000 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1001 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1002 // is C-style, static_cast might find a way, so we simply suggest a
1003 // message and tell the parent to keep searching.
1004 msg = diag::err_bad_cxx_cast_rvalue;
1005 return TC_NotApplicable;
1006 }
1007
1008 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1009 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1010 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1011 SrcType = Self.Context.getPointerType(SrcType);
1012 }
1013
1014 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1015 // the rules for const_cast are the same as those used for pointers.
1016
John McCalld425d2b2010-05-18 09:35:29 +00001017 if (!DestType->isPointerType() &&
1018 !DestType->isMemberPointerType() &&
1019 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001020 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1021 // was a reference type, we converted it to a pointer above.
1022 // The status of rvalue references isn't entirely clear, but it looks like
1023 // conversion to them is simply invalid.
1024 // C++ 5.2.11p3: For two pointer types [...]
1025 if (!CStyle)
1026 msg = diag::err_bad_const_cast_dest;
1027 return TC_NotApplicable;
1028 }
1029 if (DestType->isFunctionPointerType() ||
1030 DestType->isMemberFunctionPointerType()) {
1031 // Cannot cast direct function pointers.
1032 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1033 // T is the ultimate pointee of source and target type.
1034 if (!CStyle)
1035 msg = diag::err_bad_const_cast_dest;
1036 return TC_NotApplicable;
1037 }
1038 SrcType = Self.Context.getCanonicalType(SrcType);
1039
1040 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1041 // completely equal.
1042 // FIXME: const_cast should probably not be able to convert between pointers
1043 // to different address spaces.
1044 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1045 // in multi-level pointers may change, but the level count must be the same,
1046 // as must be the final pointee type.
1047 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001048 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +00001049 Qualifiers Quals;
1050 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1051 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001052 }
1053
1054 // Since we're dealing in canonical types, the remainder must be the same.
1055 if (SrcType != DestType)
1056 return TC_NotApplicable;
1057
1058 return TC_Success;
1059}
1060
1061static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1062 QualType DestType, bool CStyle,
1063 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001064 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001065 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001066 bool IsLValueCast = false;
1067
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001068 DestType = Self.Context.getCanonicalType(DestType);
1069 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001070 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001071 bool LValue = DestTypeTmp->isLValueReferenceType();
1072 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1073 // Cannot cast non-lvalue to reference type. See the similar comment in
1074 // const_cast.
1075 msg = diag::err_bad_cxx_cast_rvalue;
1076 return TC_NotApplicable;
1077 }
1078
1079 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1080 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1081 // built-in & and * operators.
1082 // This code does this transformation for the checked types.
1083 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1084 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore39a3892010-07-13 23:17:26 +00001085 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001086 }
1087
1088 // Canonicalize source for comparison.
1089 SrcType = Self.Context.getCanonicalType(SrcType);
1090
Ted Kremenek6217b802009-07-29 21:53:49 +00001091 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1092 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001093 if (DestMemPtr && SrcMemPtr) {
1094 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1095 // can be explicitly converted to an rvalue of type "pointer to member
1096 // of Y of type T2" if T1 and T2 are both function types or both object
1097 // types.
1098 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1099 SrcMemPtr->getPointeeType()->isFunctionType())
1100 return TC_NotApplicable;
1101
1102 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1103 // constness.
1104 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1105 // we accept it.
1106 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1107 msg = diag::err_bad_cxx_cast_const_away;
1108 return TC_Failed;
1109 }
1110
Charles Davisf231df32010-08-16 05:30:44 +00001111 // Don't allow casting between member pointers of different sizes.
1112 if (Self.Context.getTypeSize(DestMemPtr) !=
1113 Self.Context.getTypeSize(SrcMemPtr)) {
1114 msg = diag::err_bad_cxx_cast_member_pointer_size;
1115 return TC_Failed;
1116 }
1117
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001118 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001119 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001120 return TC_Success;
1121 }
1122
1123 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001124 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001125 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1126 // type large enough to hold it. A value of std::nullptr_t can be
1127 // converted to an integral type; the conversion has the same meaning
1128 // and validity as a conversion of (void*)0 to the integral type.
1129 if (Self.Context.getTypeSize(SrcType) >
1130 Self.Context.getTypeSize(DestType)) {
1131 msg = diag::err_bad_reinterpret_cast_small_int;
1132 return TC_Failed;
1133 }
John McCall2de56d12010-08-25 11:45:40 +00001134 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001135 return TC_Success;
1136 }
1137
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001138 bool destIsVector = DestType->isVectorType();
1139 bool srcIsVector = SrcType->isVectorType();
1140 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001141 // FIXME: Should this also apply to floating point types?
1142 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1143 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001144
1145 // Check if this is a cast between a vector and something else.
1146 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1147 !(srcIsVector && destIsVector))
1148 return TC_NotApplicable;
1149
1150 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001151 if (Self.Context.getTypeSize(SrcType)
1152 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001153 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001154 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001155 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001156
1157 if (destIsScalar)
1158 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1159 else if (srcIsScalar)
1160 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1161 else
1162 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1163
1164 return TC_Failed;
1165 }
1166
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001167 bool destIsPtr = DestType->isAnyPointerType() ||
1168 DestType->isBlockPointerType();
1169 bool srcIsPtr = SrcType->isAnyPointerType() ||
1170 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001171 if (!destIsPtr && !srcIsPtr) {
1172 // Except for std::nullptr_t->integer and lvalue->reference, which are
1173 // handled above, at least one of the two arguments must be a pointer.
1174 return TC_NotApplicable;
1175 }
1176
1177 if (SrcType == DestType) {
1178 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1179 // restrictions, a cast to the same type is allowed. The intent is not
1180 // entirely clear here, since all other paragraphs explicitly forbid casts
1181 // to the same type. However, the behavior of compilers is pretty consistent
1182 // on this point: allow same-type conversion if the involved types are
1183 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001184 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001185 return TC_Success;
1186 }
1187
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001188 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001189 assert(srcIsPtr && "One type must be a pointer");
1190 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1191 // type large enough to hold it.
1192 if (Self.Context.getTypeSize(SrcType) >
1193 Self.Context.getTypeSize(DestType)) {
1194 msg = diag::err_bad_reinterpret_cast_small_int;
1195 return TC_Failed;
1196 }
John McCall2de56d12010-08-25 11:45:40 +00001197 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001198 return TC_Success;
1199 }
1200
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001201 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001202 assert(destIsPtr && "One type must be a pointer");
1203 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1204 // converted to a pointer.
John McCall2de56d12010-08-25 11:45:40 +00001205 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001206 return TC_Success;
1207 }
1208
1209 if (!destIsPtr || !srcIsPtr) {
1210 // With the valid non-pointer conversions out of the way, we can be even
1211 // more stringent.
1212 return TC_NotApplicable;
1213 }
1214
1215 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1216 // The C-style cast operator can.
1217 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1218 msg = diag::err_bad_cxx_cast_const_away;
1219 return TC_Failed;
1220 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001221
1222 // Cannot convert between block pointers and Objective-C object pointers.
1223 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1224 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1225 return TC_NotApplicable;
1226
1227 // Any pointer can be cast to an Objective-C pointer type with a C-style
1228 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001229 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001230 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001231 return TC_Success;
1232 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001233
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001234 // Not casting away constness, so the only remaining check is for compatible
1235 // pointer categories.
John McCall2de56d12010-08-25 11:45:40 +00001236 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001237
1238 if (SrcType->isFunctionPointerType()) {
1239 if (DestType->isFunctionPointerType()) {
1240 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1241 // a pointer to a function of a different type.
1242 return TC_Success;
1243 }
1244
1245 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1246 // an object type or vice versa is conditionally-supported.
1247 // Compilers support it in C++03 too, though, because it's necessary for
1248 // casting the return value of dlsym() and GetProcAddress().
1249 // FIXME: Conditionally-supported behavior should be configurable in the
1250 // TargetInfo or similar.
1251 if (!Self.getLangOptions().CPlusPlus0x)
1252 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1253 return TC_Success;
1254 }
1255
1256 if (DestType->isFunctionPointerType()) {
1257 // See above.
1258 if (!Self.getLangOptions().CPlusPlus0x)
1259 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1260 return TC_Success;
1261 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001262
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001263 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1264 // a pointer to an object of different type.
1265 // Void pointers are not specified, but supported by every compiler out there.
1266 // So we finish by allowing everything that remains - it's got to be two
1267 // object pointers.
1268 return TC_Success;
1269}
1270
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001271bool
1272Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
John McCall2de56d12010-08-25 11:45:40 +00001273 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001274 CXXCastPath &BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001275 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001276 // This test is outside everything else because it's the only case where
1277 // a non-lvalue-reference target type does not lead to decay.
1278 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001279 if (CastTy->isVoidType()) {
John McCall2de56d12010-08-25 11:45:40 +00001280 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001281 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001282 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001283
1284 // If the type is dependent, we won't do any other semantic analysis now.
1285 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1286 return false;
1287
Douglas Gregorb653c522009-11-06 01:14:41 +00001288 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001289 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001290
1291 // C++ [expr.cast]p5: The conversions performed by
1292 // - a const_cast,
1293 // - a static_cast,
1294 // - a static_cast followed by a const_cast,
1295 // - a reinterpret_cast, or
1296 // - a reinterpret_cast followed by a const_cast,
1297 // can be performed using the cast notation of explicit type conversion.
1298 // [...] If a conversion can be interpreted in more than one of the ways
1299 // listed above, the interpretation that appears first in the list is used,
1300 // even if a cast resulting from that interpretation is ill-formed.
1301 // In plain language, this means trying a const_cast ...
1302 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001303 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1304 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001305 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001306 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001307
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001308 if (tcr == TC_NotApplicable) {
1309 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001310 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1311 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001312 if (tcr == TC_NotApplicable) {
1313 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001314 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1315 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001316 }
1317 }
1318
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001319 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001320 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001321 << CastExpr->getType() << CastTy << R;
John McCall2de56d12010-08-25 11:45:40 +00001322 else if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00001323 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001324
1325 return tcr != TC_Success;
1326}