blob: d055dd4c58309c108d8ea1bb41172ac1060456f0 [file] [log] [blame]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000015#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000018#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000019#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl9f831db2009-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 Redl842ef522008-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 Carlsson7cd39e02009-09-15 04:48:33 +000044 const SourceRange &DestRange,
45 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000046static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssonf10e4142009-08-07 22:21:05 +000047 const SourceRange &OpRange,
Anders Carlssone9766d52009-09-09 21:33:21 +000048 CastExpr::CastKind &Kind,
49 CXXMethodDecl *&ConversionDecl);
Sebastian Redl842ef522008-11-08 13:00:26 +000050static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
51 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000052 const SourceRange &DestRange,
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +000053 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000054
55static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-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 Carlsson9a1cd872009-11-12 16:53:16 +000073 unsigned &msg,
74 CastExpr::CastKind &Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +000075static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
76 QualType DestType, bool CStyle,
77 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000078 unsigned &msg,
79 CastExpr::CastKind &Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +000080static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
81 QualType DestType, bool CStyle,
82 const SourceRange &OpRange,
83 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000084 QualType OrigDestType, unsigned &msg,
85 CastExpr::CastKind &Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +000086static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
87 QualType DestType,bool CStyle,
88 const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +000089 unsigned &msg,
90 CastExpr::CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +000091static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +000092 QualType DestType, bool CStyle,
93 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000094 unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +000095 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000096 CXXMethodDecl *&ConversionDecl);
Sebastian Redl7c353682009-11-14 21:15:49 +000097static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +000098 QualType DestType, bool CStyle,
99 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000100 unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000101 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000102 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9f831db2009-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 Carlsson9d1b34b2009-09-26 00:12:34 +0000108 unsigned &msg,
109 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000110
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000111/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000112Action::OwningExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000113Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
114 SourceLocation LAngleBracketLoc, TypeTy *Ty,
115 SourceLocation RAngleBracketLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000116 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000117 SourceLocation RParenLoc) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000118 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000119 // FIXME: Preserve type source info.
120 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000121 SourceRange OpRange(OpLoc, RParenLoc);
122 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
123
Douglas Gregor19b8c4f2008-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 Redl3c5aa4d2008-11-05 21:50:06 +0000128 switch (Kind) {
129 default: assert(0 && "Unknown C++ cast!");
130
131 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000132 if (!TypeDependent)
133 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000134 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
135 Ex, DestType, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000136
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000137 case tok::kw_dynamic_cast: {
138 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000139 if (!TypeDependent)
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000140 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000141 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000142 Kind, Ex, DestType, OpLoc));
143 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000144 case tok::kw_reinterpret_cast: {
145 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000146 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000147 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000148 return Owned(new (Context) CXXReinterpretCastExpr(
149 DestType.getNonReferenceType(),
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000150 Kind, Ex, DestType, OpLoc));
151 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000152 case tok::kw_static_cast: {
153 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-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 Redl6d4256c2009-03-15 17:47:39 +0000170 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssonf10e4142009-08-07 22:21:05 +0000171 Kind, Ex, DestType, OpLoc));
172 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000173 }
174
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000175 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000176}
177
Sebastian Redla5a77a62009-01-27 23:18:31 +0000178/// CastsAwayConstness - Check if the pointer conversion from SrcType to
179/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
180/// the cast checkers. Both arguments must denote pointer (possibly to member)
181/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000182static bool
Mike Stump11289f42009-09-09 15:08:12 +0000183CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000184 // Casting away constness is defined in C++ 5.2.11p8 with reference to
185 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
186 // the rules are non-trivial. So first we construct Tcv *...cv* as described
187 // in C++ 5.2.11p8.
188 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
189 "Source type is not pointer or pointer to member.");
190 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
191 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000192
193 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
John McCall8ccfcb52009-09-24 19:53:00 +0000194 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000195
196 // Find the qualifications.
Sebastian Redl842ef522008-11-08 13:00:26 +0000197 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000198 cv1.push_back(UnwrappedSrcType.getQualifiers());
199 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000200 }
201 assert(cv1.size() > 0 && "Must have at least one pointer level.");
202
203 // Construct void pointers with those qualifiers (in reverse order of
204 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000205 QualType SrcConstruct = Self.Context.VoidTy;
206 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000207 ASTContext &Context = Self.Context;
208 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
209 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000210 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000211 SrcConstruct
212 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
213 DestConstruct
214 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215 }
216
217 // Test if they're compatible.
218 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000219 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000220}
221
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000222/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
223/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
224/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000225static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000226CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
227 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +0000228 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000229 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000230 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000231
232 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
233 // or "pointer to cv void".
234
235 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000236 const PointerType *DestPointer = DestType->getAs<PointerType>();
237 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000238 if (DestPointer) {
239 DestPointee = DestPointer->getPointeeType();
240 } else if (DestReference) {
241 DestPointee = DestReference->getPointeeType();
242 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000243 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000244 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000245 return;
246 }
247
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000248 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000249 if (DestPointee->isVoidType()) {
250 assert(DestPointer && "Reference to void is not possible");
251 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000252 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000253 PDiag(diag::err_bad_dynamic_cast_incomplete)
254 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000255 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000256 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000257 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000258 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000259 return;
260 }
261
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000262 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
263 // complete class type, [...]. If T is an lvalue reference type, v shall be
264 // an lvalue of a complete class type, [...]. If T is an rvalue reference
265 // type, v shall be an expression having a complete effective class type,
266 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000267
Sebastian Redl842ef522008-11-08 13:00:26 +0000268 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000269 QualType SrcPointee;
270 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000271 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000272 SrcPointee = SrcPointer->getPointeeType();
273 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000274 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000275 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000276 return;
277 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000278 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000279 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000280 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000281 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000282 }
283 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000284 } else {
285 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000286 }
287
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000288 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000289 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000290 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000291 PDiag(diag::err_bad_dynamic_cast_incomplete)
292 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000293 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000294 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000295 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000296 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000297 return;
298 }
299
300 assert((DestPointer || DestReference) &&
301 "Bad destination non-ptr/ref slipped through.");
302 assert((DestRecord || DestPointee->isVoidType()) &&
303 "Bad destination pointee slipped through.");
304 assert(SrcRecord && "Bad source pointee slipped through.");
305
306 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
307 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000308 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000309 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000310 return;
311 }
312
313 // C++ 5.2.7p3: If the type of v is the same as the required result type,
314 // [except for cv].
315 if (DestRecord == SrcRecord) {
316 return;
317 }
318
319 // C++ 5.2.7p5
320 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000321 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
322 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner1e5665e2008-11-24 06:25:27 +0000323 OpRange.getBegin(), OpRange);
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000324 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000325 // Diagnostic already emitted on error.
326 return;
327 }
328
329 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl842ef522008-11-08 13:00:26 +0000330 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redlb426f6332008-11-06 15:59:35 +0000331 assert(SrcDecl && "Definition missing");
332 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000333 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000334 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000335 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000336
337 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000338 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000339}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000340
341/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
342/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
343/// like this:
344/// const char *str = "literal";
345/// legacy_function(const_cast\<char*\>(str));
346void
347CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000348 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000349 if (!DestType->isLValueReferenceType())
350 Self.DefaultFunctionArrayConversion(SrcExpr);
351
352 unsigned msg = diag::err_bad_cxx_cast_generic;
353 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
354 && msg != 0)
355 Self.Diag(OpRange.getBegin(), msg) << CT_Const
356 << SrcExpr->getType() << DestType << OpRange;
357}
358
359/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
360/// valid.
361/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
362/// like this:
363/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
364void
365CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000366 const SourceRange &OpRange, const SourceRange &DestRange,
367 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000368 if (!DestType->isLValueReferenceType())
369 Self.DefaultFunctionArrayConversion(SrcExpr);
370
371 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000372 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
373 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000374 != TC_Success && msg != 0)
375 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
376 << SrcExpr->getType() << DestType << OpRange;
377}
378
379
380/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
381/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
382/// implicit conversions explicit and getting rid of data loss warnings.
383void
384CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssone9766d52009-09-09 21:33:21 +0000385 const SourceRange &OpRange, CastExpr::CastKind &Kind,
386 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000387 // This test is outside everything else because it's the only case where
388 // a non-lvalue-reference target type does not lead to decay.
389 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl7c353682009-11-14 21:15:49 +0000390 if (DestType->isVoidType())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000391 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000392
Douglas Gregorad8b2222009-11-06 01:14:41 +0000393 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000394 Self.DefaultFunctionArrayConversion(SrcExpr);
395
396 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000397 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000398 Kind, ConversionDecl)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000399 != TC_Success && msg != 0)
400 Self.Diag(OpRange.getBegin(), msg) << CT_Static
401 << SrcExpr->getType() << DestType << OpRange;
402}
403
404/// TryStaticCast - Check if a static cast can be performed, and do so if
405/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
406/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000407static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000408 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000409 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000410 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000411 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000412 // The order the tests is not entirely arbitrary. There is one conversion
413 // that can be handled in two different ways. Given:
414 // struct A {};
415 // struct B : public A {
416 // B(); B(const A&);
417 // };
418 // const A &a = B();
419 // the cast static_cast<const B&>(a) could be seen as either a static
420 // reference downcast, or an explicit invocation of the user-defined
421 // conversion using B's conversion constructor.
422 // DR 427 specifies that the downcast is to be applied here.
423
424 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
425 // Done outside this function.
426
427 TryCastResult tcr;
428
429 // C++ 5.2.9p5, reference downcast.
430 // See the function for details.
431 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000432 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000433 msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000434 if (tcr != TC_NotApplicable)
435 return tcr;
436
437 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
438 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
439 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000440 if (tcr != TC_NotApplicable) {
441 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000442 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000443 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000444
445 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
446 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000447 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000448 Kind, ConversionDecl);
449 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000450 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000451
Sebastian Redl9f831db2009-07-25 15:41:38 +0000452 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
453 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
454 // conversions, subject to further restrictions.
455 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
456 // of qualification conversions impossible.
457 // In the CStyle case, the earlier attempt to const_cast should have taken
458 // care of reverse qualification conversions.
459
460 QualType OrigSrcType = SrcExpr->getType();
461
462 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
463
464 // Reverse integral promotion/conversion. All such conversions are themselves
465 // again integral promotions or conversions and are thus already handled by
466 // p2 (TryDirectInitialization above).
467 // (Note: any data loss warnings should be suppressed.)
468 // The exception is the reverse of enum->integer, i.e. integer->enum (and
469 // enum->enum). See also C++ 5.2.9p7.
470 // The same goes for reverse floating point promotion/conversion and
471 // floating-integral conversions. Again, only floating->enum is relevant.
472 if (DestType->isEnumeralType()) {
473 if (SrcType->isComplexType() || SrcType->isVectorType()) {
474 // Fall through - these cannot be converted.
475 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
476 return TC_Success;
477 }
478
479 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
480 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000481 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
482 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000483 if (tcr != TC_NotApplicable)
484 return tcr;
485
486 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
487 // conversion. C++ 5.2.9p9 has additional information.
488 // DR54's access restrictions apply here also.
489 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000490 OpRange, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000491 if (tcr != TC_NotApplicable)
492 return tcr;
493
494 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
495 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
496 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000497 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000498 QualType SrcPointee = SrcPointer->getPointeeType();
499 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000500 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000501 QualType DestPointee = DestPointer->getPointeeType();
502 if (DestPointee->isIncompleteOrObjectType()) {
503 // This is definitely the intended conversion, but it might fail due
504 // to a const violation.
505 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
506 msg = diag::err_bad_cxx_cast_const_away;
507 return TC_Failed;
508 }
509 return TC_Success;
510 }
511 }
512 }
513 }
514
515 // We tried everything. Everything! Nothing works! :-(
516 return TC_NotApplicable;
517}
518
519/// Tests whether a conversion according to N2844 is valid.
520TryCastResult
521TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000522 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000523 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
524 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000525 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000526 if (!R)
527 return TC_NotApplicable;
528
529 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
530 return TC_NotApplicable;
531
532 // Because we try the reference downcast before this function, from now on
533 // this is the only cast possibility, so we issue an error if we fail now.
534 // FIXME: Should allow casting away constness if CStyle.
535 bool DerivedToBase;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000536 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
537 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9f831db2009-07-25 15:41:38 +0000538 DerivedToBase) <
539 Sema::Ref_Compatible_With_Added_Qualification) {
540 msg = diag::err_bad_lvalue_to_rvalue_cast;
541 return TC_Failed;
542 }
543
544 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
545 // than nothing.
546 return TC_Success;
547}
548
549/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
550TryCastResult
551TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
552 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000553 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000554 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
555 // cast to type "reference to cv2 D", where D is a class derived from B,
556 // if a valid standard conversion from "pointer to D" to "pointer to B"
557 // exists, cv2 >= cv1, and B is not a virtual base class of D.
558 // In addition, DR54 clarifies that the base must be accessible in the
559 // current context. Although the wording of DR54 only applies to the pointer
560 // variant of this rule, the intent is clearly for it to apply to the this
561 // conversion as well.
562
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000563 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000564 if (!DestReference) {
565 return TC_NotApplicable;
566 }
567 bool RValueRef = DestReference->isRValueReferenceType();
568 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
569 // We know the left side is an lvalue reference, so we can suggest a reason.
570 msg = diag::err_bad_cxx_cast_rvalue;
571 return TC_NotApplicable;
572 }
573
574 QualType DestPointee = DestReference->getPointeeType();
575
576 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000577 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000578}
579
580/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
581TryCastResult
582TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000583 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000584 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000585 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
586 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
587 // is a class derived from B, if a valid standard conversion from "pointer
588 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
589 // class of D.
590 // In addition, DR54 clarifies that the base must be accessible in the
591 // current context.
592
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000593 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000594 if (!DestPointer) {
595 return TC_NotApplicable;
596 }
597
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000598 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000599 if (!SrcPointer) {
600 msg = diag::err_bad_static_cast_pointer_nonpointer;
601 return TC_NotApplicable;
602 }
603
604 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
605 DestPointer->getPointeeType(), CStyle,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000606 OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000607}
608
609/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
610/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
611/// DestType, both of which must be canonical, is possible and allowed.
612TryCastResult
613TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
614 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000615 QualType OrigDestType, unsigned &msg,
616 CastExpr::CastKind &Kind) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000617 // We can only work with complete types. But don't complain if it doesn't work
618 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
619 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
620 return TC_NotApplicable;
621
Sebastian Redl9f831db2009-07-25 15:41:38 +0000622 // Downcast can only happen in class hierarchies, so we need classes.
623 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
624 return TC_NotApplicable;
625 }
626
Douglas Gregor36d1b142009-10-06 17:59:45 +0000627 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
628 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000629 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
630 return TC_NotApplicable;
631 }
632
633 // Target type does derive from source type. Now we're serious. If an error
634 // appears now, it's not ignored.
635 // This may not be entirely in line with the standard. Take for example:
636 // struct A {};
637 // struct B : virtual A {
638 // B(A&);
639 // };
Mike Stump11289f42009-09-09 15:08:12 +0000640 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000641 // void f()
642 // {
643 // (void)static_cast<const B&>(*((A*)0));
644 // }
645 // As far as the standard is concerned, p5 does not apply (A is virtual), so
646 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
647 // However, both GCC and Comeau reject this example, and accepting it would
648 // mean more complex code if we're to preserve the nice error message.
649 // FIXME: Being 100% compliant here would be nice to have.
650
651 // Must preserve cv, as always, unless we're in C-style mode.
652 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
653 msg = diag::err_bad_cxx_cast_const_away;
654 return TC_Failed;
655 }
656
657 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
658 // This code is analoguous to that in CheckDerivedToBaseConversion, except
659 // that it builds the paths in reverse order.
660 // To sum up: record all paths to the base and build a nice string from
661 // them. Use it to spice up the error message.
662 if (!Paths.isRecordingPaths()) {
663 Paths.clear();
664 Paths.setRecordingPaths(true);
665 Self.IsDerivedFrom(DestType, SrcType, Paths);
666 }
667 std::string PathDisplayStr;
668 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000669 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000670 PI != PE; ++PI) {
671 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
672 // We haven't displayed a path to this particular base
673 // class subobject yet.
674 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000675 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
676 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000677 EI != EE; ++EI)
678 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
679 PathDisplayStr += DestType.getAsString();
680 }
681 }
682
683 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
684 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
685 << PathDisplayStr << OpRange;
686 msg = 0;
687 return TC_Failed;
688 }
689
690 if (Paths.getDetectedVirtual() != 0) {
691 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
692 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
693 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
694 msg = 0;
695 return TC_Failed;
696 }
697
698 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
699 diag::err_downcast_from_inaccessible_base, Paths,
700 OpRange.getBegin(), DeclarationName())) {
701 msg = 0;
702 return TC_Failed;
703 }
704
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000705 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000706 return TC_Success;
707}
708
709/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
710/// C++ 5.2.9p9 is valid:
711///
712/// An rvalue of type "pointer to member of D of type cv1 T" can be
713/// converted to an rvalue of type "pointer to member of B of type cv2 T",
714/// where B is a base class of D [...].
715///
716TryCastResult
717TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
718 bool CStyle, const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000719 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000720 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000721 if (!DestMemPtr)
722 return TC_NotApplicable;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000723 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000724 if (!SrcMemPtr) {
725 msg = diag::err_bad_static_cast_member_pointer_nonmp;
726 return TC_NotApplicable;
727 }
728
729 // T == T, modulo cv
730 if (Self.Context.getCanonicalType(
731 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
732 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
733 getUnqualifiedType()))
734 return TC_NotApplicable;
735
736 // B base of D
737 QualType SrcClass(SrcMemPtr->getClass(), 0);
738 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000739 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000740 /*DetectVirtual=*/true);
741 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
742 return TC_NotApplicable;
743 }
744
745 // B is a base of D. But is it an allowed base? If not, it's a hard error.
746 if (Paths.isAmbiguous(DestClass)) {
747 Paths.clear();
748 Paths.setRecordingPaths(true);
749 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
750 assert(StillOkay);
751 StillOkay = StillOkay;
752 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
753 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
754 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
755 msg = 0;
756 return TC_Failed;
757 }
758
759 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
760 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
761 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
762 msg = 0;
763 return TC_Failed;
764 }
765
766 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
767 diag::err_downcast_from_inaccessible_base, Paths,
768 OpRange.getBegin(), DeclarationName())) {
769 msg = 0;
770 return TC_Failed;
771 }
772
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000773 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000774 return TC_Success;
775}
776
777/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
778/// is valid:
779///
780/// An expression e can be explicitly converted to a type T using a
781/// @c static_cast if the declaration "T t(e);" is well-formed [...].
782TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000783TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000784 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000785 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000786 CXXMethodDecl *&ConversionDecl) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000787 if (DestType->isRecordType()) {
788 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
789 diag::err_bad_dynamic_cast_incomplete)) {
790 msg = 0;
791 return TC_Failed;
792 }
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Sebastian Redl9f831db2009-07-25 15:41:38 +0000795 if (DestType->isReferenceType()) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000796 // All reference bindings insert implicit casts above that do the actual
797 // casting.
798 Kind = CastExpr::CK_NoOp;
799
Sebastian Redl9f831db2009-07-25 15:41:38 +0000800 // At this point of CheckStaticCast, if the destination is a reference,
801 // this has to work. There is no other way that works.
802 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redl7c353682009-11-14 21:15:49 +0000803 // the reinterpret_cast way. So in C-style mode, we first try the call
804 // with an ICS to suppress errors.
805 if (CStyle) {
806 ImplicitConversionSequence ICS;
807 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
808 /*SuppressUserConversions=*/false,
809 /*AllowExplicit=*/false, /*ForceRValue=*/false,
810 &ICS))
811 return TC_NotApplicable;
812 }
813 // Now we're committed either way.
814 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
815 /*SuppressUserConversions=*/false,
816 /*AllowExplicit=*/false,
817 /*ForceRValue=*/false, 0,
818 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000819 return TC_Success;
Sebastian Redl7c353682009-11-14 21:15:49 +0000820
821 // We already got an error message.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000822 msg = 0;
823 return TC_Failed;
824 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000825
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000826 if (DestType->isRecordType()) {
827 if (CXXConstructorDecl *Constructor
Sebastian Redl7c353682009-11-14 21:15:49 +0000828 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000829 OpRange.getBegin(),
830 Sema::IK_Direct)) {
831 ConversionDecl = Constructor;
832 Kind = CastExpr::CK_ConstructorConversion;
833 return TC_Success;
834 }
835
836 return TC_NotApplicable;
837 }
Sebastian Redl7c353682009-11-14 21:15:49 +0000838
Sebastian Redl9f831db2009-07-25 15:41:38 +0000839 // FIXME: To get a proper error from invalid conversions here, we need to
840 // reimplement more of this.
841 // FIXME: This does not actually perform the conversion, and thus does not
842 // check for ambiguity or access.
Mike Stump11289f42009-09-09 15:08:12 +0000843 ImplicitConversionSequence ICS =
Anders Carlssonef4c7212009-08-27 17:24:15 +0000844 Self.TryImplicitConversion(SrcExpr, DestType,
845 /*SuppressUserConversions=*/false,
Anders Carlssonf2bc7c32009-08-28 16:22:20 +0000846 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +0000847 /*ForceRValue=*/false,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000848 /*InOverloadResolution=*/false,
849 /*one of user provided casts*/true);
Mike Stump11289f42009-09-09 15:08:12 +0000850
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000851 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
852 return TC_NotApplicable;
853
Sebastian Redl7c353682009-11-14 21:15:49 +0000854 // The conversion is possible, so commit to it.
855 msg = 0;
856 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, "casting",
857 /*IgnoreBaseAccess*/CStyle) ?
858 TC_Failed : TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000859}
860
861/// TryConstCast - See if a const_cast from source to destination is allowed,
862/// and perform it if it is.
863static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
864 bool CStyle, unsigned &msg) {
865 DestType = Self.Context.getCanonicalType(DestType);
866 QualType SrcType = SrcExpr->getType();
867 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000868 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000869 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
870 // Cannot const_cast non-lvalue to lvalue reference type. But if this
871 // is C-style, static_cast might find a way, so we simply suggest a
872 // message and tell the parent to keep searching.
873 msg = diag::err_bad_cxx_cast_rvalue;
874 return TC_NotApplicable;
875 }
876
877 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
878 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
879 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
880 SrcType = Self.Context.getPointerType(SrcType);
881 }
882
883 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
884 // the rules for const_cast are the same as those used for pointers.
885
886 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
887 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
888 // was a reference type, we converted it to a pointer above.
889 // The status of rvalue references isn't entirely clear, but it looks like
890 // conversion to them is simply invalid.
891 // C++ 5.2.11p3: For two pointer types [...]
892 if (!CStyle)
893 msg = diag::err_bad_const_cast_dest;
894 return TC_NotApplicable;
895 }
896 if (DestType->isFunctionPointerType() ||
897 DestType->isMemberFunctionPointerType()) {
898 // Cannot cast direct function pointers.
899 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
900 // T is the ultimate pointee of source and target type.
901 if (!CStyle)
902 msg = diag::err_bad_const_cast_dest;
903 return TC_NotApplicable;
904 }
905 SrcType = Self.Context.getCanonicalType(SrcType);
906
907 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
908 // completely equal.
909 // FIXME: const_cast should probably not be able to convert between pointers
910 // to different address spaces.
911 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
912 // in multi-level pointers may change, but the level count must be the same,
913 // as must be the final pointee type.
914 while (SrcType != DestType &&
915 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
916 SrcType = SrcType.getUnqualifiedType();
917 DestType = DestType.getUnqualifiedType();
918 }
919
920 // Since we're dealing in canonical types, the remainder must be the same.
921 if (SrcType != DestType)
922 return TC_NotApplicable;
923
924 return TC_Success;
925}
926
927static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
928 QualType DestType, bool CStyle,
929 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000930 unsigned &msg,
931 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000932 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
933
934 DestType = Self.Context.getCanonicalType(DestType);
935 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000936 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000937 bool LValue = DestTypeTmp->isLValueReferenceType();
938 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
939 // Cannot cast non-lvalue to reference type. See the similar comment in
940 // const_cast.
941 msg = diag::err_bad_cxx_cast_rvalue;
942 return TC_NotApplicable;
943 }
944
945 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
946 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
947 // built-in & and * operators.
948 // This code does this transformation for the checked types.
949 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
950 SrcType = Self.Context.getPointerType(SrcType);
951 }
952
953 // Canonicalize source for comparison.
954 SrcType = Self.Context.getCanonicalType(SrcType);
955
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000956 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
957 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000958 if (DestMemPtr && SrcMemPtr) {
959 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
960 // can be explicitly converted to an rvalue of type "pointer to member
961 // of Y of type T2" if T1 and T2 are both function types or both object
962 // types.
963 if (DestMemPtr->getPointeeType()->isFunctionType() !=
964 SrcMemPtr->getPointeeType()->isFunctionType())
965 return TC_NotApplicable;
966
967 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
968 // constness.
969 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
970 // we accept it.
971 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
972 msg = diag::err_bad_cxx_cast_const_away;
973 return TC_Failed;
974 }
975
976 // A valid member pointer cast.
Anders Carlsson9500ad12009-10-18 20:31:03 +0000977 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000978 return TC_Success;
979 }
980
981 // See below for the enumeral issue.
982 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
983 !DestType->isEnumeralType()) {
984 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
985 // type large enough to hold it. A value of std::nullptr_t can be
986 // converted to an integral type; the conversion has the same meaning
987 // and validity as a conversion of (void*)0 to the integral type.
988 if (Self.Context.getTypeSize(SrcType) >
989 Self.Context.getTypeSize(DestType)) {
990 msg = diag::err_bad_reinterpret_cast_small_int;
991 return TC_Failed;
992 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000993 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 return TC_Success;
995 }
996
Anders Carlsson570af5d2009-09-16 19:19:43 +0000997 bool destIsVector = DestType->isVectorType();
998 bool srcIsVector = SrcType->isVectorType();
999 if (srcIsVector || destIsVector) {
1000 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1001 bool destIsScalar =
1002 DestType->isIntegralType() && !DestType->isEnumeralType();
1003
1004 // Check if this is a cast between a vector and something else.
1005 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1006 !(srcIsVector && destIsVector))
1007 return TC_NotApplicable;
1008
1009 // If both types have the same size, we can successfully cast.
1010 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
1011 return TC_Success;
1012
1013 if (destIsScalar)
1014 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1015 else if (srcIsScalar)
1016 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1017 else
1018 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1019
1020 return TC_Failed;
1021 }
1022
Sebastian Redl9f831db2009-07-25 15:41:38 +00001023 bool destIsPtr = DestType->isPointerType();
1024 bool srcIsPtr = SrcType->isPointerType();
1025 if (!destIsPtr && !srcIsPtr) {
1026 // Except for std::nullptr_t->integer and lvalue->reference, which are
1027 // handled above, at least one of the two arguments must be a pointer.
1028 return TC_NotApplicable;
1029 }
1030
1031 if (SrcType == DestType) {
1032 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1033 // restrictions, a cast to the same type is allowed. The intent is not
1034 // entirely clear here, since all other paragraphs explicitly forbid casts
1035 // to the same type. However, the behavior of compilers is pretty consistent
1036 // on this point: allow same-type conversion if the involved types are
1037 // pointers, disallow otherwise.
1038 return TC_Success;
1039 }
1040
1041 // Note: Clang treats enumeration types as integral types. If this is ever
1042 // changed for C++, the additional check here will be redundant.
1043 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1044 assert(srcIsPtr && "One type must be a pointer");
1045 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1046 // type large enough to hold it.
1047 if (Self.Context.getTypeSize(SrcType) >
1048 Self.Context.getTypeSize(DestType)) {
1049 msg = diag::err_bad_reinterpret_cast_small_int;
1050 return TC_Failed;
1051 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001052 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001053 return TC_Success;
1054 }
1055
1056 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1057 assert(destIsPtr && "One type must be a pointer");
1058 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1059 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001060 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001061 return TC_Success;
1062 }
1063
1064 if (!destIsPtr || !srcIsPtr) {
1065 // With the valid non-pointer conversions out of the way, we can be even
1066 // more stringent.
1067 return TC_NotApplicable;
1068 }
1069
1070 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1071 // The C-style cast operator can.
1072 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1073 msg = diag::err_bad_cxx_cast_const_away;
1074 return TC_Failed;
1075 }
1076
1077 // Not casting away constness, so the only remaining check is for compatible
1078 // pointer categories.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001079 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001080
1081 if (SrcType->isFunctionPointerType()) {
1082 if (DestType->isFunctionPointerType()) {
1083 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1084 // a pointer to a function of a different type.
1085 return TC_Success;
1086 }
1087
1088 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1089 // an object type or vice versa is conditionally-supported.
1090 // Compilers support it in C++03 too, though, because it's necessary for
1091 // casting the return value of dlsym() and GetProcAddress().
1092 // FIXME: Conditionally-supported behavior should be configurable in the
1093 // TargetInfo or similar.
1094 if (!Self.getLangOptions().CPlusPlus0x)
1095 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1096 return TC_Success;
1097 }
1098
1099 if (DestType->isFunctionPointerType()) {
1100 // See above.
1101 if (!Self.getLangOptions().CPlusPlus0x)
1102 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1103 return TC_Success;
1104 }
1105
1106 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1107 // a pointer to an object of different type.
1108 // Void pointers are not specified, but supported by every compiler out there.
1109 // So we finish by allowing everything that remains - it's got to be two
1110 // object pointers.
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001111 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001112 return TC_Success;
1113}
1114
Sebastian Redl955a0672009-07-29 13:50:23 +00001115bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001116 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump11289f42009-09-09 15:08:12 +00001117 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001118 // This test is outside everything else because it's the only case where
1119 // a non-lvalue-reference target type does not lead to decay.
1120 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001121 if (CastTy->isVoidType()) {
1122 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001123 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001124 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001125
1126 // If the type is dependent, we won't do any other semantic analysis now.
1127 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1128 return false;
1129
Douglas Gregorad8b2222009-11-06 01:14:41 +00001130 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001131 DefaultFunctionArrayConversion(CastExpr);
1132
1133 // C++ [expr.cast]p5: The conversions performed by
1134 // - a const_cast,
1135 // - a static_cast,
1136 // - a static_cast followed by a const_cast,
1137 // - a reinterpret_cast, or
1138 // - a reinterpret_cast followed by a const_cast,
1139 // can be performed using the cast notation of explicit type conversion.
1140 // [...] If a conversion can be interpreted in more than one of the ways
1141 // listed above, the interpretation that appears first in the list is used,
1142 // even if a cast resulting from that interpretation is ill-formed.
1143 // In plain language, this means trying a const_cast ...
1144 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001145 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1146 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001147 if (tcr == TC_Success)
1148 Kind = CastExpr::CK_NoOp;
1149
Sebastian Redl9f831db2009-07-25 15:41:38 +00001150 if (tcr == TC_NotApplicable) {
1151 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001152 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1153 Kind, ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001154 if (tcr == TC_NotApplicable) {
1155 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001156 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1157 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001158 }
1159 }
1160
Sebastian Redl9f831db2009-07-25 15:41:38 +00001161 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001162 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001163 << CastExpr->getType() << CastTy << R;
1164
1165 return tcr != TC_Success;
1166}