blob: f9138902a67865455415dfe414a890bcad5b1cb4 [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 Redl76d69bb2009-11-18 18:10:53 +0000178/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
179/// this removes one level of indirection from both types, provided that they're
180/// the same kind of pointer (plain or to-member). Unlike the Sema function,
181/// this one doesn't care if the two pointers-to-member don't point into the
182/// same class. This is because CastsAwayConstness doesn't care.
183bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
184 const PointerType *T1PtrType = T1->getAs<PointerType>(),
185 *T2PtrType = T2->getAs<PointerType>();
186 if (T1PtrType && T2PtrType) {
187 T1 = T1PtrType->getPointeeType();
188 T2 = T2PtrType->getPointeeType();
189 return true;
190 }
191
192 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
193 *T2MPType = T2->getAs<MemberPointerType>();
194 if (T1MPType && T2MPType) {
195 T1 = T1MPType->getPointeeType();
196 T2 = T2MPType->getPointeeType();
197 return true;
198 }
199 return false;
200}
201
Sebastian Redldb647282009-01-27 23:18:31 +0000202/// CastsAwayConstness - Check if the pointer conversion from SrcType to
203/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
204/// the cast checkers. Both arguments must denote pointer (possibly to member)
205/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000206static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000207CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000208 // Casting away constness is defined in C++ 5.2.11p8 with reference to
209 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
210 // the rules are non-trivial. So first we construct Tcv *...cv* as described
211 // in C++ 5.2.11p8.
212 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
213 "Source type is not pointer or pointer to member.");
214 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
215 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000217 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
218 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000219 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000220
221 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000222 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000223 cv1.push_back(UnwrappedSrcType.getQualifiers());
224 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225 }
226 assert(cv1.size() > 0 && "Must have at least one pointer level.");
227
228 // Construct void pointers with those qualifiers (in reverse order of
229 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000230 QualType SrcConstruct = Self.Context.VoidTy;
231 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000232 ASTContext &Context = Self.Context;
233 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
234 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000235 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000236 SrcConstruct
237 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
238 DestConstruct
239 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000240 }
241
242 // Test if they're compatible.
243 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000244 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000245}
246
Sebastian Redl26d85b12008-11-05 21:50:06 +0000247/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
248/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
249/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000250static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000251CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
252 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000254 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000255 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000256
257 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
258 // or "pointer to cv void".
259
260 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000261 const PointerType *DestPointer = DestType->getAs<PointerType>();
262 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263 if (DestPointer) {
264 DestPointee = DestPointer->getPointeeType();
265 } else if (DestReference) {
266 DestPointee = DestReference->getPointeeType();
267 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000268 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000269 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000270 return;
271 }
272
Ted Kremenek6217b802009-07-29 21:53:49 +0000273 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000274 if (DestPointee->isVoidType()) {
275 assert(DestPointer && "Reference to void is not possible");
276 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000277 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000278 PDiag(diag::err_bad_dynamic_cast_incomplete)
279 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000281 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000282 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000283 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000284 return;
285 }
286
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000287 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
288 // complete class type, [...]. If T is an lvalue reference type, v shall be
289 // an lvalue of a complete class type, [...]. If T is an rvalue reference
290 // type, v shall be an expression having a complete effective class type,
291 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000292
Sebastian Redl37d6de32008-11-08 13:00:26 +0000293 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000294 QualType SrcPointee;
295 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000296 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000297 SrcPointee = SrcPointer->getPointeeType();
298 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000299 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000300 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000301 return;
302 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000303 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000304 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000305 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000306 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000307 }
308 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000309 } else {
310 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000311 }
312
Ted Kremenek6217b802009-07-29 21:53:49 +0000313 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000314 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000315 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000316 PDiag(diag::err_bad_dynamic_cast_incomplete)
317 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000318 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000319 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000320 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000321 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000322 return;
323 }
324
325 assert((DestPointer || DestReference) &&
326 "Bad destination non-ptr/ref slipped through.");
327 assert((DestRecord || DestPointee->isVoidType()) &&
328 "Bad destination pointee slipped through.");
329 assert(SrcRecord && "Bad source pointee slipped through.");
330
331 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
332 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000333 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000334 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000335 return;
336 }
337
338 // C++ 5.2.7p3: If the type of v is the same as the required result type,
339 // [except for cv].
340 if (DestRecord == SrcRecord) {
341 return;
342 }
343
344 // C++ 5.2.7p5
345 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000346 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
347 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000348 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000349 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000350 // Diagnostic already emitted on error.
351 return;
352 }
353
354 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000355 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000356 assert(SrcDecl && "Definition missing");
357 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000358 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000359 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000360 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000361
362 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000363 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000364}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000365
366/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
367/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
368/// like this:
369/// const char *str = "literal";
370/// legacy_function(const_cast\<char*\>(str));
371void
372CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000373 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000374 if (!DestType->isLValueReferenceType())
375 Self.DefaultFunctionArrayConversion(SrcExpr);
376
377 unsigned msg = diag::err_bad_cxx_cast_generic;
378 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
379 && msg != 0)
380 Self.Diag(OpRange.getBegin(), msg) << CT_Const
381 << SrcExpr->getType() << DestType << OpRange;
382}
383
384/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
385/// valid.
386/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
387/// like this:
388/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
389void
390CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000391 const SourceRange &OpRange, const SourceRange &DestRange,
392 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000393 if (!DestType->isLValueReferenceType())
394 Self.DefaultFunctionArrayConversion(SrcExpr);
395
396 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000397 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
398 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000399 != TC_Success && msg != 0)
400 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
401 << SrcExpr->getType() << DestType << OpRange;
402}
403
404
405/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
406/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
407/// implicit conversions explicit and getting rid of data loss warnings.
408void
409CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000410 const SourceRange &OpRange, CastExpr::CastKind &Kind,
411 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000412 // This test is outside everything else because it's the only case where
413 // a non-lvalue-reference target type does not lead to decay.
414 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000415 if (DestType->isVoidType()) {
416 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000417 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000418 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000419
Douglas Gregorb653c522009-11-06 01:14:41 +0000420 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000421 Self.DefaultFunctionArrayConversion(SrcExpr);
422
423 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000424 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000425 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000426 != TC_Success && msg != 0)
427 Self.Diag(OpRange.getBegin(), msg) << CT_Static
428 << SrcExpr->getType() << DestType << OpRange;
429}
430
431/// TryStaticCast - Check if a static cast can be performed, and do so if
432/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
433/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000434static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000435 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000436 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000437 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000438 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000439 // The order the tests is not entirely arbitrary. There is one conversion
440 // that can be handled in two different ways. Given:
441 // struct A {};
442 // struct B : public A {
443 // B(); B(const A&);
444 // };
445 // const A &a = B();
446 // the cast static_cast<const B&>(a) could be seen as either a static
447 // reference downcast, or an explicit invocation of the user-defined
448 // conversion using B's conversion constructor.
449 // DR 427 specifies that the downcast is to be applied here.
450
451 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
452 // Done outside this function.
453
454 TryCastResult tcr;
455
456 // C++ 5.2.9p5, reference downcast.
457 // See the function for details.
458 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000459 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000460 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000461 if (tcr != TC_NotApplicable)
462 return tcr;
463
464 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
465 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
466 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000467 if (tcr != TC_NotApplicable) {
468 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000469 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000470 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000471
472 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
473 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000474 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000475 Kind, ConversionDecl);
476 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000477 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000478
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000479 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
480 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
481 // conversions, subject to further restrictions.
482 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
483 // of qualification conversions impossible.
484 // In the CStyle case, the earlier attempt to const_cast should have taken
485 // care of reverse qualification conversions.
486
487 QualType OrigSrcType = SrcExpr->getType();
488
489 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
490
491 // Reverse integral promotion/conversion. All such conversions are themselves
492 // again integral promotions or conversions and are thus already handled by
493 // p2 (TryDirectInitialization above).
494 // (Note: any data loss warnings should be suppressed.)
495 // The exception is the reverse of enum->integer, i.e. integer->enum (and
496 // enum->enum). See also C++ 5.2.9p7.
497 // The same goes for reverse floating point promotion/conversion and
498 // floating-integral conversions. Again, only floating->enum is relevant.
499 if (DestType->isEnumeralType()) {
500 if (SrcType->isComplexType() || SrcType->isVectorType()) {
501 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000502 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
503 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000504 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000505 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000506 }
507
508 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
509 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000510 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
511 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000512 if (tcr != TC_NotApplicable)
513 return tcr;
514
515 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
516 // conversion. C++ 5.2.9p9 has additional information.
517 // DR54's access restrictions apply here also.
518 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000519 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000520 if (tcr != TC_NotApplicable)
521 return tcr;
522
523 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
524 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
525 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000526 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000527 QualType SrcPointee = SrcPointer->getPointeeType();
528 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000529 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000530 QualType DestPointee = DestPointer->getPointeeType();
531 if (DestPointee->isIncompleteOrObjectType()) {
532 // This is definitely the intended conversion, but it might fail due
533 // to a const violation.
534 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
535 msg = diag::err_bad_cxx_cast_const_away;
536 return TC_Failed;
537 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000538 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000539 return TC_Success;
540 }
541 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000542 else if (CStyle && DestType->isObjCObjectPointerType()) {
543 // allow c-style cast of objective-c pointers as they are pervasive.
544 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
545 return TC_Success;
546 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000547 }
548 }
549
550 // We tried everything. Everything! Nothing works! :-(
551 return TC_NotApplicable;
552}
553
554/// Tests whether a conversion according to N2844 is valid.
555TryCastResult
556TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000557 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000558 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
559 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000560 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000561 if (!R)
562 return TC_NotApplicable;
563
564 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
565 return TC_NotApplicable;
566
567 // Because we try the reference downcast before this function, from now on
568 // this is the only cast possibility, so we issue an error if we fail now.
569 // FIXME: Should allow casting away constness if CStyle.
570 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000571 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
572 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000573 DerivedToBase) <
574 Sema::Ref_Compatible_With_Added_Qualification) {
575 msg = diag::err_bad_lvalue_to_rvalue_cast;
576 return TC_Failed;
577 }
578
579 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
580 // than nothing.
581 return TC_Success;
582}
583
584/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
585TryCastResult
586TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
587 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000588 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000589 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
590 // cast to type "reference to cv2 D", where D is a class derived from B,
591 // if a valid standard conversion from "pointer to D" to "pointer to B"
592 // exists, cv2 >= cv1, and B is not a virtual base class of D.
593 // In addition, DR54 clarifies that the base must be accessible in the
594 // current context. Although the wording of DR54 only applies to the pointer
595 // variant of this rule, the intent is clearly for it to apply to the this
596 // conversion as well.
597
Ted Kremenek6217b802009-07-29 21:53:49 +0000598 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000599 if (!DestReference) {
600 return TC_NotApplicable;
601 }
602 bool RValueRef = DestReference->isRValueReferenceType();
603 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
604 // We know the left side is an lvalue reference, so we can suggest a reason.
605 msg = diag::err_bad_cxx_cast_rvalue;
606 return TC_NotApplicable;
607 }
608
609 QualType DestPointee = DestReference->getPointeeType();
610
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000611 return TryStaticDowncast(Self,
612 Self.Context.getCanonicalType(SrcExpr->getType()),
613 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000614 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000615}
616
617/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
618TryCastResult
619TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000620 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000621 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000622 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
623 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
624 // is a class derived from B, if a valid standard conversion from "pointer
625 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
626 // class of D.
627 // In addition, DR54 clarifies that the base must be accessible in the
628 // current context.
629
Ted Kremenek6217b802009-07-29 21:53:49 +0000630 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000631 if (!DestPointer) {
632 return TC_NotApplicable;
633 }
634
Ted Kremenek6217b802009-07-29 21:53:49 +0000635 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000636 if (!SrcPointer) {
637 msg = diag::err_bad_static_cast_pointer_nonpointer;
638 return TC_NotApplicable;
639 }
640
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000641 return TryStaticDowncast(Self,
642 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
643 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
644 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000645}
646
647/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
648/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000649/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000650TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000651TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000652 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000653 QualType OrigDestType, unsigned &msg,
654 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000655 // We can only work with complete types. But don't complain if it doesn't work
656 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
657 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
658 return TC_NotApplicable;
659
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000660 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000661 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000662 return TC_NotApplicable;
663 }
664
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
666 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000667 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
668 return TC_NotApplicable;
669 }
670
671 // Target type does derive from source type. Now we're serious. If an error
672 // appears now, it's not ignored.
673 // This may not be entirely in line with the standard. Take for example:
674 // struct A {};
675 // struct B : virtual A {
676 // B(A&);
677 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000678 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679 // void f()
680 // {
681 // (void)static_cast<const B&>(*((A*)0));
682 // }
683 // As far as the standard is concerned, p5 does not apply (A is virtual), so
684 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
685 // However, both GCC and Comeau reject this example, and accepting it would
686 // mean more complex code if we're to preserve the nice error message.
687 // FIXME: Being 100% compliant here would be nice to have.
688
689 // Must preserve cv, as always, unless we're in C-style mode.
690 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
691 msg = diag::err_bad_cxx_cast_const_away;
692 return TC_Failed;
693 }
694
695 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
696 // This code is analoguous to that in CheckDerivedToBaseConversion, except
697 // that it builds the paths in reverse order.
698 // To sum up: record all paths to the base and build a nice string from
699 // them. Use it to spice up the error message.
700 if (!Paths.isRecordingPaths()) {
701 Paths.clear();
702 Paths.setRecordingPaths(true);
703 Self.IsDerivedFrom(DestType, SrcType, Paths);
704 }
705 std::string PathDisplayStr;
706 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000707 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000708 PI != PE; ++PI) {
709 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
710 // We haven't displayed a path to this particular base
711 // class subobject yet.
712 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000713 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
714 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000715 EI != EE; ++EI)
716 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000717 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000718 }
719 }
720
721 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000722 << QualType(SrcType).getUnqualifiedType()
723 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000724 << PathDisplayStr << OpRange;
725 msg = 0;
726 return TC_Failed;
727 }
728
729 if (Paths.getDetectedVirtual() != 0) {
730 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
731 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
732 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
733 msg = 0;
734 return TC_Failed;
735 }
736
737 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
738 diag::err_downcast_from_inaccessible_base, Paths,
739 OpRange.getBegin(), DeclarationName())) {
740 msg = 0;
741 return TC_Failed;
742 }
743
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000744 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000745 return TC_Success;
746}
747
748/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
749/// C++ 5.2.9p9 is valid:
750///
751/// An rvalue of type "pointer to member of D of type cv1 T" can be
752/// converted to an rvalue of type "pointer to member of B of type cv2 T",
753/// where B is a base class of D [...].
754///
755TryCastResult
756TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
757 bool CStyle, const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000758 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000759 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000760 if (!DestMemPtr)
761 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000762 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000763 if (!SrcMemPtr) {
764 msg = diag::err_bad_static_cast_member_pointer_nonmp;
765 return TC_NotApplicable;
766 }
767
768 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000769 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
770 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000771 return TC_NotApplicable;
772
773 // B base of D
774 QualType SrcClass(SrcMemPtr->getClass(), 0);
775 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000776 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000777 /*DetectVirtual=*/true);
778 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
779 return TC_NotApplicable;
780 }
781
782 // B is a base of D. But is it an allowed base? If not, it's a hard error.
783 if (Paths.isAmbiguous(DestClass)) {
784 Paths.clear();
785 Paths.setRecordingPaths(true);
786 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
787 assert(StillOkay);
788 StillOkay = StillOkay;
789 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
790 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
791 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
792 msg = 0;
793 return TC_Failed;
794 }
795
796 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
797 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
798 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
799 msg = 0;
800 return TC_Failed;
801 }
802
803 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
804 diag::err_downcast_from_inaccessible_base, Paths,
805 OpRange.getBegin(), DeclarationName())) {
806 msg = 0;
807 return TC_Failed;
808 }
809
Anders Carlsson1a31a182009-10-30 00:46:35 +0000810 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000811 return TC_Success;
812}
813
814/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
815/// is valid:
816///
817/// An expression e can be explicitly converted to a type T using a
818/// @c static_cast if the declaration "T t(e);" is well-formed [...].
819TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000820TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000821 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000822 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000823 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000824 if (DestType->isRecordType()) {
825 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
826 diag::err_bad_dynamic_cast_incomplete)) {
827 msg = 0;
828 return TC_Failed;
829 }
830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000832 if (DestType->isReferenceType()) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000833 // All reference bindings insert implicit casts above that do the actual
834 // casting.
835 Kind = CastExpr::CK_NoOp;
836
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000837 // At this point of CheckStaticCast, if the destination is a reference,
838 // this has to work. There is no other way that works.
839 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000840 // the reinterpret_cast way. So in C-style mode, we first try the call
841 // with an ICS to suppress errors.
842 if (CStyle) {
843 ImplicitConversionSequence ICS;
844 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
845 /*SuppressUserConversions=*/false,
846 /*AllowExplicit=*/false, /*ForceRValue=*/false,
847 &ICS))
848 return TC_NotApplicable;
849 }
850 // Now we're committed either way.
851 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
852 /*SuppressUserConversions=*/false,
853 /*AllowExplicit=*/false,
854 /*ForceRValue=*/false, 0,
855 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000856 return TC_Success;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000857
858 // We already got an error message.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000859 msg = 0;
860 return TC_Failed;
861 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000862
Douglas Gregor19aeac62009-11-14 03:27:21 +0000863 if (DestType->isRecordType()) {
864 if (CXXConstructorDecl *Constructor
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000865 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregor19aeac62009-11-14 03:27:21 +0000866 OpRange.getBegin(),
867 Sema::IK_Direct)) {
868 ConversionDecl = Constructor;
869 Kind = CastExpr::CK_ConstructorConversion;
870 return TC_Success;
871 }
872
873 return TC_NotApplicable;
874 }
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000875
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000876 // FIXME: To get a proper error from invalid conversions here, we need to
877 // reimplement more of this.
878 // FIXME: This does not actually perform the conversion, and thus does not
879 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000880 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000881 Self.TryImplicitConversion(SrcExpr, DestType,
882 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000883 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000884 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000885 /*InOverloadResolution=*/false,
886 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Anders Carlsson3c31a392009-09-26 00:12:34 +0000888 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
889 return TC_NotApplicable;
890
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000891 // The conversion is possible, so commit to it.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000892 Kind = CastExpr::CK_NoOp;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000893 msg = 0;
894 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, "casting",
895 /*IgnoreBaseAccess*/CStyle) ?
896 TC_Failed : TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000897}
898
899/// TryConstCast - See if a const_cast from source to destination is allowed,
900/// and perform it if it is.
901static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
902 bool CStyle, unsigned &msg) {
903 DestType = Self.Context.getCanonicalType(DestType);
904 QualType SrcType = SrcExpr->getType();
905 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000906 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000907 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
908 // Cannot const_cast non-lvalue to lvalue reference type. But if this
909 // is C-style, static_cast might find a way, so we simply suggest a
910 // message and tell the parent to keep searching.
911 msg = diag::err_bad_cxx_cast_rvalue;
912 return TC_NotApplicable;
913 }
914
915 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
916 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
917 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
918 SrcType = Self.Context.getPointerType(SrcType);
919 }
920
921 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
922 // the rules for const_cast are the same as those used for pointers.
923
924 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
925 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
926 // was a reference type, we converted it to a pointer above.
927 // The status of rvalue references isn't entirely clear, but it looks like
928 // conversion to them is simply invalid.
929 // C++ 5.2.11p3: For two pointer types [...]
930 if (!CStyle)
931 msg = diag::err_bad_const_cast_dest;
932 return TC_NotApplicable;
933 }
934 if (DestType->isFunctionPointerType() ||
935 DestType->isMemberFunctionPointerType()) {
936 // Cannot cast direct function pointers.
937 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
938 // T is the ultimate pointee of source and target type.
939 if (!CStyle)
940 msg = diag::err_bad_const_cast_dest;
941 return TC_NotApplicable;
942 }
943 SrcType = Self.Context.getCanonicalType(SrcType);
944
945 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
946 // completely equal.
947 // FIXME: const_cast should probably not be able to convert between pointers
948 // to different address spaces.
949 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
950 // in multi-level pointers may change, but the level count must be the same,
951 // as must be the final pointee type.
952 while (SrcType != DestType &&
953 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
954 SrcType = SrcType.getUnqualifiedType();
955 DestType = DestType.getUnqualifiedType();
956 }
957
958 // Since we're dealing in canonical types, the remainder must be the same.
959 if (SrcType != DestType)
960 return TC_NotApplicable;
961
962 return TC_Success;
963}
964
965static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
966 QualType DestType, bool CStyle,
967 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000968 unsigned &msg,
969 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000970 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
971
972 DestType = Self.Context.getCanonicalType(DestType);
973 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000974 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000975 bool LValue = DestTypeTmp->isLValueReferenceType();
976 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
977 // Cannot cast non-lvalue to reference type. See the similar comment in
978 // const_cast.
979 msg = diag::err_bad_cxx_cast_rvalue;
980 return TC_NotApplicable;
981 }
982
983 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
984 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
985 // built-in & and * operators.
986 // This code does this transformation for the checked types.
987 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
988 SrcType = Self.Context.getPointerType(SrcType);
989 }
990
991 // Canonicalize source for comparison.
992 SrcType = Self.Context.getCanonicalType(SrcType);
993
Ted Kremenek6217b802009-07-29 21:53:49 +0000994 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
995 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000996 if (DestMemPtr && SrcMemPtr) {
997 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
998 // can be explicitly converted to an rvalue of type "pointer to member
999 // of Y of type T2" if T1 and T2 are both function types or both object
1000 // types.
1001 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1002 SrcMemPtr->getPointeeType()->isFunctionType())
1003 return TC_NotApplicable;
1004
1005 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1006 // constness.
1007 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1008 // we accept it.
1009 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1010 msg = diag::err_bad_cxx_cast_const_away;
1011 return TC_Failed;
1012 }
1013
1014 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001015 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001016 return TC_Success;
1017 }
1018
1019 // See below for the enumeral issue.
1020 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1021 !DestType->isEnumeralType()) {
1022 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1023 // type large enough to hold it. A value of std::nullptr_t can be
1024 // converted to an integral type; the conversion has the same meaning
1025 // and validity as a conversion of (void*)0 to the integral type.
1026 if (Self.Context.getTypeSize(SrcType) >
1027 Self.Context.getTypeSize(DestType)) {
1028 msg = diag::err_bad_reinterpret_cast_small_int;
1029 return TC_Failed;
1030 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001031 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001032 return TC_Success;
1033 }
1034
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001035 bool destIsVector = DestType->isVectorType();
1036 bool srcIsVector = SrcType->isVectorType();
1037 if (srcIsVector || destIsVector) {
1038 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1039 bool destIsScalar =
1040 DestType->isIntegralType() && !DestType->isEnumeralType();
1041
1042 // Check if this is a cast between a vector and something else.
1043 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1044 !(srcIsVector && destIsVector))
1045 return TC_NotApplicable;
1046
1047 // If both types have the same size, we can successfully cast.
1048 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
1049 return TC_Success;
1050
1051 if (destIsScalar)
1052 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1053 else if (srcIsScalar)
1054 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1055 else
1056 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1057
1058 return TC_Failed;
1059 }
1060
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001061 bool destIsPtr =
1062 CStyle? DestType->isAnyPointerType() : DestType->isPointerType();
1063 bool srcIsPtr =
1064 CStyle ? SrcType->isAnyPointerType() : SrcType->isPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001065 if (!destIsPtr && !srcIsPtr) {
1066 // Except for std::nullptr_t->integer and lvalue->reference, which are
1067 // handled above, at least one of the two arguments must be a pointer.
1068 return TC_NotApplicable;
1069 }
1070
1071 if (SrcType == DestType) {
1072 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1073 // restrictions, a cast to the same type is allowed. The intent is not
1074 // entirely clear here, since all other paragraphs explicitly forbid casts
1075 // to the same type. However, the behavior of compilers is pretty consistent
1076 // on this point: allow same-type conversion if the involved types are
1077 // pointers, disallow otherwise.
1078 return TC_Success;
1079 }
1080
1081 // Note: Clang treats enumeration types as integral types. If this is ever
1082 // changed for C++, the additional check here will be redundant.
1083 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1084 assert(srcIsPtr && "One type must be a pointer");
1085 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1086 // type large enough to hold it.
1087 if (Self.Context.getTypeSize(SrcType) >
1088 Self.Context.getTypeSize(DestType)) {
1089 msg = diag::err_bad_reinterpret_cast_small_int;
1090 return TC_Failed;
1091 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001092 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001093 return TC_Success;
1094 }
1095
1096 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1097 assert(destIsPtr && "One type must be a pointer");
1098 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1099 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001100 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001101 return TC_Success;
1102 }
1103
1104 if (!destIsPtr || !srcIsPtr) {
1105 // With the valid non-pointer conversions out of the way, we can be even
1106 // more stringent.
1107 return TC_NotApplicable;
1108 }
1109
1110 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1111 // The C-style cast operator can.
1112 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1113 msg = diag::err_bad_cxx_cast_const_away;
1114 return TC_Failed;
1115 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001116 if (CStyle && DestType->isObjCObjectPointerType()) {
1117 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1118 return TC_Success;
1119 }
1120
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001121 // Not casting away constness, so the only remaining check is for compatible
1122 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001123 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001124
1125 if (SrcType->isFunctionPointerType()) {
1126 if (DestType->isFunctionPointerType()) {
1127 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1128 // a pointer to a function of a different type.
1129 return TC_Success;
1130 }
1131
1132 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1133 // an object type or vice versa is conditionally-supported.
1134 // Compilers support it in C++03 too, though, because it's necessary for
1135 // casting the return value of dlsym() and GetProcAddress().
1136 // FIXME: Conditionally-supported behavior should be configurable in the
1137 // TargetInfo or similar.
1138 if (!Self.getLangOptions().CPlusPlus0x)
1139 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1140 return TC_Success;
1141 }
1142
1143 if (DestType->isFunctionPointerType()) {
1144 // See above.
1145 if (!Self.getLangOptions().CPlusPlus0x)
1146 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1147 return TC_Success;
1148 }
1149
1150 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1151 // a pointer to an object of different type.
1152 // Void pointers are not specified, but supported by every compiler out there.
1153 // So we finish by allowing everything that remains - it's got to be two
1154 // object pointers.
1155 return TC_Success;
1156}
1157
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001158bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001159 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001160 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001161 // This test is outside everything else because it's the only case where
1162 // a non-lvalue-reference target type does not lead to decay.
1163 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001164 if (CastTy->isVoidType()) {
1165 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001166 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001167 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001168
1169 // If the type is dependent, we won't do any other semantic analysis now.
1170 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1171 return false;
1172
Douglas Gregorb653c522009-11-06 01:14:41 +00001173 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001174 DefaultFunctionArrayConversion(CastExpr);
1175
1176 // C++ [expr.cast]p5: The conversions performed by
1177 // - a const_cast,
1178 // - a static_cast,
1179 // - a static_cast followed by a const_cast,
1180 // - a reinterpret_cast, or
1181 // - a reinterpret_cast followed by a const_cast,
1182 // can be performed using the cast notation of explicit type conversion.
1183 // [...] If a conversion can be interpreted in more than one of the ways
1184 // listed above, the interpretation that appears first in the list is used,
1185 // even if a cast resulting from that interpretation is ill-formed.
1186 // In plain language, this means trying a const_cast ...
1187 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001188 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1189 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001190 if (tcr == TC_Success)
1191 Kind = CastExpr::CK_NoOp;
1192
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001193 if (tcr == TC_NotApplicable) {
1194 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001195 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1196 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001197 if (tcr == TC_NotApplicable) {
1198 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001199 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1200 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001201 }
1202 }
1203
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001204 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001205 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001206 << CastExpr->getType() << CastTy << R;
1207
1208 return tcr != TC_Success;
1209}