blob: 8bb334855d02954ec9fe1f67dbdc69e0cd84f25d [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,
73 unsigned &msg);
74static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
75 QualType DestType, bool CStyle,
76 const SourceRange &OpRange,
77 unsigned &msg);
78static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
81 QualType OrigSrcType,
82 QualType OrigDestType, unsigned &msg);
83static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
84 QualType DestType,bool CStyle,
85 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +000086 unsigned &msg,
87 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000088static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
89 QualType DestType, bool CStyle,
90 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000091 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000092 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000093 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000094static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
95 QualType DestType, bool CStyle,
96 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +000097 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000098 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000099 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000100static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
101 bool CStyle, unsigned &msg);
102static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
103 QualType DestType, bool CStyle,
104 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000105 unsigned &msg,
106 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000107
Sebastian Redl26d85b12008-11-05 21:50:06 +0000108/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000109Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000110Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
111 SourceLocation LAngleBracketLoc, TypeTy *Ty,
112 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000113 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000114 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000115 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000116 // FIXME: Preserve type source info.
117 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000118 SourceRange OpRange(OpLoc, RParenLoc);
119 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
120
Douglas Gregor9103bb22008-12-17 22:52:20 +0000121 // If the type is dependent, we won't do the semantic analysis now.
122 // FIXME: should we check this in a more fine-grained manner?
123 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
124
Sebastian Redl26d85b12008-11-05 21:50:06 +0000125 switch (Kind) {
126 default: assert(0 && "Unknown C++ cast!");
127
128 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000129 if (!TypeDependent)
130 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000131 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
132 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000133
Anders Carlsson714179b2009-08-02 19:07:59 +0000134 case tok::kw_dynamic_cast: {
135 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000136 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000137 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000138 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000139 Kind, Ex, DestType, OpLoc));
140 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000141 case tok::kw_reinterpret_cast: {
142 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000143 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000144 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000145 return Owned(new (Context) CXXReinterpretCastExpr(
146 DestType.getNonReferenceType(),
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000147 Kind, Ex, DestType, OpLoc));
148 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000149 case tok::kw_static_cast: {
150 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000151 if (!TypeDependent) {
152 CXXMethodDecl *Method = 0;
153
154 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
155
156 if (Method) {
157 OwningExprResult CastArg
158 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
159 Kind, Method, Owned(Ex));
160 if (CastArg.isInvalid())
161 return ExprError();
162
163 Ex = CastArg.takeAs<Expr>();
164 }
165 }
166
Sebastian Redlf53597f2009-03-15 17:47:39 +0000167 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000168 Kind, Ex, DestType, OpLoc));
169 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000170 }
171
Sebastian Redlf53597f2009-03-15 17:47:39 +0000172 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000173}
174
Sebastian Redldb647282009-01-27 23:18:31 +0000175/// CastsAwayConstness - Check if the pointer conversion from SrcType to
176/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
177/// the cast checkers. Both arguments must denote pointer (possibly to member)
178/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000179static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000180CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000181 // Casting away constness is defined in C++ 5.2.11p8 with reference to
182 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
183 // the rules are non-trivial. So first we construct Tcv *...cv* as described
184 // in C++ 5.2.11p8.
185 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
186 "Source type is not pointer or pointer to member.");
187 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
188 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000189
190 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
John McCall0953e762009-09-24 19:53:00 +0000191 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000192
193 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000194 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000195 cv1.push_back(UnwrappedSrcType.getQualifiers());
196 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000197 }
198 assert(cv1.size() > 0 && "Must have at least one pointer level.");
199
200 // Construct void pointers with those qualifiers (in reverse order of
201 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000202 QualType SrcConstruct = Self.Context.VoidTy;
203 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000204 ASTContext &Context = Self.Context;
205 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
206 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000207 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000208 SrcConstruct
209 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
210 DestConstruct
211 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000212 }
213
214 // Test if they're compatible.
215 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000216 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000217}
218
Sebastian Redl26d85b12008-11-05 21:50:06 +0000219/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
220/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
221/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000222static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000223CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
224 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000225 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000226 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000227 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000228
229 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
230 // or "pointer to cv void".
231
232 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000233 const PointerType *DestPointer = DestType->getAs<PointerType>();
234 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000235 if (DestPointer) {
236 DestPointee = DestPointer->getPointeeType();
237 } else if (DestReference) {
238 DestPointee = DestReference->getPointeeType();
239 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000240 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000241 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000242 return;
243 }
244
Ted Kremenek6217b802009-07-29 21:53:49 +0000245 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000246 if (DestPointee->isVoidType()) {
247 assert(DestPointer && "Reference to void is not possible");
248 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000249 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000250 PDiag(diag::err_bad_dynamic_cast_incomplete)
251 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000253 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000254 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000255 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000256 return;
257 }
258
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000259 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
260 // complete class type, [...]. If T is an lvalue reference type, v shall be
261 // an lvalue of a complete class type, [...]. If T is an rvalue reference
262 // type, v shall be an expression having a complete effective class type,
263 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000264
Sebastian Redl37d6de32008-11-08 13:00:26 +0000265 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000266 QualType SrcPointee;
267 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000268 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000269 SrcPointee = SrcPointer->getPointeeType();
270 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000271 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000272 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000273 return;
274 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000275 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000276 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000277 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000278 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000279 }
280 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000281 } else {
282 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000283 }
284
Ted Kremenek6217b802009-07-29 21:53:49 +0000285 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000286 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000287 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000288 PDiag(diag::err_bad_dynamic_cast_incomplete)
289 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000291 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000292 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000293 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000294 return;
295 }
296
297 assert((DestPointer || DestReference) &&
298 "Bad destination non-ptr/ref slipped through.");
299 assert((DestRecord || DestPointee->isVoidType()) &&
300 "Bad destination pointee slipped through.");
301 assert(SrcRecord && "Bad source pointee slipped through.");
302
303 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
304 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000305 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000306 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000307 return;
308 }
309
310 // C++ 5.2.7p3: If the type of v is the same as the required result type,
311 // [except for cv].
312 if (DestRecord == SrcRecord) {
313 return;
314 }
315
316 // C++ 5.2.7p5
317 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000318 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
319 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000320 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000321 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000322 // Diagnostic already emitted on error.
323 return;
324 }
325
326 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000327 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000328 assert(SrcDecl && "Definition missing");
329 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000330 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000331 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000332 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000333
334 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000335 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000336}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000337
338/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
339/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
340/// like this:
341/// const char *str = "literal";
342/// legacy_function(const_cast\<char*\>(str));
343void
344CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000345 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000346 if (!DestType->isLValueReferenceType())
347 Self.DefaultFunctionArrayConversion(SrcExpr);
348
349 unsigned msg = diag::err_bad_cxx_cast_generic;
350 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
351 && msg != 0)
352 Self.Diag(OpRange.getBegin(), msg) << CT_Const
353 << SrcExpr->getType() << DestType << OpRange;
354}
355
356/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
357/// valid.
358/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
359/// like this:
360/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
361void
362CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000363 const SourceRange &OpRange, const SourceRange &DestRange,
364 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000365 if (!DestType->isLValueReferenceType())
366 Self.DefaultFunctionArrayConversion(SrcExpr);
367
368 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000369 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
370 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000371 != TC_Success && msg != 0)
372 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
373 << SrcExpr->getType() << DestType << OpRange;
374}
375
376
377/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
378/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
379/// implicit conversions explicit and getting rid of data loss warnings.
380void
381CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000382 const SourceRange &OpRange, CastExpr::CastKind &Kind,
383 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000384 // This test is outside everything else because it's the only case where
385 // a non-lvalue-reference target type does not lead to decay.
386 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
387 if (DestType->isVoidType()) {
388 return;
389 }
390
391 if (!DestType->isLValueReferenceType())
392 Self.DefaultFunctionArrayConversion(SrcExpr);
393
394 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000395 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false,OpRange, msg,
396 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000397 != TC_Success && msg != 0)
398 Self.Diag(OpRange.getBegin(), msg) << CT_Static
399 << SrcExpr->getType() << DestType << OpRange;
400}
401
402/// TryStaticCast - Check if a static cast can be performed, and do so if
403/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
404/// and casting away constness.
405static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
406 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000407 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000408 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000409 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000410 // The order the tests is not entirely arbitrary. There is one conversion
411 // that can be handled in two different ways. Given:
412 // struct A {};
413 // struct B : public A {
414 // B(); B(const A&);
415 // };
416 // const A &a = B();
417 // the cast static_cast<const B&>(a) could be seen as either a static
418 // reference downcast, or an explicit invocation of the user-defined
419 // conversion using B's conversion constructor.
420 // DR 427 specifies that the downcast is to be applied here.
421
422 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
423 // Done outside this function.
424
425 TryCastResult tcr;
426
427 // C++ 5.2.9p5, reference downcast.
428 // See the function for details.
429 // DR 427 specifies that this is to be applied before paragraph 2.
430 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
431 if (tcr != TC_NotApplicable)
432 return tcr;
433
434 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
435 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
436 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
437 if (tcr != TC_NotApplicable)
438 return tcr;
439
440 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
441 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000442 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000443 Kind, ConversionDecl);
444 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000445 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000446
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000447 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
448 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
449 // conversions, subject to further restrictions.
450 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
451 // of qualification conversions impossible.
452 // In the CStyle case, the earlier attempt to const_cast should have taken
453 // care of reverse qualification conversions.
454
455 QualType OrigSrcType = SrcExpr->getType();
456
457 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
458
459 // Reverse integral promotion/conversion. All such conversions are themselves
460 // again integral promotions or conversions and are thus already handled by
461 // p2 (TryDirectInitialization above).
462 // (Note: any data loss warnings should be suppressed.)
463 // The exception is the reverse of enum->integer, i.e. integer->enum (and
464 // enum->enum). See also C++ 5.2.9p7.
465 // The same goes for reverse floating point promotion/conversion and
466 // floating-integral conversions. Again, only floating->enum is relevant.
467 if (DestType->isEnumeralType()) {
468 if (SrcType->isComplexType() || SrcType->isVectorType()) {
469 // Fall through - these cannot be converted.
470 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
471 return TC_Success;
472 }
473
474 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
475 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
476 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
477 if (tcr != TC_NotApplicable)
478 return tcr;
479
480 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
481 // conversion. C++ 5.2.9p9 has additional information.
482 // DR54's access restrictions apply here also.
483 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000484 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000485 if (tcr != TC_NotApplicable)
486 return tcr;
487
488 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
489 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
490 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000491 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000492 QualType SrcPointee = SrcPointer->getPointeeType();
493 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000494 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000495 QualType DestPointee = DestPointer->getPointeeType();
496 if (DestPointee->isIncompleteOrObjectType()) {
497 // This is definitely the intended conversion, but it might fail due
498 // to a const violation.
499 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
500 msg = diag::err_bad_cxx_cast_const_away;
501 return TC_Failed;
502 }
503 return TC_Success;
504 }
505 }
506 }
507 }
508
509 // We tried everything. Everything! Nothing works! :-(
510 return TC_NotApplicable;
511}
512
513/// Tests whether a conversion according to N2844 is valid.
514TryCastResult
515TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000516 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000517 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
518 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000519 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000520 if (!R)
521 return TC_NotApplicable;
522
523 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
524 return TC_NotApplicable;
525
526 // Because we try the reference downcast before this function, from now on
527 // this is the only cast possibility, so we issue an error if we fail now.
528 // FIXME: Should allow casting away constness if CStyle.
529 bool DerivedToBase;
530 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
531 DerivedToBase) <
532 Sema::Ref_Compatible_With_Added_Qualification) {
533 msg = diag::err_bad_lvalue_to_rvalue_cast;
534 return TC_Failed;
535 }
536
537 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
538 // than nothing.
539 return TC_Success;
540}
541
542/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
543TryCastResult
544TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
545 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000546 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000547 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
548 // cast to type "reference to cv2 D", where D is a class derived from B,
549 // if a valid standard conversion from "pointer to D" to "pointer to B"
550 // exists, cv2 >= cv1, and B is not a virtual base class of D.
551 // In addition, DR54 clarifies that the base must be accessible in the
552 // current context. Although the wording of DR54 only applies to the pointer
553 // variant of this rule, the intent is clearly for it to apply to the this
554 // conversion as well.
555
Ted Kremenek6217b802009-07-29 21:53:49 +0000556 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000557 if (!DestReference) {
558 return TC_NotApplicable;
559 }
560 bool RValueRef = DestReference->isRValueReferenceType();
561 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
562 // We know the left side is an lvalue reference, so we can suggest a reason.
563 msg = diag::err_bad_cxx_cast_rvalue;
564 return TC_NotApplicable;
565 }
566
567 QualType DestPointee = DestReference->getPointeeType();
568
569 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
570 OpRange, SrcExpr->getType(), DestType, msg);
571}
572
573/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
574TryCastResult
575TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000576 bool CStyle, const SourceRange &OpRange,
577 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000578 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
579 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
580 // is a class derived from B, if a valid standard conversion from "pointer
581 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
582 // class of D.
583 // In addition, DR54 clarifies that the base must be accessible in the
584 // current context.
585
Ted Kremenek6217b802009-07-29 21:53:49 +0000586 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000587 if (!DestPointer) {
588 return TC_NotApplicable;
589 }
590
Ted Kremenek6217b802009-07-29 21:53:49 +0000591 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000592 if (!SrcPointer) {
593 msg = diag::err_bad_static_cast_pointer_nonpointer;
594 return TC_NotApplicable;
595 }
596
597 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
598 DestPointer->getPointeeType(), CStyle,
599 OpRange, SrcType, DestType, msg);
600}
601
602/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
603/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
604/// DestType, both of which must be canonical, is possible and allowed.
605TryCastResult
606TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
607 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump1eb44332009-09-09 15:08:12 +0000608 QualType OrigDestType, unsigned &msg) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000609 // We can only work with complete types. But don't complain if it doesn't work
610 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
611 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
612 return TC_NotApplicable;
613
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000614 // Downcast can only happen in class hierarchies, so we need classes.
615 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
616 return TC_NotApplicable;
617 }
618
Douglas Gregora8f32e02009-10-06 17:59:45 +0000619 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
620 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000621 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
622 return TC_NotApplicable;
623 }
624
625 // Target type does derive from source type. Now we're serious. If an error
626 // appears now, it's not ignored.
627 // This may not be entirely in line with the standard. Take for example:
628 // struct A {};
629 // struct B : virtual A {
630 // B(A&);
631 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000632 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000633 // void f()
634 // {
635 // (void)static_cast<const B&>(*((A*)0));
636 // }
637 // As far as the standard is concerned, p5 does not apply (A is virtual), so
638 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
639 // However, both GCC and Comeau reject this example, and accepting it would
640 // mean more complex code if we're to preserve the nice error message.
641 // FIXME: Being 100% compliant here would be nice to have.
642
643 // Must preserve cv, as always, unless we're in C-style mode.
644 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
645 msg = diag::err_bad_cxx_cast_const_away;
646 return TC_Failed;
647 }
648
649 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
650 // This code is analoguous to that in CheckDerivedToBaseConversion, except
651 // that it builds the paths in reverse order.
652 // To sum up: record all paths to the base and build a nice string from
653 // them. Use it to spice up the error message.
654 if (!Paths.isRecordingPaths()) {
655 Paths.clear();
656 Paths.setRecordingPaths(true);
657 Self.IsDerivedFrom(DestType, SrcType, Paths);
658 }
659 std::string PathDisplayStr;
660 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000661 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000662 PI != PE; ++PI) {
663 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
664 // We haven't displayed a path to this particular base
665 // class subobject yet.
666 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000667 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
668 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000669 EI != EE; ++EI)
670 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
671 PathDisplayStr += DestType.getAsString();
672 }
673 }
674
675 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
676 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
677 << PathDisplayStr << OpRange;
678 msg = 0;
679 return TC_Failed;
680 }
681
682 if (Paths.getDetectedVirtual() != 0) {
683 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
684 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
685 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
686 msg = 0;
687 return TC_Failed;
688 }
689
690 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
691 diag::err_downcast_from_inaccessible_base, Paths,
692 OpRange.getBegin(), DeclarationName())) {
693 msg = 0;
694 return TC_Failed;
695 }
696
697 return TC_Success;
698}
699
700/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
701/// C++ 5.2.9p9 is valid:
702///
703/// An rvalue of type "pointer to member of D of type cv1 T" can be
704/// converted to an rvalue of type "pointer to member of B of type cv2 T",
705/// where B is a base class of D [...].
706///
707TryCastResult
708TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
709 bool CStyle, const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000710 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000711 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000712 if (!DestMemPtr)
713 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000714 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000715 if (!SrcMemPtr) {
716 msg = diag::err_bad_static_cast_member_pointer_nonmp;
717 return TC_NotApplicable;
718 }
719
720 // T == T, modulo cv
721 if (Self.Context.getCanonicalType(
722 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
723 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
724 getUnqualifiedType()))
725 return TC_NotApplicable;
726
727 // B base of D
728 QualType SrcClass(SrcMemPtr->getClass(), 0);
729 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000731 /*DetectVirtual=*/true);
732 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
733 return TC_NotApplicable;
734 }
735
736 // B is a base of D. But is it an allowed base? If not, it's a hard error.
737 if (Paths.isAmbiguous(DestClass)) {
738 Paths.clear();
739 Paths.setRecordingPaths(true);
740 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
741 assert(StillOkay);
742 StillOkay = StillOkay;
743 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
744 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
745 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
746 msg = 0;
747 return TC_Failed;
748 }
749
750 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
751 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
752 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
753 msg = 0;
754 return TC_Failed;
755 }
756
757 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
758 diag::err_downcast_from_inaccessible_base, Paths,
759 OpRange.getBegin(), DeclarationName())) {
760 msg = 0;
761 return TC_Failed;
762 }
763
Anders Carlsson1a31a182009-10-30 00:46:35 +0000764 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000765 return TC_Success;
766}
767
768/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
769/// is valid:
770///
771/// An expression e can be explicitly converted to a type T using a
772/// @c static_cast if the declaration "T t(e);" is well-formed [...].
773TryCastResult
774TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000775 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000776 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000777 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000778 if (DestType->isRecordType()) {
779 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
780 diag::err_bad_dynamic_cast_incomplete)) {
781 msg = 0;
782 return TC_Failed;
783 }
784 }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000786 if (DestType->isReferenceType()) {
787 // At this point of CheckStaticCast, if the destination is a reference,
788 // this has to work. There is no other way that works.
789 // On the other hand, if we're checking a C-style cast, we've still got
790 // the reinterpret_cast way. In that case, we pass an ICS so we don't
791 // get error messages.
792 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +0000793 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000794 OpRange.getBegin(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000795 /*SuppressUserConversions=*/false,
796 /*AllowExplicit=*/false,
797 /*ForceRValue=*/false,
798 CStyle ? &ICS : 0);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000799 if (!failed)
800 return TC_Success;
801 if (CStyle)
802 return TC_NotApplicable;
803 // If we didn't pass the ICS, we already got an error message.
804 msg = 0;
805 return TC_Failed;
806 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000807
808 // FIXME: To get a proper error from invalid conversions here, we need to
809 // reimplement more of this.
810 // FIXME: This does not actually perform the conversion, and thus does not
811 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000813 Self.TryImplicitConversion(SrcExpr, DestType,
814 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000815 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000816 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000817 /*InOverloadResolution=*/false,
818 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Anders Carlsson3c31a392009-09-26 00:12:34 +0000820 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
821 return TC_NotApplicable;
822
Anders Carlsson0aebc812009-09-09 21:33:21 +0000823 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) {
Anders Carlsson3c31a392009-09-26 00:12:34 +0000824 ConversionDecl = cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction);
825 if (isa<CXXConstructorDecl>(ConversionDecl))
826 Kind = CastExpr::CK_ConstructorConversion;
827 else if (isa<CXXConversionDecl>(ConversionDecl))
828 Kind = CastExpr::CK_UserDefinedConversion;
829 } else if (ICS.ConversionKind ==
830 ImplicitConversionSequence::StandardConversion) {
831 // FIXME: Set the cast kind depending on which types of conversions we have.
Anders Carlsson0aebc812009-09-09 21:33:21 +0000832 }
Anders Carlsson3c31a392009-09-26 00:12:34 +0000833
834 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000835}
836
837/// TryConstCast - See if a const_cast from source to destination is allowed,
838/// and perform it if it is.
839static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
840 bool CStyle, unsigned &msg) {
841 DestType = Self.Context.getCanonicalType(DestType);
842 QualType SrcType = SrcExpr->getType();
843 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000844 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000845 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
846 // Cannot const_cast non-lvalue to lvalue reference type. But if this
847 // is C-style, static_cast might find a way, so we simply suggest a
848 // message and tell the parent to keep searching.
849 msg = diag::err_bad_cxx_cast_rvalue;
850 return TC_NotApplicable;
851 }
852
853 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
854 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
855 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
856 SrcType = Self.Context.getPointerType(SrcType);
857 }
858
859 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
860 // the rules for const_cast are the same as those used for pointers.
861
862 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
863 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
864 // was a reference type, we converted it to a pointer above.
865 // The status of rvalue references isn't entirely clear, but it looks like
866 // conversion to them is simply invalid.
867 // C++ 5.2.11p3: For two pointer types [...]
868 if (!CStyle)
869 msg = diag::err_bad_const_cast_dest;
870 return TC_NotApplicable;
871 }
872 if (DestType->isFunctionPointerType() ||
873 DestType->isMemberFunctionPointerType()) {
874 // Cannot cast direct function pointers.
875 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
876 // T is the ultimate pointee of source and target type.
877 if (!CStyle)
878 msg = diag::err_bad_const_cast_dest;
879 return TC_NotApplicable;
880 }
881 SrcType = Self.Context.getCanonicalType(SrcType);
882
883 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
884 // completely equal.
885 // FIXME: const_cast should probably not be able to convert between pointers
886 // to different address spaces.
887 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
888 // in multi-level pointers may change, but the level count must be the same,
889 // as must be the final pointee type.
890 while (SrcType != DestType &&
891 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
892 SrcType = SrcType.getUnqualifiedType();
893 DestType = DestType.getUnqualifiedType();
894 }
895
896 // Since we're dealing in canonical types, the remainder must be the same.
897 if (SrcType != DestType)
898 return TC_NotApplicable;
899
900 return TC_Success;
901}
902
903static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
904 QualType DestType, bool CStyle,
905 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000906 unsigned &msg,
907 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000908 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
909
910 DestType = Self.Context.getCanonicalType(DestType);
911 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000912 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000913 bool LValue = DestTypeTmp->isLValueReferenceType();
914 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
915 // Cannot cast non-lvalue to reference type. See the similar comment in
916 // const_cast.
917 msg = diag::err_bad_cxx_cast_rvalue;
918 return TC_NotApplicable;
919 }
920
921 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
922 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
923 // built-in & and * operators.
924 // This code does this transformation for the checked types.
925 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
926 SrcType = Self.Context.getPointerType(SrcType);
927 }
928
929 // Canonicalize source for comparison.
930 SrcType = Self.Context.getCanonicalType(SrcType);
931
Ted Kremenek6217b802009-07-29 21:53:49 +0000932 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
933 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000934 if (DestMemPtr && SrcMemPtr) {
935 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
936 // can be explicitly converted to an rvalue of type "pointer to member
937 // of Y of type T2" if T1 and T2 are both function types or both object
938 // types.
939 if (DestMemPtr->getPointeeType()->isFunctionType() !=
940 SrcMemPtr->getPointeeType()->isFunctionType())
941 return TC_NotApplicable;
942
943 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
944 // constness.
945 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
946 // we accept it.
947 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
948 msg = diag::err_bad_cxx_cast_const_away;
949 return TC_Failed;
950 }
951
952 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000953 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000954 return TC_Success;
955 }
956
957 // See below for the enumeral issue.
958 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
959 !DestType->isEnumeralType()) {
960 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
961 // type large enough to hold it. A value of std::nullptr_t can be
962 // converted to an integral type; the conversion has the same meaning
963 // and validity as a conversion of (void*)0 to the integral type.
964 if (Self.Context.getTypeSize(SrcType) >
965 Self.Context.getTypeSize(DestType)) {
966 msg = diag::err_bad_reinterpret_cast_small_int;
967 return TC_Failed;
968 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000969 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000970 return TC_Success;
971 }
972
Anders Carlsson0de51bc2009-09-16 19:19:43 +0000973 bool destIsVector = DestType->isVectorType();
974 bool srcIsVector = SrcType->isVectorType();
975 if (srcIsVector || destIsVector) {
976 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
977 bool destIsScalar =
978 DestType->isIntegralType() && !DestType->isEnumeralType();
979
980 // Check if this is a cast between a vector and something else.
981 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
982 !(srcIsVector && destIsVector))
983 return TC_NotApplicable;
984
985 // If both types have the same size, we can successfully cast.
986 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
987 return TC_Success;
988
989 if (destIsScalar)
990 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
991 else if (srcIsScalar)
992 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
993 else
994 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
995
996 return TC_Failed;
997 }
998
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000999 bool destIsPtr = DestType->isPointerType();
1000 bool srcIsPtr = SrcType->isPointerType();
1001 if (!destIsPtr && !srcIsPtr) {
1002 // Except for std::nullptr_t->integer and lvalue->reference, which are
1003 // handled above, at least one of the two arguments must be a pointer.
1004 return TC_NotApplicable;
1005 }
1006
1007 if (SrcType == DestType) {
1008 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1009 // restrictions, a cast to the same type is allowed. The intent is not
1010 // entirely clear here, since all other paragraphs explicitly forbid casts
1011 // to the same type. However, the behavior of compilers is pretty consistent
1012 // on this point: allow same-type conversion if the involved types are
1013 // pointers, disallow otherwise.
1014 return TC_Success;
1015 }
1016
1017 // Note: Clang treats enumeration types as integral types. If this is ever
1018 // changed for C++, the additional check here will be redundant.
1019 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1020 assert(srcIsPtr && "One type must be a pointer");
1021 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1022 // type large enough to hold it.
1023 if (Self.Context.getTypeSize(SrcType) >
1024 Self.Context.getTypeSize(DestType)) {
1025 msg = diag::err_bad_reinterpret_cast_small_int;
1026 return TC_Failed;
1027 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001028 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001029 return TC_Success;
1030 }
1031
1032 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1033 assert(destIsPtr && "One type must be a pointer");
1034 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1035 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001036 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001037 return TC_Success;
1038 }
1039
1040 if (!destIsPtr || !srcIsPtr) {
1041 // With the valid non-pointer conversions out of the way, we can be even
1042 // more stringent.
1043 return TC_NotApplicable;
1044 }
1045
1046 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1047 // The C-style cast operator can.
1048 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1049 msg = diag::err_bad_cxx_cast_const_away;
1050 return TC_Failed;
1051 }
1052
1053 // Not casting away constness, so the only remaining check is for compatible
1054 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001055 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001056
1057 if (SrcType->isFunctionPointerType()) {
1058 if (DestType->isFunctionPointerType()) {
1059 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1060 // a pointer to a function of a different type.
1061 return TC_Success;
1062 }
1063
1064 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1065 // an object type or vice versa is conditionally-supported.
1066 // Compilers support it in C++03 too, though, because it's necessary for
1067 // casting the return value of dlsym() and GetProcAddress().
1068 // FIXME: Conditionally-supported behavior should be configurable in the
1069 // TargetInfo or similar.
1070 if (!Self.getLangOptions().CPlusPlus0x)
1071 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1072 return TC_Success;
1073 }
1074
1075 if (DestType->isFunctionPointerType()) {
1076 // See above.
1077 if (!Self.getLangOptions().CPlusPlus0x)
1078 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1079 return TC_Success;
1080 }
1081
1082 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1083 // a pointer to an object of different type.
1084 // Void pointers are not specified, but supported by every compiler out there.
1085 // So we finish by allowing everything that remains - it's got to be two
1086 // object pointers.
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001087 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001088 return TC_Success;
1089}
1090
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001091bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001092 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001093 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001094 // This test is outside everything else because it's the only case where
1095 // a non-lvalue-reference target type does not lead to decay.
1096 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001097 if (CastTy->isVoidType()) {
1098 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001099 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001100 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001101
1102 // If the type is dependent, we won't do any other semantic analysis now.
1103 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1104 return false;
1105
1106 if (!CastTy->isLValueReferenceType())
1107 DefaultFunctionArrayConversion(CastExpr);
1108
1109 // C++ [expr.cast]p5: The conversions performed by
1110 // - a const_cast,
1111 // - a static_cast,
1112 // - a static_cast followed by a const_cast,
1113 // - a reinterpret_cast, or
1114 // - a reinterpret_cast followed by a const_cast,
1115 // can be performed using the cast notation of explicit type conversion.
1116 // [...] If a conversion can be interpreted in more than one of the ways
1117 // listed above, the interpretation that appears first in the list is used,
1118 // even if a cast resulting from that interpretation is ill-formed.
1119 // In plain language, this means trying a const_cast ...
1120 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001121 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1122 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001123 if (tcr == TC_Success)
1124 Kind = CastExpr::CK_NoOp;
1125
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001126 if (tcr == TC_NotApplicable) {
1127 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001128 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1129 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001130 if (tcr == TC_NotApplicable) {
1131 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001132 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1133 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001134 }
1135 }
1136
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001137 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001138 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001139 << CastExpr->getType() << CastTy << R;
1140
1141 return tcr != TC_Success;
1142}