blob: e5ad338502df1736ef8a5b3cb01acc63d8d8f1df [file] [log] [blame]
Sebastian Redl26d85b12008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000015#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000018#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000019#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl9cc11e72009-07-25 15:41:38 +000023enum TryCastResult {
24 TC_NotApplicable, ///< The cast method is not applicable.
25 TC_Success, ///< The cast method is appropriate and successful.
26 TC_Failed ///< The cast method is appropriate, but failed. A
27 ///< diagnostic has been emitted.
28};
29
30enum CastType {
31 CT_Const, ///< const_cast
32 CT_Static, ///< static_cast
33 CT_Reinterpret, ///< reinterpret_cast
34 CT_Dynamic, ///< dynamic_cast
35 CT_CStyle, ///< (Type)expr
36 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000037};
38
39static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
40 const SourceRange &OpRange,
41 const SourceRange &DestRange);
42static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
43 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000044 const SourceRange &DestRange,
45 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000046static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000047 const SourceRange &OpRange,
Anders Carlsson0aebc812009-09-09 21:33:21 +000048 CastExpr::CastKind &Kind,
49 CXXMethodDecl *&ConversionDecl);
Sebastian Redl37d6de32008-11-08 13:00:26 +000050static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
51 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000052 const SourceRange &DestRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000053 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000054
55static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000056
57// The Try functions attempt a specific way of casting. If they succeed, they
58// return TC_Success. If their way of casting is not appropriate for the given
59// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
60// to emit if no other way succeeds. If their way of casting is appropriate but
61// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
62// they emit a specialized diagnostic.
63// All diagnostics returned by these functions must expect the same three
64// arguments:
65// %0: Cast Type (a value from the CastType enumeration)
66// %1: Source Type
67// %2: Destination Type
68static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
69 QualType DestType, unsigned &msg);
70static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, bool CStyle,
72 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000073 unsigned &msg,
74 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000075static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
76 QualType DestType, bool CStyle,
77 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000078 unsigned &msg,
79 CastExpr::CastKind &Kind);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000080static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
81 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000082 const SourceRange &OpRange,
83 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000084 QualType OrigDestType, unsigned &msg,
85 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000086static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
87 QualType DestType,bool CStyle,
88 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +000089 unsigned &msg,
90 CastExpr::CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000091static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000092 QualType DestType, bool CStyle,
93 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000094 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000095 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000096 CXXMethodDecl *&ConversionDecl);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000097static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000098 QualType DestType, bool CStyle,
99 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000100 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000101 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000102 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000103static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
104 bool CStyle, unsigned &msg);
105static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
106 QualType DestType, bool CStyle,
107 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000108 unsigned &msg,
109 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000110
Sebastian Redl26d85b12008-11-05 21:50:06 +0000111/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000112Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
114 SourceLocation LAngleBracketLoc, TypeTy *Ty,
115 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000116 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000117 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000118 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000119 // FIXME: Preserve type source info.
120 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000121 SourceRange OpRange(OpLoc, RParenLoc);
122 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
123
Douglas Gregor9103bb22008-12-17 22:52:20 +0000124 // If the type is dependent, we won't do the semantic analysis now.
125 // FIXME: should we check this in a more fine-grained manner?
126 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
127
Sebastian Redl26d85b12008-11-05 21:50:06 +0000128 switch (Kind) {
129 default: assert(0 && "Unknown C++ cast!");
130
131 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000132 if (!TypeDependent)
133 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000134 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
135 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000136
Anders Carlsson714179b2009-08-02 19:07:59 +0000137 case tok::kw_dynamic_cast: {
138 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000139 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000140 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000141 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000142 Kind, Ex, DestType, OpLoc));
143 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000144 case tok::kw_reinterpret_cast: {
145 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000146 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000147 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000148 return Owned(new (Context) CXXReinterpretCastExpr(
149 DestType.getNonReferenceType(),
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000150 Kind, Ex, DestType, OpLoc));
151 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000152 case tok::kw_static_cast: {
153 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000154 if (!TypeDependent) {
155 CXXMethodDecl *Method = 0;
156
157 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
158
159 if (Method) {
160 OwningExprResult CastArg
161 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
162 Kind, Method, Owned(Ex));
163 if (CastArg.isInvalid())
164 return ExprError();
165
166 Ex = CastArg.takeAs<Expr>();
167 }
168 }
169
Sebastian Redlf53597f2009-03-15 17:47:39 +0000170 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000171 Kind, Ex, DestType, OpLoc));
172 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000173 }
174
Sebastian Redlf53597f2009-03-15 17:47:39 +0000175 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000176}
177
Sebastian Redldb647282009-01-27 23:18:31 +0000178/// CastsAwayConstness - Check if the pointer conversion from SrcType to
179/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
180/// the cast checkers. Both arguments must denote pointer (possibly to member)
181/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000182static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000183CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000184 // Casting away constness is defined in C++ 5.2.11p8 with reference to
185 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
186 // the rules are non-trivial. So first we construct Tcv *...cv* as described
187 // in C++ 5.2.11p8.
188 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
189 "Source type is not pointer or pointer to member.");
190 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
191 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000192
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000193 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
194 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000195 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000196
197 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000198 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000199 cv1.push_back(UnwrappedSrcType.getQualifiers());
200 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000201 }
202 assert(cv1.size() > 0 && "Must have at least one pointer level.");
203
204 // Construct void pointers with those qualifiers (in reverse order of
205 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000206 QualType SrcConstruct = Self.Context.VoidTy;
207 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000208 ASTContext &Context = Self.Context;
209 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
210 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000211 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000212 SrcConstruct
213 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
214 DestConstruct
215 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216 }
217
218 // Test if they're compatible.
219 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000220 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000221}
222
Sebastian Redl26d85b12008-11-05 21:50:06 +0000223/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
224/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
225/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000226static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000227CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
228 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000229 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000230 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000231 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000232
233 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
234 // or "pointer to cv void".
235
236 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000237 const PointerType *DestPointer = DestType->getAs<PointerType>();
238 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000239 if (DestPointer) {
240 DestPointee = DestPointer->getPointeeType();
241 } else if (DestReference) {
242 DestPointee = DestReference->getPointeeType();
243 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000244 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000245 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000246 return;
247 }
248
Ted Kremenek6217b802009-07-29 21:53:49 +0000249 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000250 if (DestPointee->isVoidType()) {
251 assert(DestPointer && "Reference to void is not possible");
252 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000253 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000254 PDiag(diag::err_bad_dynamic_cast_incomplete)
255 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000256 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000257 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000258 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000259 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000260 return;
261 }
262
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000263 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
264 // complete class type, [...]. If T is an lvalue reference type, v shall be
265 // an lvalue of a complete class type, [...]. If T is an rvalue reference
266 // type, v shall be an expression having a complete effective class type,
267 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268
Sebastian Redl37d6de32008-11-08 13:00:26 +0000269 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000270 QualType SrcPointee;
271 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000272 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000273 SrcPointee = SrcPointer->getPointeeType();
274 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000275 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000276 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000277 return;
278 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000279 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000280 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000281 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000282 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000283 }
284 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000285 } else {
286 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000287 }
288
Ted Kremenek6217b802009-07-29 21:53:49 +0000289 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000291 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000292 PDiag(diag::err_bad_dynamic_cast_incomplete)
293 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000294 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000295 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000296 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000297 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000298 return;
299 }
300
301 assert((DestPointer || DestReference) &&
302 "Bad destination non-ptr/ref slipped through.");
303 assert((DestRecord || DestPointee->isVoidType()) &&
304 "Bad destination pointee slipped through.");
305 assert(SrcRecord && "Bad source pointee slipped through.");
306
307 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
308 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000309 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000310 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000311 return;
312 }
313
314 // C++ 5.2.7p3: If the type of v is the same as the required result type,
315 // [except for cv].
316 if (DestRecord == SrcRecord) {
317 return;
318 }
319
320 // C++ 5.2.7p5
321 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000322 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
323 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000324 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000325 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000326 // Diagnostic already emitted on error.
327 return;
328 }
329
330 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000331 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000332 assert(SrcDecl && "Definition missing");
333 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000334 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000335 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000336 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000337
338 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000339 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000340}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000341
342/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
343/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
344/// like this:
345/// const char *str = "literal";
346/// legacy_function(const_cast\<char*\>(str));
347void
348CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000349 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000350 if (!DestType->isLValueReferenceType())
351 Self.DefaultFunctionArrayConversion(SrcExpr);
352
353 unsigned msg = diag::err_bad_cxx_cast_generic;
354 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
355 && msg != 0)
356 Self.Diag(OpRange.getBegin(), msg) << CT_Const
357 << SrcExpr->getType() << DestType << OpRange;
358}
359
360/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
361/// valid.
362/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
363/// like this:
364/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
365void
366CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000367 const SourceRange &OpRange, const SourceRange &DestRange,
368 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000369 if (!DestType->isLValueReferenceType())
370 Self.DefaultFunctionArrayConversion(SrcExpr);
371
372 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000373 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
374 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000375 != TC_Success && msg != 0)
376 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
377 << SrcExpr->getType() << DestType << OpRange;
378}
379
380
381/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
382/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
383/// implicit conversions explicit and getting rid of data loss warnings.
384void
385CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000386 const SourceRange &OpRange, CastExpr::CastKind &Kind,
387 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000388 // This test is outside everything else because it's the only case where
389 // a non-lvalue-reference target type does not lead to decay.
390 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000391 if (DestType->isVoidType()) {
392 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000393 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000394 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000395
Douglas Gregorb653c522009-11-06 01:14:41 +0000396 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000397 Self.DefaultFunctionArrayConversion(SrcExpr);
398
399 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000400 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000401 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000402 != TC_Success && msg != 0)
403 Self.Diag(OpRange.getBegin(), msg) << CT_Static
404 << SrcExpr->getType() << DestType << OpRange;
405}
406
407/// TryStaticCast - Check if a static cast can be performed, and do so if
408/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
409/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000410static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000411 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000412 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000413 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000414 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000415 // The order the tests is not entirely arbitrary. There is one conversion
416 // that can be handled in two different ways. Given:
417 // struct A {};
418 // struct B : public A {
419 // B(); B(const A&);
420 // };
421 // const A &a = B();
422 // the cast static_cast<const B&>(a) could be seen as either a static
423 // reference downcast, or an explicit invocation of the user-defined
424 // conversion using B's conversion constructor.
425 // DR 427 specifies that the downcast is to be applied here.
426
427 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
428 // Done outside this function.
429
430 TryCastResult tcr;
431
432 // C++ 5.2.9p5, reference downcast.
433 // See the function for details.
434 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000435 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000436 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000437 if (tcr != TC_NotApplicable)
438 return tcr;
439
440 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
441 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
442 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000443 if (tcr != TC_NotApplicable) {
444 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000445 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000446 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000447
448 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
449 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000450 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000451 Kind, ConversionDecl);
452 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000453 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000454
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000455 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
456 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
457 // conversions, subject to further restrictions.
458 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
459 // of qualification conversions impossible.
460 // In the CStyle case, the earlier attempt to const_cast should have taken
461 // care of reverse qualification conversions.
462
463 QualType OrigSrcType = SrcExpr->getType();
464
465 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
466
467 // Reverse integral promotion/conversion. All such conversions are themselves
468 // again integral promotions or conversions and are thus already handled by
469 // p2 (TryDirectInitialization above).
470 // (Note: any data loss warnings should be suppressed.)
471 // The exception is the reverse of enum->integer, i.e. integer->enum (and
472 // enum->enum). See also C++ 5.2.9p7.
473 // The same goes for reverse floating point promotion/conversion and
474 // floating-integral conversions. Again, only floating->enum is relevant.
475 if (DestType->isEnumeralType()) {
476 if (SrcType->isComplexType() || SrcType->isVectorType()) {
477 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000478 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
479 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000480 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000481 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000482 }
483
484 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
485 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000486 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
487 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000488 if (tcr != TC_NotApplicable)
489 return tcr;
490
491 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
492 // conversion. C++ 5.2.9p9 has additional information.
493 // DR54's access restrictions apply here also.
494 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000495 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000496 if (tcr != TC_NotApplicable)
497 return tcr;
498
499 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
500 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
501 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000502 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000503 QualType SrcPointee = SrcPointer->getPointeeType();
504 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000506 QualType DestPointee = DestPointer->getPointeeType();
507 if (DestPointee->isIncompleteOrObjectType()) {
508 // This is definitely the intended conversion, but it might fail due
509 // to a const violation.
510 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
511 msg = diag::err_bad_cxx_cast_const_away;
512 return TC_Failed;
513 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000514 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000515 return TC_Success;
516 }
517 }
518 }
519 }
520
521 // We tried everything. Everything! Nothing works! :-(
522 return TC_NotApplicable;
523}
524
525/// Tests whether a conversion according to N2844 is valid.
526TryCastResult
527TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000528 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000529 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
530 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000531 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000532 if (!R)
533 return TC_NotApplicable;
534
535 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
536 return TC_NotApplicable;
537
538 // Because we try the reference downcast before this function, from now on
539 // this is the only cast possibility, so we issue an error if we fail now.
540 // FIXME: Should allow casting away constness if CStyle.
541 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000542 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
543 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000544 DerivedToBase) <
545 Sema::Ref_Compatible_With_Added_Qualification) {
546 msg = diag::err_bad_lvalue_to_rvalue_cast;
547 return TC_Failed;
548 }
549
550 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
551 // than nothing.
552 return TC_Success;
553}
554
555/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
556TryCastResult
557TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
558 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000559 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000560 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
561 // cast to type "reference to cv2 D", where D is a class derived from B,
562 // if a valid standard conversion from "pointer to D" to "pointer to B"
563 // exists, cv2 >= cv1, and B is not a virtual base class of D.
564 // In addition, DR54 clarifies that the base must be accessible in the
565 // current context. Although the wording of DR54 only applies to the pointer
566 // variant of this rule, the intent is clearly for it to apply to the this
567 // conversion as well.
568
Ted Kremenek6217b802009-07-29 21:53:49 +0000569 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000570 if (!DestReference) {
571 return TC_NotApplicable;
572 }
573 bool RValueRef = DestReference->isRValueReferenceType();
574 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
575 // We know the left side is an lvalue reference, so we can suggest a reason.
576 msg = diag::err_bad_cxx_cast_rvalue;
577 return TC_NotApplicable;
578 }
579
580 QualType DestPointee = DestReference->getPointeeType();
581
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000582 return TryStaticDowncast(Self,
583 Self.Context.getCanonicalType(SrcExpr->getType()),
584 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000585 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000586}
587
588/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
589TryCastResult
590TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000591 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000592 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000593 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
594 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
595 // is a class derived from B, if a valid standard conversion from "pointer
596 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
597 // class of D.
598 // In addition, DR54 clarifies that the base must be accessible in the
599 // current context.
600
Ted Kremenek6217b802009-07-29 21:53:49 +0000601 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000602 if (!DestPointer) {
603 return TC_NotApplicable;
604 }
605
Ted Kremenek6217b802009-07-29 21:53:49 +0000606 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000607 if (!SrcPointer) {
608 msg = diag::err_bad_static_cast_pointer_nonpointer;
609 return TC_NotApplicable;
610 }
611
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000612 return TryStaticDowncast(Self,
613 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
614 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
615 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000616}
617
618/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
619/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000620/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000621TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000622TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000623 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000624 QualType OrigDestType, unsigned &msg,
625 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000626 // We can only work with complete types. But don't complain if it doesn't work
627 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
628 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
629 return TC_NotApplicable;
630
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000631 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000632 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000633 return TC_NotApplicable;
634 }
635
Douglas Gregora8f32e02009-10-06 17:59:45 +0000636 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
637 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000638 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
639 return TC_NotApplicable;
640 }
641
642 // Target type does derive from source type. Now we're serious. If an error
643 // appears now, it's not ignored.
644 // This may not be entirely in line with the standard. Take for example:
645 // struct A {};
646 // struct B : virtual A {
647 // B(A&);
648 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000649 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000650 // void f()
651 // {
652 // (void)static_cast<const B&>(*((A*)0));
653 // }
654 // As far as the standard is concerned, p5 does not apply (A is virtual), so
655 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
656 // However, both GCC and Comeau reject this example, and accepting it would
657 // mean more complex code if we're to preserve the nice error message.
658 // FIXME: Being 100% compliant here would be nice to have.
659
660 // Must preserve cv, as always, unless we're in C-style mode.
661 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
662 msg = diag::err_bad_cxx_cast_const_away;
663 return TC_Failed;
664 }
665
666 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
667 // This code is analoguous to that in CheckDerivedToBaseConversion, except
668 // that it builds the paths in reverse order.
669 // To sum up: record all paths to the base and build a nice string from
670 // them. Use it to spice up the error message.
671 if (!Paths.isRecordingPaths()) {
672 Paths.clear();
673 Paths.setRecordingPaths(true);
674 Self.IsDerivedFrom(DestType, SrcType, Paths);
675 }
676 std::string PathDisplayStr;
677 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000678 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679 PI != PE; ++PI) {
680 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
681 // We haven't displayed a path to this particular base
682 // class subobject yet.
683 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000684 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
685 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000686 EI != EE; ++EI)
687 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000688 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000689 }
690 }
691
692 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000693 << QualType(SrcType).getUnqualifiedType()
694 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000695 << PathDisplayStr << OpRange;
696 msg = 0;
697 return TC_Failed;
698 }
699
700 if (Paths.getDetectedVirtual() != 0) {
701 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
702 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
703 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
704 msg = 0;
705 return TC_Failed;
706 }
707
708 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
709 diag::err_downcast_from_inaccessible_base, Paths,
710 OpRange.getBegin(), DeclarationName())) {
711 msg = 0;
712 return TC_Failed;
713 }
714
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000715 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000716 return TC_Success;
717}
718
719/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
720/// C++ 5.2.9p9 is valid:
721///
722/// An rvalue of type "pointer to member of D of type cv1 T" can be
723/// converted to an rvalue of type "pointer to member of B of type cv2 T",
724/// where B is a base class of D [...].
725///
726TryCastResult
727TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
728 bool CStyle, const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000729 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000730 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000731 if (!DestMemPtr)
732 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000733 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000734 if (!SrcMemPtr) {
735 msg = diag::err_bad_static_cast_member_pointer_nonmp;
736 return TC_NotApplicable;
737 }
738
739 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000740 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
741 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000742 return TC_NotApplicable;
743
744 // B base of D
745 QualType SrcClass(SrcMemPtr->getClass(), 0);
746 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000748 /*DetectVirtual=*/true);
749 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
750 return TC_NotApplicable;
751 }
752
753 // B is a base of D. But is it an allowed base? If not, it's a hard error.
754 if (Paths.isAmbiguous(DestClass)) {
755 Paths.clear();
756 Paths.setRecordingPaths(true);
757 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
758 assert(StillOkay);
759 StillOkay = StillOkay;
760 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
761 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
762 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
763 msg = 0;
764 return TC_Failed;
765 }
766
767 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
768 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
769 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
770 msg = 0;
771 return TC_Failed;
772 }
773
774 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
775 diag::err_downcast_from_inaccessible_base, Paths,
776 OpRange.getBegin(), DeclarationName())) {
777 msg = 0;
778 return TC_Failed;
779 }
780
Anders Carlsson1a31a182009-10-30 00:46:35 +0000781 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000782 return TC_Success;
783}
784
785/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
786/// is valid:
787///
788/// An expression e can be explicitly converted to a type T using a
789/// @c static_cast if the declaration "T t(e);" is well-formed [...].
790TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000791TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000792 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000793 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000794 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000795 if (DestType->isRecordType()) {
796 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
797 diag::err_bad_dynamic_cast_incomplete)) {
798 msg = 0;
799 return TC_Failed;
800 }
801 }
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000803 if (DestType->isReferenceType()) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000804 // All reference bindings insert implicit casts above that do the actual
805 // casting.
806 Kind = CastExpr::CK_NoOp;
807
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000808 // At this point of CheckStaticCast, if the destination is a reference,
809 // this has to work. There is no other way that works.
810 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000811 // the reinterpret_cast way. So in C-style mode, we first try the call
812 // with an ICS to suppress errors.
813 if (CStyle) {
814 ImplicitConversionSequence ICS;
815 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
816 /*SuppressUserConversions=*/false,
817 /*AllowExplicit=*/false, /*ForceRValue=*/false,
818 &ICS))
819 return TC_NotApplicable;
820 }
821 // Now we're committed either way.
822 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
823 /*SuppressUserConversions=*/false,
824 /*AllowExplicit=*/false,
825 /*ForceRValue=*/false, 0,
826 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000827 return TC_Success;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000828
829 // We already got an error message.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000830 msg = 0;
831 return TC_Failed;
832 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000833
Douglas Gregor19aeac62009-11-14 03:27:21 +0000834 if (DestType->isRecordType()) {
835 if (CXXConstructorDecl *Constructor
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000836 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregor19aeac62009-11-14 03:27:21 +0000837 OpRange.getBegin(),
838 Sema::IK_Direct)) {
839 ConversionDecl = Constructor;
840 Kind = CastExpr::CK_ConstructorConversion;
841 return TC_Success;
842 }
843
844 return TC_NotApplicable;
845 }
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000846
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000847 // FIXME: To get a proper error from invalid conversions here, we need to
848 // reimplement more of this.
849 // FIXME: This does not actually perform the conversion, and thus does not
850 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000851 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000852 Self.TryImplicitConversion(SrcExpr, DestType,
853 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000854 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000855 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000856 /*InOverloadResolution=*/false,
857 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Anders Carlsson3c31a392009-09-26 00:12:34 +0000859 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
860 return TC_NotApplicable;
861
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000862 // The conversion is possible, so commit to it.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000863 Kind = CastExpr::CK_NoOp;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000864 msg = 0;
865 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, "casting",
866 /*IgnoreBaseAccess*/CStyle) ?
867 TC_Failed : TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000868}
869
870/// TryConstCast - See if a const_cast from source to destination is allowed,
871/// and perform it if it is.
872static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
873 bool CStyle, unsigned &msg) {
874 DestType = Self.Context.getCanonicalType(DestType);
875 QualType SrcType = SrcExpr->getType();
876 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000877 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000878 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
879 // Cannot const_cast non-lvalue to lvalue reference type. But if this
880 // is C-style, static_cast might find a way, so we simply suggest a
881 // message and tell the parent to keep searching.
882 msg = diag::err_bad_cxx_cast_rvalue;
883 return TC_NotApplicable;
884 }
885
886 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
887 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
888 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
889 SrcType = Self.Context.getPointerType(SrcType);
890 }
891
892 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
893 // the rules for const_cast are the same as those used for pointers.
894
895 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
896 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
897 // was a reference type, we converted it to a pointer above.
898 // The status of rvalue references isn't entirely clear, but it looks like
899 // conversion to them is simply invalid.
900 // C++ 5.2.11p3: For two pointer types [...]
901 if (!CStyle)
902 msg = diag::err_bad_const_cast_dest;
903 return TC_NotApplicable;
904 }
905 if (DestType->isFunctionPointerType() ||
906 DestType->isMemberFunctionPointerType()) {
907 // Cannot cast direct function pointers.
908 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
909 // T is the ultimate pointee of source and target type.
910 if (!CStyle)
911 msg = diag::err_bad_const_cast_dest;
912 return TC_NotApplicable;
913 }
914 SrcType = Self.Context.getCanonicalType(SrcType);
915
916 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
917 // completely equal.
918 // FIXME: const_cast should probably not be able to convert between pointers
919 // to different address spaces.
920 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
921 // in multi-level pointers may change, but the level count must be the same,
922 // as must be the final pointee type.
923 while (SrcType != DestType &&
924 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
925 SrcType = SrcType.getUnqualifiedType();
926 DestType = DestType.getUnqualifiedType();
927 }
928
929 // Since we're dealing in canonical types, the remainder must be the same.
930 if (SrcType != DestType)
931 return TC_NotApplicable;
932
933 return TC_Success;
934}
935
936static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
937 QualType DestType, bool CStyle,
938 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000939 unsigned &msg,
940 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000941 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
942
943 DestType = Self.Context.getCanonicalType(DestType);
944 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000945 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000946 bool LValue = DestTypeTmp->isLValueReferenceType();
947 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
948 // Cannot cast non-lvalue to reference type. See the similar comment in
949 // const_cast.
950 msg = diag::err_bad_cxx_cast_rvalue;
951 return TC_NotApplicable;
952 }
953
954 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
955 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
956 // built-in & and * operators.
957 // This code does this transformation for the checked types.
958 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
959 SrcType = Self.Context.getPointerType(SrcType);
960 }
961
962 // Canonicalize source for comparison.
963 SrcType = Self.Context.getCanonicalType(SrcType);
964
Ted Kremenek6217b802009-07-29 21:53:49 +0000965 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
966 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000967 if (DestMemPtr && SrcMemPtr) {
968 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
969 // can be explicitly converted to an rvalue of type "pointer to member
970 // of Y of type T2" if T1 and T2 are both function types or both object
971 // types.
972 if (DestMemPtr->getPointeeType()->isFunctionType() !=
973 SrcMemPtr->getPointeeType()->isFunctionType())
974 return TC_NotApplicable;
975
976 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
977 // constness.
978 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
979 // we accept it.
980 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
981 msg = diag::err_bad_cxx_cast_const_away;
982 return TC_Failed;
983 }
984
985 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000986 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000987 return TC_Success;
988 }
989
990 // See below for the enumeral issue.
991 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
992 !DestType->isEnumeralType()) {
993 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
994 // type large enough to hold it. A value of std::nullptr_t can be
995 // converted to an integral type; the conversion has the same meaning
996 // and validity as a conversion of (void*)0 to the integral type.
997 if (Self.Context.getTypeSize(SrcType) >
998 Self.Context.getTypeSize(DestType)) {
999 msg = diag::err_bad_reinterpret_cast_small_int;
1000 return TC_Failed;
1001 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001002 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001003 return TC_Success;
1004 }
1005
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001006 bool destIsVector = DestType->isVectorType();
1007 bool srcIsVector = SrcType->isVectorType();
1008 if (srcIsVector || destIsVector) {
1009 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1010 bool destIsScalar =
1011 DestType->isIntegralType() && !DestType->isEnumeralType();
1012
1013 // Check if this is a cast between a vector and something else.
1014 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1015 !(srcIsVector && destIsVector))
1016 return TC_NotApplicable;
1017
1018 // If both types have the same size, we can successfully cast.
1019 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
1020 return TC_Success;
1021
1022 if (destIsScalar)
1023 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1024 else if (srcIsScalar)
1025 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1026 else
1027 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1028
1029 return TC_Failed;
1030 }
1031
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001032 bool destIsPtr = DestType->isPointerType();
1033 bool srcIsPtr = SrcType->isPointerType();
1034 if (!destIsPtr && !srcIsPtr) {
1035 // Except for std::nullptr_t->integer and lvalue->reference, which are
1036 // handled above, at least one of the two arguments must be a pointer.
1037 return TC_NotApplicable;
1038 }
1039
1040 if (SrcType == DestType) {
1041 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1042 // restrictions, a cast to the same type is allowed. The intent is not
1043 // entirely clear here, since all other paragraphs explicitly forbid casts
1044 // to the same type. However, the behavior of compilers is pretty consistent
1045 // on this point: allow same-type conversion if the involved types are
1046 // pointers, disallow otherwise.
1047 return TC_Success;
1048 }
1049
1050 // Note: Clang treats enumeration types as integral types. If this is ever
1051 // changed for C++, the additional check here will be redundant.
1052 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1053 assert(srcIsPtr && "One type must be a pointer");
1054 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1055 // type large enough to hold it.
1056 if (Self.Context.getTypeSize(SrcType) >
1057 Self.Context.getTypeSize(DestType)) {
1058 msg = diag::err_bad_reinterpret_cast_small_int;
1059 return TC_Failed;
1060 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001061 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001062 return TC_Success;
1063 }
1064
1065 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1066 assert(destIsPtr && "One type must be a pointer");
1067 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1068 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001069 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001070 return TC_Success;
1071 }
1072
1073 if (!destIsPtr || !srcIsPtr) {
1074 // With the valid non-pointer conversions out of the way, we can be even
1075 // more stringent.
1076 return TC_NotApplicable;
1077 }
1078
1079 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1080 // The C-style cast operator can.
1081 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1082 msg = diag::err_bad_cxx_cast_const_away;
1083 return TC_Failed;
1084 }
1085
1086 // Not casting away constness, so the only remaining check is for compatible
1087 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001088 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001089
1090 if (SrcType->isFunctionPointerType()) {
1091 if (DestType->isFunctionPointerType()) {
1092 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1093 // a pointer to a function of a different type.
1094 return TC_Success;
1095 }
1096
1097 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1098 // an object type or vice versa is conditionally-supported.
1099 // Compilers support it in C++03 too, though, because it's necessary for
1100 // casting the return value of dlsym() and GetProcAddress().
1101 // FIXME: Conditionally-supported behavior should be configurable in the
1102 // TargetInfo or similar.
1103 if (!Self.getLangOptions().CPlusPlus0x)
1104 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1105 return TC_Success;
1106 }
1107
1108 if (DestType->isFunctionPointerType()) {
1109 // See above.
1110 if (!Self.getLangOptions().CPlusPlus0x)
1111 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1112 return TC_Success;
1113 }
1114
1115 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1116 // a pointer to an object of different type.
1117 // Void pointers are not specified, but supported by every compiler out there.
1118 // So we finish by allowing everything that remains - it's got to be two
1119 // object pointers.
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001120 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001121 return TC_Success;
1122}
1123
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001124bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001125 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001126 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 // This test is outside everything else because it's the only case where
1128 // a non-lvalue-reference target type does not lead to decay.
1129 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001130 if (CastTy->isVoidType()) {
1131 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001132 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001133 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001134
1135 // If the type is dependent, we won't do any other semantic analysis now.
1136 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1137 return false;
1138
Douglas Gregorb653c522009-11-06 01:14:41 +00001139 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001140 DefaultFunctionArrayConversion(CastExpr);
1141
1142 // C++ [expr.cast]p5: The conversions performed by
1143 // - a const_cast,
1144 // - a static_cast,
1145 // - a static_cast followed by a const_cast,
1146 // - a reinterpret_cast, or
1147 // - a reinterpret_cast followed by a const_cast,
1148 // can be performed using the cast notation of explicit type conversion.
1149 // [...] If a conversion can be interpreted in more than one of the ways
1150 // listed above, the interpretation that appears first in the list is used,
1151 // even if a cast resulting from that interpretation is ill-formed.
1152 // In plain language, this means trying a const_cast ...
1153 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001154 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1155 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001156 if (tcr == TC_Success)
1157 Kind = CastExpr::CK_NoOp;
1158
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001159 if (tcr == TC_NotApplicable) {
1160 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001161 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1162 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001163 if (tcr == TC_NotApplicable) {
1164 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001165 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1166 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001167 }
1168 }
1169
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001170 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001171 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001172 << CastExpr->getType() << CastTy << R;
1173
1174 return tcr != TC_Success;
1175}