blob: 9f8b344562f80dd1c9e73961c6192bab2cb8bbe8 [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
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.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,
50 CXXBaseSpecifierArray &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,
55 CXXBaseSpecifierArray &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,
77 CXXBaseSpecifierArray &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,
83 CXXBaseSpecifierArray &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,
90 CXXBaseSpecifierArray &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,
97 CXXBaseSpecifierArray &BasePath);
98
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,
109 CXXBaseSpecifierArray &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);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000156 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000157 Ex, DestTInfo, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000158
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000159 case tok::kw_dynamic_cast: {
160 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000161 CXXBaseSpecifierArray BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000162 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000163 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000164 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson5d270e82010-04-24 18:38:56 +0000165 Kind, Ex, BasePath, DestTInfo,
166 OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000167 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000168 case tok::kw_reinterpret_cast: {
169 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000170 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000171 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000172 return Owned(new (Context) CXXReinterpretCastExpr(
173 DestType.getNonReferenceType(),
Anders Carlssona70cff62010-04-24 19:06:50 +0000174 Kind, Ex, CXXBaseSpecifierArray(),
175 DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000176 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000177 case tok::kw_static_cast: {
178 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000179 CXXBaseSpecifierArray BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000180 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000181 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000182
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000183 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson5d270e82010-04-24 18:38:56 +0000184 Kind, Ex, BasePath,
185 DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000186 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000187 }
188
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000189 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000190}
191
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000192/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
193/// this removes one level of indirection from both types, provided that they're
194/// the same kind of pointer (plain or to-member). Unlike the Sema function,
195/// this one doesn't care if the two pointers-to-member don't point into the
196/// same class. This is because CastsAwayConstness doesn't care.
197bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
198 const PointerType *T1PtrType = T1->getAs<PointerType>(),
199 *T2PtrType = T2->getAs<PointerType>();
200 if (T1PtrType && T2PtrType) {
201 T1 = T1PtrType->getPointeeType();
202 T2 = T2PtrType->getPointeeType();
203 return true;
204 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000205 const ObjCObjectPointerType *T1ObjCPtrType =
206 T1->getAs<ObjCObjectPointerType>(),
207 *T2ObjCPtrType =
208 T2->getAs<ObjCObjectPointerType>();
209 if (T1ObjCPtrType) {
210 if (T2ObjCPtrType) {
211 T1 = T1ObjCPtrType->getPointeeType();
212 T2 = T2ObjCPtrType->getPointeeType();
213 return true;
214 }
215 else if (T2PtrType) {
216 T1 = T1ObjCPtrType->getPointeeType();
217 T2 = T2PtrType->getPointeeType();
218 return true;
219 }
220 }
221 else if (T2ObjCPtrType) {
222 if (T1PtrType) {
223 T2 = T2ObjCPtrType->getPointeeType();
224 T1 = T1PtrType->getPointeeType();
225 return true;
226 }
227 }
228
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000229 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
230 *T2MPType = T2->getAs<MemberPointerType>();
231 if (T1MPType && T2MPType) {
232 T1 = T1MPType->getPointeeType();
233 T2 = T2MPType->getPointeeType();
234 return true;
235 }
236 return false;
237}
238
Sebastian Redla5a77a62009-01-27 23:18:31 +0000239/// CastsAwayConstness - Check if the pointer conversion from SrcType to
240/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
241/// the cast checkers. Both arguments must denote pointer (possibly to member)
242/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000243static bool
Mike Stump11289f42009-09-09 15:08:12 +0000244CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000245 // Casting away constness is defined in C++ 5.2.11p8 with reference to
246 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
247 // the rules are non-trivial. So first we construct Tcv *...cv* as described
248 // in C++ 5.2.11p8.
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000249 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000250 "Source type is not pointer or pointer to member.");
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000251 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000252 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000253
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000254 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
255 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000256 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000257
258 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000259 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000260 cv1.push_back(UnwrappedSrcType.getQualifiers());
261 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000262 }
263 assert(cv1.size() > 0 && "Must have at least one pointer level.");
264
265 // Construct void pointers with those qualifiers (in reverse order of
266 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000267 QualType SrcConstruct = Self.Context.VoidTy;
268 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000269 ASTContext &Context = Self.Context;
270 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
271 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000272 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000273 SrcConstruct
274 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
275 DestConstruct
276 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000277 }
278
279 // Test if they're compatible.
280 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000281 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000282}
283
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000284/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
285/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
286/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000287static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000288CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
289 const SourceRange &OpRange,
Anders Carlssona70cff62010-04-24 19:06:50 +0000290 const SourceRange &DestRange, CastExpr::CastKind &Kind,
291 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000292 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000293 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000294
295 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
296 // or "pointer to cv void".
297
298 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000299 const PointerType *DestPointer = DestType->getAs<PointerType>();
300 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000301 if (DestPointer) {
302 DestPointee = DestPointer->getPointeeType();
303 } else if (DestReference) {
304 DestPointee = DestReference->getPointeeType();
305 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000306 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000307 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000308 return;
309 }
310
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000311 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000312 if (DestPointee->isVoidType()) {
313 assert(DestPointer && "Reference to void is not possible");
314 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000315 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000316 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000317 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000318 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000319 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000320 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000321 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000322 return;
323 }
324
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000325 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
326 // complete class type, [...]. If T is an lvalue reference type, v shall be
327 // an lvalue of a complete class type, [...]. If T is an rvalue reference
328 // type, v shall be an expression having a complete effective class type,
329 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000330
Sebastian Redl842ef522008-11-08 13:00:26 +0000331 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000332 QualType SrcPointee;
333 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000334 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000335 SrcPointee = SrcPointer->getPointeeType();
336 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000337 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000338 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000339 return;
340 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000341 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000342 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000343 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000344 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000345 }
346 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000347 } else {
348 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000349 }
350
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000351 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000352 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000353 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000354 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000355 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000356 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000357 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000358 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000359 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000360 return;
361 }
362
363 assert((DestPointer || DestReference) &&
364 "Bad destination non-ptr/ref slipped through.");
365 assert((DestRecord || DestPointee->isVoidType()) &&
366 "Bad destination pointee slipped through.");
367 assert(SrcRecord && "Bad source pointee slipped through.");
368
369 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
370 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000371 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000372 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000373 return;
374 }
375
376 // C++ 5.2.7p3: If the type of v is the same as the required result type,
377 // [except for cv].
378 if (DestRecord == SrcRecord) {
379 return;
380 }
381
382 // C++ 5.2.7p5
383 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000384 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000385 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
386 OpRange.getBegin(), OpRange,
387 &BasePath))
388 return;
389
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000390 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000391 return;
392 }
393
394 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000395 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000396 assert(SrcDecl && "Definition missing");
397 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000398 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000399 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000400 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000401
402 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000403 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000404}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000405
406/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
407/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
408/// like this:
409/// const char *str = "literal";
410/// legacy_function(const_cast\<char*\>(str));
411void
412CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000413 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000414 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000415 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000416
417 unsigned msg = diag::err_bad_cxx_cast_generic;
418 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
419 && msg != 0)
420 Self.Diag(OpRange.getBegin(), msg) << CT_Const
421 << SrcExpr->getType() << DestType << OpRange;
422}
423
424/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
425/// valid.
426/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
427/// like this:
428/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
429void
430CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000431 const SourceRange &OpRange, const SourceRange &DestRange,
432 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000433 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000434 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000435
436 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000437 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
438 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000439 != TC_Success && msg != 0)
440 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
441 << SrcExpr->getType() << DestType << OpRange;
442}
443
444
445/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
446/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
447/// implicit conversions explicit and getting rid of data loss warnings.
448void
449CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssona70cff62010-04-24 19:06:50 +0000450 const SourceRange &OpRange, CastExpr::CastKind &Kind,
451 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000452 // This test is outside everything else because it's the only case where
453 // a non-lvalue-reference target type does not lead to decay.
454 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000455 if (DestType->isVoidType()) {
456 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000457 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000458 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000459
Douglas Gregorad8b2222009-11-06 01:14:41 +0000460 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000461 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000462
463 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000464 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000465 Kind, BasePath) != TC_Success && msg != 0)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000466 Self.Diag(OpRange.getBegin(), msg) << CT_Static
467 << SrcExpr->getType() << DestType << OpRange;
468}
469
470/// TryStaticCast - Check if a static cast can be performed, and do so if
471/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
472/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000473static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000474 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000475 const SourceRange &OpRange, unsigned &msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000476 CastExpr::CastKind &Kind,
477 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000478 // The order the tests is not entirely arbitrary. There is one conversion
479 // that can be handled in two different ways. Given:
480 // struct A {};
481 // struct B : public A {
482 // B(); B(const A&);
483 // };
484 // const A &a = B();
485 // the cast static_cast<const B&>(a) could be seen as either a static
486 // reference downcast, or an explicit invocation of the user-defined
487 // conversion using B's conversion constructor.
488 // DR 427 specifies that the downcast is to be applied here.
489
490 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
491 // Done outside this function.
492
493 TryCastResult tcr;
494
495 // C++ 5.2.9p5, reference downcast.
496 // See the function for details.
497 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000498 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000499 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000500 if (tcr != TC_NotApplicable)
501 return tcr;
502
503 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
504 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
505 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000506 if (tcr != TC_NotApplicable) {
507 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000508 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000509 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000510
511 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
512 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000513 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000514 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000515 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000516 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000517
Sebastian Redl9f831db2009-07-25 15:41:38 +0000518 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
519 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
520 // conversions, subject to further restrictions.
521 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
522 // of qualification conversions impossible.
523 // In the CStyle case, the earlier attempt to const_cast should have taken
524 // care of reverse qualification conversions.
525
526 QualType OrigSrcType = SrcExpr->getType();
527
528 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
529
530 // Reverse integral promotion/conversion. All such conversions are themselves
531 // again integral promotions or conversions and are thus already handled by
532 // p2 (TryDirectInitialization above).
533 // (Note: any data loss warnings should be suppressed.)
534 // The exception is the reverse of enum->integer, i.e. integer->enum (and
535 // enum->enum). See also C++ 5.2.9p7.
536 // The same goes for reverse floating point promotion/conversion and
537 // floating-integral conversions. Again, only floating->enum is relevant.
538 if (DestType->isEnumeralType()) {
539 if (SrcType->isComplexType() || SrcType->isVectorType()) {
540 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000541 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
542 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000543 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000544 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000545 }
546
547 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
548 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000549 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000550 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000551 if (tcr != TC_NotApplicable)
552 return tcr;
553
554 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
555 // conversion. C++ 5.2.9p9 has additional information.
556 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000557 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000558 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000559 if (tcr != TC_NotApplicable)
560 return tcr;
561
562 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
563 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
564 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000565 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000566 QualType SrcPointee = SrcPointer->getPointeeType();
567 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000568 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000569 QualType DestPointee = DestPointer->getPointeeType();
570 if (DestPointee->isIncompleteOrObjectType()) {
571 // This is definitely the intended conversion, but it might fail due
572 // to a const violation.
573 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
574 msg = diag::err_bad_cxx_cast_const_away;
575 return TC_Failed;
576 }
Eli Friedman03bf60a2009-11-16 05:44:20 +0000577 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000578 return TC_Success;
579 }
580 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000581 else if (DestType->isObjCObjectPointerType()) {
582 // allow both c-style cast and static_cast of objective-c pointers as
583 // they are pervasive.
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000584 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
585 return TC_Success;
586 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000587 else if (CStyle && DestType->isBlockPointerType()) {
588 // allow c-style cast of void * to block pointers.
589 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
590 return TC_Success;
591 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000592 }
593 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000594 // Allow arbitray objective-c pointer conversion with static casts.
595 if (SrcType->isObjCObjectPointerType() &&
596 DestType->isObjCObjectPointerType())
597 return TC_Success;
598
Sebastian Redl9f831db2009-07-25 15:41:38 +0000599 // We tried everything. Everything! Nothing works! :-(
600 return TC_NotApplicable;
601}
602
603/// Tests whether a conversion according to N2844 is valid.
604TryCastResult
605TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000606 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000607 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
608 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000609 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000610 if (!R)
611 return TC_NotApplicable;
612
613 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
614 return TC_NotApplicable;
615
616 // Because we try the reference downcast before this function, from now on
617 // this is the only cast possibility, so we issue an error if we fail now.
618 // FIXME: Should allow casting away constness if CStyle.
619 bool DerivedToBase;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000620 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
621 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9f831db2009-07-25 15:41:38 +0000622 DerivedToBase) <
623 Sema::Ref_Compatible_With_Added_Qualification) {
624 msg = diag::err_bad_lvalue_to_rvalue_cast;
625 return TC_Failed;
626 }
627
Douglas Gregor031296e2010-03-25 00:20:38 +0000628 // FIXME: We should probably have an AST node for lvalue-to-rvalue
629 // conversions.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000630 return TC_Success;
631}
632
633/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
634TryCastResult
635TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
636 bool CStyle, const SourceRange &OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000637 unsigned &msg, CastExpr::CastKind &Kind,
638 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000639 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
640 // cast to type "reference to cv2 D", where D is a class derived from B,
641 // if a valid standard conversion from "pointer to D" to "pointer to B"
642 // exists, cv2 >= cv1, and B is not a virtual base class of D.
643 // In addition, DR54 clarifies that the base must be accessible in the
644 // current context. Although the wording of DR54 only applies to the pointer
645 // variant of this rule, the intent is clearly for it to apply to the this
646 // conversion as well.
647
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000648 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000649 if (!DestReference) {
650 return TC_NotApplicable;
651 }
652 bool RValueRef = DestReference->isRValueReferenceType();
653 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
654 // We know the left side is an lvalue reference, so we can suggest a reason.
655 msg = diag::err_bad_cxx_cast_rvalue;
656 return TC_NotApplicable;
657 }
658
659 QualType DestPointee = DestReference->getPointeeType();
660
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000661 return TryStaticDowncast(Self,
662 Self.Context.getCanonicalType(SrcExpr->getType()),
663 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000664 OpRange, SrcExpr->getType(), DestType, msg, Kind,
665 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000666}
667
668/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
669TryCastResult
670TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000671 bool CStyle, const SourceRange &OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000672 unsigned &msg, CastExpr::CastKind &Kind,
673 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000674 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
675 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
676 // is a class derived from B, if a valid standard conversion from "pointer
677 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
678 // class of D.
679 // In addition, DR54 clarifies that the base must be accessible in the
680 // current context.
681
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000682 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000683 if (!DestPointer) {
684 return TC_NotApplicable;
685 }
686
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000687 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000688 if (!SrcPointer) {
689 msg = diag::err_bad_static_cast_pointer_nonpointer;
690 return TC_NotApplicable;
691 }
692
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000693 return TryStaticDowncast(Self,
694 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
695 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000696 CStyle, OpRange, SrcType, DestType, msg, Kind,
697 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000698}
699
700/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
701/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000702/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000703TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000704TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000705 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000706 QualType OrigDestType, unsigned &msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000707 CastExpr::CastKind &Kind, CXXBaseSpecifierArray &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000708 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000709 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
710 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000711 return TC_NotApplicable;
712
Sebastian Redl9f831db2009-07-25 15:41:38 +0000713 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000714 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000715 return TC_NotApplicable;
716 }
717
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000719 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000720 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
721 return TC_NotApplicable;
722 }
723
724 // Target type does derive from source type. Now we're serious. If an error
725 // appears now, it's not ignored.
726 // This may not be entirely in line with the standard. Take for example:
727 // struct A {};
728 // struct B : virtual A {
729 // B(A&);
730 // };
Mike Stump11289f42009-09-09 15:08:12 +0000731 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000732 // void f()
733 // {
734 // (void)static_cast<const B&>(*((A*)0));
735 // }
736 // As far as the standard is concerned, p5 does not apply (A is virtual), so
737 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
738 // However, both GCC and Comeau reject this example, and accepting it would
739 // mean more complex code if we're to preserve the nice error message.
740 // FIXME: Being 100% compliant here would be nice to have.
741
742 // Must preserve cv, as always, unless we're in C-style mode.
743 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
744 msg = diag::err_bad_cxx_cast_const_away;
745 return TC_Failed;
746 }
747
748 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
749 // This code is analoguous to that in CheckDerivedToBaseConversion, except
750 // that it builds the paths in reverse order.
751 // To sum up: record all paths to the base and build a nice string from
752 // them. Use it to spice up the error message.
753 if (!Paths.isRecordingPaths()) {
754 Paths.clear();
755 Paths.setRecordingPaths(true);
756 Self.IsDerivedFrom(DestType, SrcType, Paths);
757 }
758 std::string PathDisplayStr;
759 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000760 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000761 PI != PE; ++PI) {
762 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
763 // We haven't displayed a path to this particular base
764 // class subobject yet.
765 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000766 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
767 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000768 EI != EE; ++EI)
769 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000770 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000771 }
772 }
773
774 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000775 << QualType(SrcType).getUnqualifiedType()
776 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000777 << PathDisplayStr << OpRange;
778 msg = 0;
779 return TC_Failed;
780 }
781
782 if (Paths.getDetectedVirtual() != 0) {
783 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
784 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
785 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
786 msg = 0;
787 return TC_Failed;
788 }
789
John McCall5b0829a2010-02-10 09:31:12 +0000790 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000791 SrcType, DestType,
John McCall1064d7e2010-03-16 05:22:47 +0000792 Paths.front(),
793 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000794 msg = 0;
795 return TC_Failed;
796 }
797
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000798 Self.BuildBasePathArray(Paths, BasePath);
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000799 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000800 return TC_Success;
801}
802
803/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
804/// C++ 5.2.9p9 is valid:
805///
806/// An rvalue of type "pointer to member of D of type cv1 T" can be
807/// converted to an rvalue of type "pointer to member of B of type cv2 T",
808/// where B is a base class of D [...].
809///
810TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +0000811TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
812 QualType DestType, bool CStyle,
813 const SourceRange &OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000814 unsigned &msg, CastExpr::CastKind &Kind,
815 CXXBaseSpecifierArray &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000816 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000817 if (!DestMemPtr)
818 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +0000819
820 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +0000821 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +0000822 if (SrcExpr->getType() == Self.Context.OverloadTy) {
823 if (FunctionDecl *Fn
824 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
825 FoundOverload)) {
826 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
827 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
828 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
829 WasOverloadedFunction = true;
830 }
Douglas Gregorc934bc82010-03-07 23:24:59 +0000831 }
Douglas Gregor064fdb22010-04-14 23:11:21 +0000832
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000833 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000834 if (!SrcMemPtr) {
835 msg = diag::err_bad_static_cast_member_pointer_nonmp;
836 return TC_NotApplicable;
837 }
838
839 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000840 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
841 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000842 return TC_NotApplicable;
843
844 // B base of D
845 QualType SrcClass(SrcMemPtr->getClass(), 0);
846 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000847 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000848 /*DetectVirtual=*/true);
849 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
850 return TC_NotApplicable;
851 }
852
853 // B is a base of D. But is it an allowed base? If not, it's a hard error.
854 if (Paths.isAmbiguous(DestClass)) {
855 Paths.clear();
856 Paths.setRecordingPaths(true);
857 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
858 assert(StillOkay);
859 StillOkay = StillOkay;
860 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
861 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
862 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
863 msg = 0;
864 return TC_Failed;
865 }
866
867 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
868 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
869 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
870 msg = 0;
871 return TC_Failed;
872 }
873
John McCall5b0829a2010-02-10 09:31:12 +0000874 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000875 DestType, SrcType,
John McCall1064d7e2010-03-16 05:22:47 +0000876 Paths.front(),
877 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000878 msg = 0;
879 return TC_Failed;
880 }
881
Douglas Gregorc934bc82010-03-07 23:24:59 +0000882 if (WasOverloadedFunction) {
883 // Resolve the address of the overloaded function again, this time
884 // allowing complaints if something goes wrong.
885 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
886 DestType,
John McCall16df1e52010-03-30 21:47:33 +0000887 true,
888 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000889 if (!Fn) {
890 msg = 0;
891 return TC_Failed;
892 }
893
John McCall16df1e52010-03-30 21:47:33 +0000894 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000895 if (!SrcExpr) {
896 msg = 0;
897 return TC_Failed;
898 }
899 }
900
Anders Carlssonb78feca2010-04-24 19:22:20 +0000901 Self.BuildBasePathArray(Paths, BasePath);
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000902 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000903 return TC_Success;
904}
905
906/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
907/// is valid:
908///
909/// An expression e can be explicitly converted to a type T using a
910/// @c static_cast if the declaration "T t(e);" is well-formed [...].
911TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000912TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000913 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000914 CastExpr::CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000915 if (DestType->isRecordType()) {
916 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
917 diag::err_bad_dynamic_cast_incomplete)) {
918 msg = 0;
919 return TC_Failed;
920 }
921 }
Douglas Gregorb33eed02010-04-16 22:09:46 +0000922
923 // At this point of CheckStaticCast, if the destination is a reference,
924 // this has to work. There is no other way that works.
925 // On the other hand, if we're checking a C-style cast, we've still got
926 // the reinterpret_cast way.
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000927 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
928 InitializationKind InitKind
Douglas Gregorb33eed02010-04-16 22:09:46 +0000929 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
930 CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000931 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregorb33eed02010-04-16 22:09:46 +0000932 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
933 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000934 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000935
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000936 Sema::OwningExprResult Result
Douglas Gregorb33eed02010-04-16 22:09:46 +0000937 = InitSeq.Perform(Self, Entity, InitKind,
938 Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000939 if (Result.isInvalid()) {
940 msg = 0;
941 return TC_Failed;
942 }
943
Douglas Gregorb33eed02010-04-16 22:09:46 +0000944 if (InitSeq.isConstructorInitialization())
945 Kind = CastExpr::CK_ConstructorConversion;
946 else
947 Kind = CastExpr::CK_NoOp;
948
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000949 SrcExpr = Result.takeAs<Expr>();
950 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000951}
952
953/// TryConstCast - See if a const_cast from source to destination is allowed,
954/// and perform it if it is.
955static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
956 bool CStyle, unsigned &msg) {
957 DestType = Self.Context.getCanonicalType(DestType);
958 QualType SrcType = SrcExpr->getType();
959 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000960 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000961 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
962 // Cannot const_cast non-lvalue to lvalue reference type. But if this
963 // is C-style, static_cast might find a way, so we simply suggest a
964 // message and tell the parent to keep searching.
965 msg = diag::err_bad_cxx_cast_rvalue;
966 return TC_NotApplicable;
967 }
968
969 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
970 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
971 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
972 SrcType = Self.Context.getPointerType(SrcType);
973 }
974
975 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
976 // the rules for const_cast are the same as those used for pointers.
977
978 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
979 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
980 // was a reference type, we converted it to a pointer above.
981 // The status of rvalue references isn't entirely clear, but it looks like
982 // conversion to them is simply invalid.
983 // C++ 5.2.11p3: For two pointer types [...]
984 if (!CStyle)
985 msg = diag::err_bad_const_cast_dest;
986 return TC_NotApplicable;
987 }
988 if (DestType->isFunctionPointerType() ||
989 DestType->isMemberFunctionPointerType()) {
990 // Cannot cast direct function pointers.
991 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
992 // T is the ultimate pointee of source and target type.
993 if (!CStyle)
994 msg = diag::err_bad_const_cast_dest;
995 return TC_NotApplicable;
996 }
997 SrcType = Self.Context.getCanonicalType(SrcType);
998
999 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1000 // completely equal.
1001 // FIXME: const_cast should probably not be able to convert between pointers
1002 // to different address spaces.
1003 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1004 // in multi-level pointers may change, but the level count must be the same,
1005 // as must be the final pointee type.
1006 while (SrcType != DestType &&
1007 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001008 Qualifiers Quals;
1009 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1010 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001011 }
1012
1013 // Since we're dealing in canonical types, the remainder must be the same.
1014 if (SrcType != DestType)
1015 return TC_NotApplicable;
1016
1017 return TC_Success;
1018}
1019
1020static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1021 QualType DestType, bool CStyle,
1022 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001023 unsigned &msg,
1024 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 DestType = Self.Context.getCanonicalType(DestType);
1026 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001027 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001028 bool LValue = DestTypeTmp->isLValueReferenceType();
1029 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1030 // Cannot cast non-lvalue to reference type. See the similar comment in
1031 // const_cast.
1032 msg = diag::err_bad_cxx_cast_rvalue;
1033 return TC_NotApplicable;
1034 }
1035
1036 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1037 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1038 // built-in & and * operators.
1039 // This code does this transformation for the checked types.
1040 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1041 SrcType = Self.Context.getPointerType(SrcType);
1042 }
1043
1044 // Canonicalize source for comparison.
1045 SrcType = Self.Context.getCanonicalType(SrcType);
1046
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001047 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1048 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001049 if (DestMemPtr && SrcMemPtr) {
1050 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1051 // can be explicitly converted to an rvalue of type "pointer to member
1052 // of Y of type T2" if T1 and T2 are both function types or both object
1053 // types.
1054 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1055 SrcMemPtr->getPointeeType()->isFunctionType())
1056 return TC_NotApplicable;
1057
1058 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1059 // constness.
1060 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1061 // we accept it.
1062 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1063 msg = diag::err_bad_cxx_cast_const_away;
1064 return TC_Failed;
1065 }
1066
1067 // A valid member pointer cast.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001068 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001069 return TC_Success;
1070 }
1071
1072 // See below for the enumeral issue.
1073 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1074 !DestType->isEnumeralType()) {
1075 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1076 // type large enough to hold it. A value of std::nullptr_t can be
1077 // converted to an integral type; the conversion has the same meaning
1078 // and validity as a conversion of (void*)0 to the integral type.
1079 if (Self.Context.getTypeSize(SrcType) >
1080 Self.Context.getTypeSize(DestType)) {
1081 msg = diag::err_bad_reinterpret_cast_small_int;
1082 return TC_Failed;
1083 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001084 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001085 return TC_Success;
1086 }
1087
Anders Carlsson570af5d2009-09-16 19:19:43 +00001088 bool destIsVector = DestType->isVectorType();
1089 bool srcIsVector = SrcType->isVectorType();
1090 if (srcIsVector || destIsVector) {
1091 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1092 bool destIsScalar =
1093 DestType->isIntegralType() && !DestType->isEnumeralType();
1094
1095 // Check if this is a cast between a vector and something else.
1096 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1097 !(srcIsVector && destIsVector))
1098 return TC_NotApplicable;
1099
1100 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001101 if (Self.Context.getTypeSize(SrcType)
1102 == Self.Context.getTypeSize(DestType)) {
1103 Kind = CastExpr::CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001104 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001105 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001106
1107 if (destIsScalar)
1108 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1109 else if (srcIsScalar)
1110 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1111 else
1112 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1113
1114 return TC_Failed;
1115 }
1116
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +00001117 bool destIsPtr = DestType->isAnyPointerType();
1118 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001119 if (!destIsPtr && !srcIsPtr) {
1120 // Except for std::nullptr_t->integer and lvalue->reference, which are
1121 // handled above, at least one of the two arguments must be a pointer.
1122 return TC_NotApplicable;
1123 }
1124
1125 if (SrcType == DestType) {
1126 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1127 // restrictions, a cast to the same type is allowed. The intent is not
1128 // entirely clear here, since all other paragraphs explicitly forbid casts
1129 // to the same type. However, the behavior of compilers is pretty consistent
1130 // on this point: allow same-type conversion if the involved types are
1131 // pointers, disallow otherwise.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001132 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001133 return TC_Success;
1134 }
1135
1136 // Note: Clang treats enumeration types as integral types. If this is ever
1137 // changed for C++, the additional check here will be redundant.
1138 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1139 assert(srcIsPtr && "One type must be a pointer");
1140 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1141 // type large enough to hold it.
1142 if (Self.Context.getTypeSize(SrcType) >
1143 Self.Context.getTypeSize(DestType)) {
1144 msg = diag::err_bad_reinterpret_cast_small_int;
1145 return TC_Failed;
1146 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001147 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001148 return TC_Success;
1149 }
1150
1151 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1152 assert(destIsPtr && "One type must be a pointer");
1153 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1154 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001155 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001156 return TC_Success;
1157 }
1158
1159 if (!destIsPtr || !srcIsPtr) {
1160 // With the valid non-pointer conversions out of the way, we can be even
1161 // more stringent.
1162 return TC_NotApplicable;
1163 }
1164
1165 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1166 // The C-style cast operator can.
1167 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1168 msg = diag::err_bad_cxx_cast_const_away;
1169 return TC_Failed;
1170 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001171 if (CStyle && DestType->isObjCObjectPointerType()) {
1172 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1173 return TC_Success;
1174 }
1175
Sebastian Redl9f831db2009-07-25 15:41:38 +00001176 // Not casting away constness, so the only remaining check is for compatible
1177 // pointer categories.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001178 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001179
1180 if (SrcType->isFunctionPointerType()) {
1181 if (DestType->isFunctionPointerType()) {
1182 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1183 // a pointer to a function of a different type.
1184 return TC_Success;
1185 }
1186
1187 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1188 // an object type or vice versa is conditionally-supported.
1189 // Compilers support it in C++03 too, though, because it's necessary for
1190 // casting the return value of dlsym() and GetProcAddress().
1191 // FIXME: Conditionally-supported behavior should be configurable in the
1192 // TargetInfo or similar.
1193 if (!Self.getLangOptions().CPlusPlus0x)
1194 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1195 return TC_Success;
1196 }
1197
1198 if (DestType->isFunctionPointerType()) {
1199 // See above.
1200 if (!Self.getLangOptions().CPlusPlus0x)
1201 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1202 return TC_Success;
1203 }
1204
1205 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1206 // a pointer to an object of different type.
1207 // Void pointers are not specified, but supported by every compiler out there.
1208 // So we finish by allowing everything that remains - it's got to be two
1209 // object pointers.
1210 return TC_Success;
1211}
1212
Anders Carlssona70cff62010-04-24 19:06:50 +00001213bool
1214Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
1215 CastExpr::CastKind &Kind,
1216 CXXBaseSpecifierArray &BasePath,
1217 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001218 // This test is outside everything else because it's the only case where
1219 // a non-lvalue-reference target type does not lead to decay.
1220 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001221 if (CastTy->isVoidType()) {
1222 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001223 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001224 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001225
1226 // If the type is dependent, we won't do any other semantic analysis now.
1227 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1228 return false;
1229
Douglas Gregorad8b2222009-11-06 01:14:41 +00001230 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001231 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001232
1233 // C++ [expr.cast]p5: The conversions performed by
1234 // - a const_cast,
1235 // - a static_cast,
1236 // - a static_cast followed by a const_cast,
1237 // - a reinterpret_cast, or
1238 // - a reinterpret_cast followed by a const_cast,
1239 // can be performed using the cast notation of explicit type conversion.
1240 // [...] If a conversion can be interpreted in more than one of the ways
1241 // listed above, the interpretation that appears first in the list is used,
1242 // even if a cast resulting from that interpretation is ill-formed.
1243 // In plain language, this means trying a const_cast ...
1244 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001245 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1246 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001247 if (tcr == TC_Success)
1248 Kind = CastExpr::CK_NoOp;
1249
Sebastian Redl9f831db2009-07-25 15:41:38 +00001250 if (tcr == TC_NotApplicable) {
1251 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001252 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1253 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001254 if (tcr == TC_NotApplicable) {
1255 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001256 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1257 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001258 }
1259 }
1260
Sebastian Redl9f831db2009-07-25 15:41:38 +00001261 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001262 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001263 << CastExpr->getType() << CastTy << R;
1264
1265 return tcr != TC_Success;
1266}