blob: a7225180ac66076a32a9cb1957d524f72f91b111 [file] [log] [blame]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000022using namespace clang;
23
Sebastian Redl9f831db2009-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 Redl842ef522008-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 Carlsson7cd39e02009-09-15 04:48:33 +000045 const SourceRange &DestRange,
46 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000047static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssonf10e4142009-08-07 22:21:05 +000048 const SourceRange &OpRange,
Anders Carlssona70cff62010-04-24 19:06:50 +000049 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000050 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000051static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
52 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000053 const SourceRange &DestRange,
Anders Carlssona70cff62010-04-24 19:06:50 +000054 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000055 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000056
57static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-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 Carlsson7d3360f2010-04-24 19:36:51 +000073 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
75 unsigned &msg,
76 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000077 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +000078static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000081 unsigned &msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000082 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000083 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000084static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
85 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000086 const SourceRange &OpRange,
87 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000088 QualType OrigDestType, unsigned &msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000089 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000090 CXXCastPath &BasePath);
Douglas Gregorc934bc82010-03-07 23:24:59 +000091static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +000092 QualType SrcType,
93 QualType DestType,bool CStyle,
94 const SourceRange &OpRange,
95 unsigned &msg,
96 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000097 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +000098
Sebastian Redl7c353682009-11-14 21:15:49 +000099static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000102 unsigned &msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000103 CastExpr::CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +0000104static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000105 QualType DestType, bool CStyle,
106 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000107 unsigned &msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000108 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000109 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-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 Carlsson9d1b34b2009-09-26 00:12:34 +0000115 unsigned &msg,
116 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000117
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000118/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000119Action::OwningExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000120Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
121 SourceLocation LAngleBracketLoc, TypeTy *Ty,
122 SourceLocation RAngleBracketLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000123 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000124 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000125
John McCall97513962010-01-15 18:39:57 +0000126 TypeSourceInfo *DestTInfo;
127 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
128 if (!DestTInfo)
129 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000130
131 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
132 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
133 SourceRange(LParenLoc, RParenLoc));
134}
135
136Action::OwningExprResult
137Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
138 TypeSourceInfo *DestTInfo, ExprArg E,
139 SourceRange AngleBrackets, SourceRange Parens) {
140 Expr *Ex = E.takeAs<Expr>();
141 QualType DestType = DestTInfo->getType();
142
143 SourceRange OpRange(OpLoc, Parens.getEnd());
144 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000145
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000146 // If the type is dependent, we won't do the semantic analysis now.
147 // FIXME: should we check this in a more fine-grained manner?
148 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
149
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000150 switch (Kind) {
151 default: assert(0 && "Unknown C++ cast!");
152
153 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000154 if (!TypeDependent)
155 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
John McCallcf142162010-08-07 06:22:56 +0000156 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000157 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000158 Ex, DestTInfo, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000159
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000160 case tok::kw_dynamic_cast: {
161 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000162 CXXCastPath BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000163 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000164 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
John McCallcf142162010-08-07 06:22:56 +0000165 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000166 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000167 Kind, Ex, &BasePath, DestTInfo,
168 OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000169 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000170 case tok::kw_reinterpret_cast: {
171 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000172 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000173 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
John McCallcf142162010-08-07 06:22:56 +0000174 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000175 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000176 Kind, Ex, 0,
Anders Carlssona70cff62010-04-24 19:06:50 +0000177 DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000178 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000179 case tok::kw_static_cast: {
180 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000181 CXXCastPath BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000182 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000183 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000184
John McCallcf142162010-08-07 06:22:56 +0000185 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000186 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000187 Kind, Ex, &BasePath,
188 DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000189 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000190 }
191
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000192 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000193}
194
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000195/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
196/// this removes one level of indirection from both types, provided that they're
197/// the same kind of pointer (plain or to-member). Unlike the Sema function,
198/// this one doesn't care if the two pointers-to-member don't point into the
199/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000200static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000201 const PointerType *T1PtrType = T1->getAs<PointerType>(),
202 *T2PtrType = T2->getAs<PointerType>();
203 if (T1PtrType && T2PtrType) {
204 T1 = T1PtrType->getPointeeType();
205 T2 = T2PtrType->getPointeeType();
206 return true;
207 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000208 const ObjCObjectPointerType *T1ObjCPtrType =
209 T1->getAs<ObjCObjectPointerType>(),
210 *T2ObjCPtrType =
211 T2->getAs<ObjCObjectPointerType>();
212 if (T1ObjCPtrType) {
213 if (T2ObjCPtrType) {
214 T1 = T1ObjCPtrType->getPointeeType();
215 T2 = T2ObjCPtrType->getPointeeType();
216 return true;
217 }
218 else if (T2PtrType) {
219 T1 = T1ObjCPtrType->getPointeeType();
220 T2 = T2PtrType->getPointeeType();
221 return true;
222 }
223 }
224 else if (T2ObjCPtrType) {
225 if (T1PtrType) {
226 T2 = T2ObjCPtrType->getPointeeType();
227 T1 = T1PtrType->getPointeeType();
228 return true;
229 }
230 }
231
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000232 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
233 *T2MPType = T2->getAs<MemberPointerType>();
234 if (T1MPType && T2MPType) {
235 T1 = T1MPType->getPointeeType();
236 T2 = T2MPType->getPointeeType();
237 return true;
238 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000239
240 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
241 *T2BPType = T2->getAs<BlockPointerType>();
242 if (T1BPType && T2BPType) {
243 T1 = T1BPType->getPointeeType();
244 T2 = T2BPType->getPointeeType();
245 return true;
246 }
247
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000248 return false;
249}
250
Sebastian Redla5a77a62009-01-27 23:18:31 +0000251/// CastsAwayConstness - Check if the pointer conversion from SrcType to
252/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
253/// the cast checkers. Both arguments must denote pointer (possibly to member)
254/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000255static bool
Mike Stump11289f42009-09-09 15:08:12 +0000256CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000257 // Casting away constness is defined in C++ 5.2.11p8 with reference to
258 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
259 // the rules are non-trivial. So first we construct Tcv *...cv* as described
260 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000261 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
262 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000263 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000264 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
265 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000266 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000267
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000268 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
269 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000270 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000271
272 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000273 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000274 Qualifiers SrcQuals;
275 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
276 cv1.push_back(SrcQuals);
277
278 Qualifiers DestQuals;
279 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
280 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000281 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000282 if (cv1.empty())
283 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000284
285 // Construct void pointers with those qualifiers (in reverse order of
286 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000287 QualType SrcConstruct = Self.Context.VoidTy;
288 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000289 ASTContext &Context = Self.Context;
290 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
291 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000292 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000293 SrcConstruct
294 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
295 DestConstruct
296 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000297 }
298
299 // Test if they're compatible.
300 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000301 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000302}
303
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000304/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
305/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
306/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000307static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000308CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
309 const SourceRange &OpRange,
Anders Carlssona70cff62010-04-24 19:06:50 +0000310 const SourceRange &DestRange, CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000311 CXXCastPath &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000312 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000313 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000314
315 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
316 // or "pointer to cv void".
317
318 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000319 const PointerType *DestPointer = DestType->getAs<PointerType>();
320 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000321 if (DestPointer) {
322 DestPointee = DestPointer->getPointeeType();
323 } else if (DestReference) {
324 DestPointee = DestReference->getPointeeType();
325 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000326 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000327 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000328 return;
329 }
330
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000331 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000332 if (DestPointee->isVoidType()) {
333 assert(DestPointer && "Reference to void is not possible");
334 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000335 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000336 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000337 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000338 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000339 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000340 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000341 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000342 return;
343 }
344
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000345 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
346 // complete class type, [...]. If T is an lvalue reference type, v shall be
347 // an lvalue of a complete class type, [...]. If T is an rvalue reference
348 // type, v shall be an expression having a complete effective class type,
349 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000350
Sebastian Redl842ef522008-11-08 13:00:26 +0000351 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000352 QualType SrcPointee;
353 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000354 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000355 SrcPointee = SrcPointer->getPointeeType();
356 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000357 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000358 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000359 return;
360 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000361 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000362 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000363 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000364 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000365 }
366 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000367 } else {
368 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000369 }
370
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000371 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000372 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000373 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000374 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000375 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000376 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000377 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000378 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000379 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000380 return;
381 }
382
383 assert((DestPointer || DestReference) &&
384 "Bad destination non-ptr/ref slipped through.");
385 assert((DestRecord || DestPointee->isVoidType()) &&
386 "Bad destination pointee slipped through.");
387 assert(SrcRecord && "Bad source pointee slipped through.");
388
389 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
390 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000391 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000392 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000393 return;
394 }
395
396 // C++ 5.2.7p3: If the type of v is the same as the required result type,
397 // [except for cv].
398 if (DestRecord == SrcRecord) {
Douglas Gregore9bf2d12010-07-29 16:12:45 +0000399 Kind = CastExpr::CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000400 return;
401 }
402
403 // C++ 5.2.7p5
404 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000405 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000406 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
407 OpRange.getBegin(), OpRange,
408 &BasePath))
409 return;
410
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000411 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000412
413 // If we are casting to or through a virtual base class, we need a
414 // vtable.
415 if (Self.BasePathInvolvesVirtualBase(BasePath))
416 Self.MarkVTableUsed(OpRange.getBegin(),
417 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000418 return;
419 }
420
421 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000422 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000423 assert(SrcDecl && "Definition missing");
424 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000425 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000426 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000427 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000428 Self.MarkVTableUsed(OpRange.getBegin(),
429 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000430
431 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000432 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000433}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000434
435/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
436/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
437/// like this:
438/// const char *str = "literal";
439/// legacy_function(const_cast\<char*\>(str));
440void
441CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000442 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000443 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000444 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000445
446 unsigned msg = diag::err_bad_cxx_cast_generic;
447 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
448 && msg != 0)
449 Self.Diag(OpRange.getBegin(), msg) << CT_Const
450 << SrcExpr->getType() << DestType << OpRange;
451}
452
453/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
454/// valid.
455/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
456/// like this:
457/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
458void
459CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000460 const SourceRange &OpRange, const SourceRange &DestRange,
461 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000462 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000463 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000464
465 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000466 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
467 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000468 != TC_Success && msg != 0)
469 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
470 << SrcExpr->getType() << DestType << OpRange;
471}
472
473
474/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
475/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
476/// implicit conversions explicit and getting rid of data loss warnings.
477void
478CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssona70cff62010-04-24 19:06:50 +0000479 const SourceRange &OpRange, CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000480 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000481 // This test is outside everything else because it's the only case where
482 // a non-lvalue-reference target type does not lead to decay.
483 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000484 if (DestType->isVoidType()) {
485 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000486 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000487 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000488
Douglas Gregorad8b2222009-11-06 01:14:41 +0000489 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000490 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000491
492 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000493 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000494 Kind, BasePath) != TC_Success && msg != 0)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000495 Self.Diag(OpRange.getBegin(), msg) << CT_Static
496 << SrcExpr->getType() << DestType << OpRange;
John McCall2b5c1b22010-08-12 21:44:57 +0000497 else if (Kind == CastExpr::CK_Unknown || Kind == CastExpr::CK_BitCast)
498 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000499}
500
501/// TryStaticCast - Check if a static cast can be performed, and do so if
502/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
503/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000504static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000505 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000506 const SourceRange &OpRange, unsigned &msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000507 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000508 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000509 // The order the tests is not entirely arbitrary. There is one conversion
510 // that can be handled in two different ways. Given:
511 // struct A {};
512 // struct B : public A {
513 // B(); B(const A&);
514 // };
515 // const A &a = B();
516 // the cast static_cast<const B&>(a) could be seen as either a static
517 // reference downcast, or an explicit invocation of the user-defined
518 // conversion using B's conversion constructor.
519 // DR 427 specifies that the downcast is to be applied here.
520
521 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
522 // Done outside this function.
523
524 TryCastResult tcr;
525
526 // C++ 5.2.9p5, reference downcast.
527 // See the function for details.
528 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000529 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000530 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000531 if (tcr != TC_NotApplicable)
532 return tcr;
533
534 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
535 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
536 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000537 if (tcr != TC_NotApplicable) {
538 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000539 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000540 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000541
542 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
543 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000544 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000545 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000546 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000547 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000548
Sebastian Redl9f831db2009-07-25 15:41:38 +0000549 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
550 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
551 // conversions, subject to further restrictions.
552 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
553 // of qualification conversions impossible.
554 // In the CStyle case, the earlier attempt to const_cast should have taken
555 // care of reverse qualification conversions.
556
557 QualType OrigSrcType = SrcExpr->getType();
558
559 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
560
561 // Reverse integral promotion/conversion. All such conversions are themselves
562 // again integral promotions or conversions and are thus already handled by
563 // p2 (TryDirectInitialization above).
564 // (Note: any data loss warnings should be suppressed.)
565 // The exception is the reverse of enum->integer, i.e. integer->enum (and
566 // enum->enum). See also C++ 5.2.9p7.
567 // The same goes for reverse floating point promotion/conversion and
568 // floating-integral conversions. Again, only floating->enum is relevant.
569 if (DestType->isEnumeralType()) {
570 if (SrcType->isComplexType() || SrcType->isVectorType()) {
571 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000572 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
573 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000574 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000575 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000576 }
577
578 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
579 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000580 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000581 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000582 if (tcr != TC_NotApplicable)
583 return tcr;
584
585 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
586 // conversion. C++ 5.2.9p9 has additional information.
587 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000588 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000589 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000590 if (tcr != TC_NotApplicable)
591 return tcr;
592
593 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
594 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
595 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000596 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000597 QualType SrcPointee = SrcPointer->getPointeeType();
598 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000599 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000600 QualType DestPointee = DestPointer->getPointeeType();
601 if (DestPointee->isIncompleteOrObjectType()) {
602 // This is definitely the intended conversion, but it might fail due
603 // to a const violation.
604 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
605 msg = diag::err_bad_cxx_cast_const_away;
606 return TC_Failed;
607 }
Eli Friedman03bf60a2009-11-16 05:44:20 +0000608 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000609 return TC_Success;
610 }
611 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000612 else if (DestType->isObjCObjectPointerType()) {
613 // allow both c-style cast and static_cast of objective-c pointers as
614 // they are pervasive.
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000615 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
616 return TC_Success;
617 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000618 else if (CStyle && DestType->isBlockPointerType()) {
619 // allow c-style cast of void * to block pointers.
620 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
621 return TC_Success;
622 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000623 }
624 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000625 // Allow arbitray objective-c pointer conversion with static casts.
626 if (SrcType->isObjCObjectPointerType() &&
627 DestType->isObjCObjectPointerType())
628 return TC_Success;
629
Sebastian Redl9f831db2009-07-25 15:41:38 +0000630 // We tried everything. Everything! Nothing works! :-(
631 return TC_NotApplicable;
632}
633
634/// Tests whether a conversion according to N2844 is valid.
635TryCastResult
636TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000637 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000638 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
639 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000640 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000641 if (!R)
642 return TC_NotApplicable;
643
644 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
645 return TC_NotApplicable;
646
647 // Because we try the reference downcast before this function, from now on
648 // this is the only cast possibility, so we issue an error if we fail now.
649 // FIXME: Should allow casting away constness if CStyle.
650 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000651 bool ObjCConversion;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000652 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
653 SrcExpr->getType(), R->getPointeeType(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000654 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000655 Sema::Ref_Compatible_With_Added_Qualification) {
656 msg = diag::err_bad_lvalue_to_rvalue_cast;
657 return TC_Failed;
658 }
659
Douglas Gregor031296e2010-03-25 00:20:38 +0000660 // FIXME: We should probably have an AST node for lvalue-to-rvalue
661 // conversions.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000662 return TC_Success;
663}
664
665/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
666TryCastResult
667TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
668 bool CStyle, const SourceRange &OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000669 unsigned &msg, CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000670 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000671 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
672 // cast to type "reference to cv2 D", where D is a class derived from B,
673 // if a valid standard conversion from "pointer to D" to "pointer to B"
674 // exists, cv2 >= cv1, and B is not a virtual base class of D.
675 // In addition, DR54 clarifies that the base must be accessible in the
676 // current context. Although the wording of DR54 only applies to the pointer
677 // variant of this rule, the intent is clearly for it to apply to the this
678 // conversion as well.
679
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000680 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000681 if (!DestReference) {
682 return TC_NotApplicable;
683 }
684 bool RValueRef = DestReference->isRValueReferenceType();
685 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
686 // We know the left side is an lvalue reference, so we can suggest a reason.
687 msg = diag::err_bad_cxx_cast_rvalue;
688 return TC_NotApplicable;
689 }
690
691 QualType DestPointee = DestReference->getPointeeType();
692
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000693 return TryStaticDowncast(Self,
694 Self.Context.getCanonicalType(SrcExpr->getType()),
695 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000696 OpRange, SrcExpr->getType(), DestType, msg, Kind,
697 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000698}
699
700/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
701TryCastResult
702TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000703 bool CStyle, const SourceRange &OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000704 unsigned &msg, CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000705 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000706 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
707 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
708 // is a class derived from B, if a valid standard conversion from "pointer
709 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
710 // class of D.
711 // In addition, DR54 clarifies that the base must be accessible in the
712 // current context.
713
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000714 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000715 if (!DestPointer) {
716 return TC_NotApplicable;
717 }
718
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000719 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000720 if (!SrcPointer) {
721 msg = diag::err_bad_static_cast_pointer_nonpointer;
722 return TC_NotApplicable;
723 }
724
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000725 return TryStaticDowncast(Self,
726 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
727 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000728 CStyle, OpRange, SrcType, DestType, msg, Kind,
729 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000730}
731
732/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
733/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000734/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000735TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000736TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000737 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000738 QualType OrigDestType, unsigned &msg,
John McCallcf142162010-08-07 06:22:56 +0000739 CastExpr::CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000740 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000741 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
742 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000743 return TC_NotApplicable;
744
Sebastian Redl9f831db2009-07-25 15:41:38 +0000745 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000746 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000747 return TC_NotApplicable;
748 }
749
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000750 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000751 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000752 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
753 return TC_NotApplicable;
754 }
755
756 // Target type does derive from source type. Now we're serious. If an error
757 // appears now, it's not ignored.
758 // This may not be entirely in line with the standard. Take for example:
759 // struct A {};
760 // struct B : virtual A {
761 // B(A&);
762 // };
Mike Stump11289f42009-09-09 15:08:12 +0000763 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000764 // void f()
765 // {
766 // (void)static_cast<const B&>(*((A*)0));
767 // }
768 // As far as the standard is concerned, p5 does not apply (A is virtual), so
769 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
770 // However, both GCC and Comeau reject this example, and accepting it would
771 // mean more complex code if we're to preserve the nice error message.
772 // FIXME: Being 100% compliant here would be nice to have.
773
774 // Must preserve cv, as always, unless we're in C-style mode.
775 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
776 msg = diag::err_bad_cxx_cast_const_away;
777 return TC_Failed;
778 }
779
780 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
781 // This code is analoguous to that in CheckDerivedToBaseConversion, except
782 // that it builds the paths in reverse order.
783 // To sum up: record all paths to the base and build a nice string from
784 // them. Use it to spice up the error message.
785 if (!Paths.isRecordingPaths()) {
786 Paths.clear();
787 Paths.setRecordingPaths(true);
788 Self.IsDerivedFrom(DestType, SrcType, Paths);
789 }
790 std::string PathDisplayStr;
791 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000792 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000793 PI != PE; ++PI) {
794 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
795 // We haven't displayed a path to this particular base
796 // class subobject yet.
797 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000798 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
799 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000800 EI != EE; ++EI)
801 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000802 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000803 }
804 }
805
806 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000807 << QualType(SrcType).getUnqualifiedType()
808 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000809 << PathDisplayStr << OpRange;
810 msg = 0;
811 return TC_Failed;
812 }
813
814 if (Paths.getDetectedVirtual() != 0) {
815 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
816 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
817 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
818 msg = 0;
819 return TC_Failed;
820 }
821
John McCall5b0829a2010-02-10 09:31:12 +0000822 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000823 SrcType, DestType,
John McCall1064d7e2010-03-16 05:22:47 +0000824 Paths.front(),
825 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000826 msg = 0;
827 return TC_Failed;
828 }
829
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000830 Self.BuildBasePathArray(Paths, BasePath);
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000831 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000832 return TC_Success;
833}
834
835/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
836/// C++ 5.2.9p9 is valid:
837///
838/// An rvalue of type "pointer to member of D of type cv1 T" can be
839/// converted to an rvalue of type "pointer to member of B of type cv2 T",
840/// where B is a base class of D [...].
841///
842TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +0000843TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
844 QualType DestType, bool CStyle,
845 const SourceRange &OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000846 unsigned &msg, CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000847 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000848 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000849 if (!DestMemPtr)
850 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +0000851
852 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +0000853 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +0000854 if (SrcExpr->getType() == Self.Context.OverloadTy) {
855 if (FunctionDecl *Fn
856 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
857 FoundOverload)) {
858 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
859 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
860 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
861 WasOverloadedFunction = true;
862 }
Douglas Gregorc934bc82010-03-07 23:24:59 +0000863 }
Douglas Gregor064fdb22010-04-14 23:11:21 +0000864
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000865 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000866 if (!SrcMemPtr) {
867 msg = diag::err_bad_static_cast_member_pointer_nonmp;
868 return TC_NotApplicable;
869 }
870
871 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000872 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
873 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000874 return TC_NotApplicable;
875
876 // B base of D
877 QualType SrcClass(SrcMemPtr->getClass(), 0);
878 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000879 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000880 /*DetectVirtual=*/true);
881 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
882 return TC_NotApplicable;
883 }
884
885 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +0000886 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000887 Paths.clear();
888 Paths.setRecordingPaths(true);
889 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
890 assert(StillOkay);
891 StillOkay = StillOkay;
892 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
893 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
894 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
895 msg = 0;
896 return TC_Failed;
897 }
898
899 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
900 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
901 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
902 msg = 0;
903 return TC_Failed;
904 }
905
John McCall5b0829a2010-02-10 09:31:12 +0000906 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedmand4c75cd2010-07-23 19:25:41 +0000907 DestClass, SrcClass,
John McCall1064d7e2010-03-16 05:22:47 +0000908 Paths.front(),
909 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000910 msg = 0;
911 return TC_Failed;
912 }
913
Douglas Gregorc934bc82010-03-07 23:24:59 +0000914 if (WasOverloadedFunction) {
915 // Resolve the address of the overloaded function again, this time
916 // allowing complaints if something goes wrong.
917 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
918 DestType,
John McCall16df1e52010-03-30 21:47:33 +0000919 true,
920 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000921 if (!Fn) {
922 msg = 0;
923 return TC_Failed;
924 }
925
John McCall16df1e52010-03-30 21:47:33 +0000926 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000927 if (!SrcExpr) {
928 msg = 0;
929 return TC_Failed;
930 }
931 }
932
Anders Carlssonb78feca2010-04-24 19:22:20 +0000933 Self.BuildBasePathArray(Paths, BasePath);
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000934 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000935 return TC_Success;
936}
937
938/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
939/// is valid:
940///
941/// An expression e can be explicitly converted to a type T using a
942/// @c static_cast if the declaration "T t(e);" is well-formed [...].
943TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000944TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000945 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000946 CastExpr::CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000947 if (DestType->isRecordType()) {
948 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
949 diag::err_bad_dynamic_cast_incomplete)) {
950 msg = 0;
951 return TC_Failed;
952 }
953 }
Douglas Gregorb33eed02010-04-16 22:09:46 +0000954
955 // At this point of CheckStaticCast, if the destination is a reference,
956 // this has to work. There is no other way that works.
957 // On the other hand, if we're checking a C-style cast, we've still got
958 // the reinterpret_cast way.
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000959 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
960 InitializationKind InitKind
Douglas Gregorb33eed02010-04-16 22:09:46 +0000961 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
962 CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000963 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregorb33eed02010-04-16 22:09:46 +0000964 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
965 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000966 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000967
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000968 Sema::OwningExprResult Result
Douglas Gregorb33eed02010-04-16 22:09:46 +0000969 = InitSeq.Perform(Self, Entity, InitKind,
John McCall37ad5512010-08-23 06:44:23 +0000970 Action::MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000971 if (Result.isInvalid()) {
972 msg = 0;
973 return TC_Failed;
974 }
975
Douglas Gregorb33eed02010-04-16 22:09:46 +0000976 if (InitSeq.isConstructorInitialization())
977 Kind = CastExpr::CK_ConstructorConversion;
978 else
979 Kind = CastExpr::CK_NoOp;
980
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000981 SrcExpr = Result.takeAs<Expr>();
982 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000983}
984
985/// TryConstCast - See if a const_cast from source to destination is allowed,
986/// and perform it if it is.
987static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
988 bool CStyle, unsigned &msg) {
989 DestType = Self.Context.getCanonicalType(DestType);
990 QualType SrcType = SrcExpr->getType();
991 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000992 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000993 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
994 // Cannot const_cast non-lvalue to lvalue reference type. But if this
995 // is C-style, static_cast might find a way, so we simply suggest a
996 // message and tell the parent to keep searching.
997 msg = diag::err_bad_cxx_cast_rvalue;
998 return TC_NotApplicable;
999 }
1000
1001 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1002 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1003 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1004 SrcType = Self.Context.getPointerType(SrcType);
1005 }
1006
1007 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1008 // the rules for const_cast are the same as those used for pointers.
1009
John McCall0e704f72010-05-18 09:35:29 +00001010 if (!DestType->isPointerType() &&
1011 !DestType->isMemberPointerType() &&
1012 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001013 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1014 // was a reference type, we converted it to a pointer above.
1015 // The status of rvalue references isn't entirely clear, but it looks like
1016 // conversion to them is simply invalid.
1017 // C++ 5.2.11p3: For two pointer types [...]
1018 if (!CStyle)
1019 msg = diag::err_bad_const_cast_dest;
1020 return TC_NotApplicable;
1021 }
1022 if (DestType->isFunctionPointerType() ||
1023 DestType->isMemberFunctionPointerType()) {
1024 // Cannot cast direct function pointers.
1025 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1026 // T is the ultimate pointee of source and target type.
1027 if (!CStyle)
1028 msg = diag::err_bad_const_cast_dest;
1029 return TC_NotApplicable;
1030 }
1031 SrcType = Self.Context.getCanonicalType(SrcType);
1032
1033 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1034 // completely equal.
1035 // FIXME: const_cast should probably not be able to convert between pointers
1036 // to different address spaces.
1037 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1038 // in multi-level pointers may change, but the level count must be the same,
1039 // as must be the final pointee type.
1040 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001041 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001042 Qualifiers Quals;
1043 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1044 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045 }
1046
1047 // Since we're dealing in canonical types, the remainder must be the same.
1048 if (SrcType != DestType)
1049 return TC_NotApplicable;
1050
1051 return TC_Success;
1052}
1053
1054static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1055 QualType DestType, bool CStyle,
1056 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001057 unsigned &msg,
1058 CastExpr::CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001059 bool IsLValueCast = false;
1060
Sebastian Redl9f831db2009-07-25 15:41:38 +00001061 DestType = Self.Context.getCanonicalType(DestType);
1062 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001063 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001064 bool LValue = DestTypeTmp->isLValueReferenceType();
1065 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1066 // Cannot cast non-lvalue to reference type. See the similar comment in
1067 // const_cast.
1068 msg = diag::err_bad_cxx_cast_rvalue;
1069 return TC_NotApplicable;
1070 }
1071
1072 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1073 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1074 // built-in & and * operators.
1075 // This code does this transformation for the checked types.
1076 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1077 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor51954272010-07-13 23:17:26 +00001078 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001079 }
1080
1081 // Canonicalize source for comparison.
1082 SrcType = Self.Context.getCanonicalType(SrcType);
1083
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001084 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1085 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001086 if (DestMemPtr && SrcMemPtr) {
1087 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1088 // can be explicitly converted to an rvalue of type "pointer to member
1089 // of Y of type T2" if T1 and T2 are both function types or both object
1090 // types.
1091 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1092 SrcMemPtr->getPointeeType()->isFunctionType())
1093 return TC_NotApplicable;
1094
1095 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1096 // constness.
1097 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1098 // we accept it.
1099 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1100 msg = diag::err_bad_cxx_cast_const_away;
1101 return TC_Failed;
1102 }
1103
Charles Davisebab1ed2010-08-16 05:30:44 +00001104 // Don't allow casting between member pointers of different sizes.
1105 if (Self.Context.getTypeSize(DestMemPtr) !=
1106 Self.Context.getTypeSize(SrcMemPtr)) {
1107 msg = diag::err_bad_cxx_cast_member_pointer_size;
1108 return TC_Failed;
1109 }
1110
Sebastian Redl9f831db2009-07-25 15:41:38 +00001111 // A valid member pointer cast.
Douglas Gregor51954272010-07-13 23:17:26 +00001112 Kind = IsLValueCast? CastExpr::CK_LValueBitCast : CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001113 return TC_Success;
1114 }
1115
1116 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001117 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001118 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1119 // type large enough to hold it. A value of std::nullptr_t can be
1120 // converted to an integral type; the conversion has the same meaning
1121 // and validity as a conversion of (void*)0 to the integral type.
1122 if (Self.Context.getTypeSize(SrcType) >
1123 Self.Context.getTypeSize(DestType)) {
1124 msg = diag::err_bad_reinterpret_cast_small_int;
1125 return TC_Failed;
1126 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001127 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001128 return TC_Success;
1129 }
1130
Anders Carlsson570af5d2009-09-16 19:19:43 +00001131 bool destIsVector = DestType->isVectorType();
1132 bool srcIsVector = SrcType->isVectorType();
1133 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001134 // FIXME: Should this also apply to floating point types?
1135 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1136 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001137
1138 // Check if this is a cast between a vector and something else.
1139 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1140 !(srcIsVector && destIsVector))
1141 return TC_NotApplicable;
1142
1143 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001144 if (Self.Context.getTypeSize(SrcType)
1145 == Self.Context.getTypeSize(DestType)) {
1146 Kind = CastExpr::CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001147 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001148 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001149
1150 if (destIsScalar)
1151 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1152 else if (srcIsScalar)
1153 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1154 else
1155 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1156
1157 return TC_Failed;
1158 }
1159
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001160 bool destIsPtr = DestType->isAnyPointerType() ||
1161 DestType->isBlockPointerType();
1162 bool srcIsPtr = SrcType->isAnyPointerType() ||
1163 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001164 if (!destIsPtr && !srcIsPtr) {
1165 // Except for std::nullptr_t->integer and lvalue->reference, which are
1166 // handled above, at least one of the two arguments must be a pointer.
1167 return TC_NotApplicable;
1168 }
1169
1170 if (SrcType == DestType) {
1171 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1172 // restrictions, a cast to the same type is allowed. The intent is not
1173 // entirely clear here, since all other paragraphs explicitly forbid casts
1174 // to the same type. However, the behavior of compilers is pretty consistent
1175 // on this point: allow same-type conversion if the involved types are
1176 // pointers, disallow otherwise.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001177 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001178 return TC_Success;
1179 }
1180
Douglas Gregor6972a622010-06-16 00:35:25 +00001181 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001182 assert(srcIsPtr && "One type must be a pointer");
1183 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1184 // type large enough to hold it.
1185 if (Self.Context.getTypeSize(SrcType) >
1186 Self.Context.getTypeSize(DestType)) {
1187 msg = diag::err_bad_reinterpret_cast_small_int;
1188 return TC_Failed;
1189 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001190 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001191 return TC_Success;
1192 }
1193
Douglas Gregorb90df602010-06-16 00:17:44 +00001194 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001195 assert(destIsPtr && "One type must be a pointer");
1196 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1197 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001198 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001199 return TC_Success;
1200 }
1201
1202 if (!destIsPtr || !srcIsPtr) {
1203 // With the valid non-pointer conversions out of the way, we can be even
1204 // more stringent.
1205 return TC_NotApplicable;
1206 }
1207
1208 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1209 // The C-style cast operator can.
1210 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1211 msg = diag::err_bad_cxx_cast_const_away;
1212 return TC_Failed;
1213 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001214
1215 // Cannot convert between block pointers and Objective-C object pointers.
1216 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1217 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1218 return TC_NotApplicable;
1219
1220 // Any pointer can be cast to an Objective-C pointer type with a C-style
1221 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001222 if (CStyle && DestType->isObjCObjectPointerType()) {
1223 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1224 return TC_Success;
1225 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001226
Sebastian Redl9f831db2009-07-25 15:41:38 +00001227 // Not casting away constness, so the only remaining check is for compatible
1228 // pointer categories.
Douglas Gregor51954272010-07-13 23:17:26 +00001229 Kind = IsLValueCast? CastExpr::CK_LValueBitCast : CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001230
1231 if (SrcType->isFunctionPointerType()) {
1232 if (DestType->isFunctionPointerType()) {
1233 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1234 // a pointer to a function of a different type.
1235 return TC_Success;
1236 }
1237
1238 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1239 // an object type or vice versa is conditionally-supported.
1240 // Compilers support it in C++03 too, though, because it's necessary for
1241 // casting the return value of dlsym() and GetProcAddress().
1242 // FIXME: Conditionally-supported behavior should be configurable in the
1243 // TargetInfo or similar.
1244 if (!Self.getLangOptions().CPlusPlus0x)
1245 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1246 return TC_Success;
1247 }
1248
1249 if (DestType->isFunctionPointerType()) {
1250 // See above.
1251 if (!Self.getLangOptions().CPlusPlus0x)
1252 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1253 return TC_Success;
1254 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001255
Sebastian Redl9f831db2009-07-25 15:41:38 +00001256 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1257 // a pointer to an object of different type.
1258 // Void pointers are not specified, but supported by every compiler out there.
1259 // So we finish by allowing everything that remains - it's got to be two
1260 // object pointers.
1261 return TC_Success;
1262}
1263
Anders Carlssona70cff62010-04-24 19:06:50 +00001264bool
1265Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
1266 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001267 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001268 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001269 // This test is outside everything else because it's the only case where
1270 // a non-lvalue-reference target type does not lead to decay.
1271 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001272 if (CastTy->isVoidType()) {
1273 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001274 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001275 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001276
1277 // If the type is dependent, we won't do any other semantic analysis now.
1278 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1279 return false;
1280
Douglas Gregorad8b2222009-11-06 01:14:41 +00001281 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001282 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001283
1284 // C++ [expr.cast]p5: The conversions performed by
1285 // - a const_cast,
1286 // - a static_cast,
1287 // - a static_cast followed by a const_cast,
1288 // - a reinterpret_cast, or
1289 // - a reinterpret_cast followed by a const_cast,
1290 // can be performed using the cast notation of explicit type conversion.
1291 // [...] If a conversion can be interpreted in more than one of the ways
1292 // listed above, the interpretation that appears first in the list is used,
1293 // even if a cast resulting from that interpretation is ill-formed.
1294 // In plain language, this means trying a const_cast ...
1295 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001296 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1297 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001298 if (tcr == TC_Success)
1299 Kind = CastExpr::CK_NoOp;
1300
Sebastian Redl9f831db2009-07-25 15:41:38 +00001301 if (tcr == TC_NotApplicable) {
1302 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001303 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1304 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001305 if (tcr == TC_NotApplicable) {
1306 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001307 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1308 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001309 }
1310 }
1311
Sebastian Redl9f831db2009-07-25 15:41:38 +00001312 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001313 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001314 << CastExpr->getType() << CastTy << R;
John McCall2b5c1b22010-08-12 21:44:57 +00001315 else if (Kind == CastExpr::CK_Unknown || Kind == CastExpr::CK_BitCast)
1316 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001317
1318 return tcr != TC_Success;
1319}