blob: 9f5c5e58708f63fb6e05953e42d2d9496f7f3a0c [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"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000018#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000019#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000020using namespace clang;
21
Sebastian Redl37d6de32008-11-08 13:00:26 +000022enum TryStaticCastResult {
23 TSC_NotApplicable, ///< The cast method is not applicable.
24 TSC_Success, ///< The cast method is appropriate and successful.
25 TSC_Failed ///< The cast method is appropriate, but failed. A
26 ///< diagnostic has been emitted.
27};
28
29static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
30 const SourceRange &OpRange,
31 const SourceRange &DestRange);
32static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
33 const SourceRange &OpRange,
34 const SourceRange &DestRange);
35static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
36 const SourceRange &OpRange);
37static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
38 const SourceRange &OpRange,
39 const SourceRange &DestRange);
40
41static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
42static TryStaticCastResult TryStaticReferenceDowncast(
43 Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
44static TryStaticCastResult TryStaticPointerDowncast(
45 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
Sebastian Redl21593ac2009-01-28 18:33:18 +000046static TryStaticCastResult TryStaticMemberPointerUpcast(
47 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
Sebastian Redl37d6de32008-11-08 13:00:26 +000048static TryStaticCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
49 QualType DestType,
50 const SourceRange &OpRange,
51 QualType OrigSrcType,
52 QualType OrigDestType);
53static TryStaticCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
54 QualType DestType,
55 const SourceRange &OpRange);
56
Sebastian Redl26d85b12008-11-05 21:50:06 +000057/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +000058Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +000059Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
60 SourceLocation LAngleBracketLoc, TypeTy *Ty,
61 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +000062 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +000063 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 Expr *Ex = (Expr*)E.release();
Sebastian Redl26d85b12008-11-05 21:50:06 +000065 QualType DestType = QualType::getFromOpaquePtr(Ty);
66 SourceRange OpRange(OpLoc, RParenLoc);
67 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
68
Douglas Gregor9103bb22008-12-17 22:52:20 +000069 // If the type is dependent, we won't do the semantic analysis now.
70 // FIXME: should we check this in a more fine-grained manner?
71 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
72
Sebastian Redl26d85b12008-11-05 21:50:06 +000073 switch (Kind) {
74 default: assert(0 && "Unknown C++ cast!");
75
76 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000077 if (!TypeDependent)
78 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000079 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
80 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +000081
82 case tok::kw_dynamic_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000083 if (!TypeDependent)
84 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000085 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
86 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +000087
88 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000089 if (!TypeDependent)
90 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000091 return Owned(new (Context) CXXReinterpretCastExpr(
92 DestType.getNonReferenceType(),
93 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +000094
95 case tok::kw_static_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000096 if (!TypeDependent)
97 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000098 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
99 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000100 }
101
Sebastian Redlf53597f2009-03-15 17:47:39 +0000102 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000103}
104
105/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
106/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
107/// like this:
108/// const char *str = "literal";
109/// legacy_function(const_cast\<char*\>(str));
110void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000111CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
112 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113{
114 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
115
Sebastian Redl37d6de32008-11-08 13:00:26 +0000116 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000117 QualType SrcType = SrcExpr->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000118 if (const LValueReferenceType *DestTypeTmp =
119 DestType->getAsLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000120 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000121 // Cannot cast non-lvalue to lvalue reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000122 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000123 << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000124 return;
125 }
126
127 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
128 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000129 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
130 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000131 } else {
132 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
133 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
134 // conversions are performed on the expression.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000135 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000136 SrcType = SrcExpr->getType();
137 }
138
Sebastian Redlf20269b2009-01-26 22:19:12 +0000139 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
140 // the rules for const_cast are the same as those used for pointers.
141
142 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000143 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
144 // was a reference type, we converted it to a pointer above.
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000145 // The status of rvalue references isn't entirely clear, but it looks like
146 // conversion to them is simply invalid.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000147 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000148 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000149 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000150 return;
151 }
Sebastian Redlf20269b2009-01-26 22:19:12 +0000152 if (DestType->isFunctionPointerType() ||
153 DestType->isMemberFunctionPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000154 // Cannot cast direct function pointers.
155 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
156 // T is the ultimate pointee of source and target type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000157 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000158 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000159 return;
160 }
Sebastian Redl37d6de32008-11-08 13:00:26 +0000161 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000162
163 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
164 // completely equal.
165 // FIXME: const_cast should probably not be able to convert between pointers
166 // to different address spaces.
167 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
168 // in multi-level pointers may change, but the level count must be the same,
169 // as must be the final pointee type.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000170 while (SrcType != DestType &&
171 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000172 SrcType = SrcType.getUnqualifiedType();
173 DestType = DestType.getUnqualifiedType();
174 }
175
176 // Doug Gregor said to disallow this until users complain.
177#if 0
178 // If we end up with constant arrays of equal size, unwrap those too. A cast
179 // from const int [N] to int (&)[N] is invalid by my reading of the
180 // standard, but g++ accepts it even with -ansi -pedantic.
181 // No more than one level, though, so don't embed this in the unwrap loop
182 // above.
183 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redl37d6de32008-11-08 13:00:26 +0000184 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
185 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000186 {
187 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
188 // Different array sizes.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000189 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000190 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000191 return;
192 }
193 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
194 DestType = DestTypeArr->getElementType().getUnqualifiedType();
195 }
196#endif
197
198 // Since we're dealing in canonical types, the remainder must be the same.
199 if (SrcType != DestType) {
200 // Cast between unrelated types.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000201 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000202 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000203 return;
204 }
205}
206
207/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
208/// valid.
209/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
210/// like this:
211/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
212void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000213CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
214 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215{
216 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
217
Sebastian Redl37d6de32008-11-08 13:00:26 +0000218 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000219 QualType SrcType = SrcExpr->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000220 if (const LValueReferenceType *DestTypeTmp =
221 DestType->getAsLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000222 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000223 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000224 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000225 << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000226 return;
227 }
228
229 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
230 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
231 // built-in & and * operators.
232 // This code does this transformation for the checked types.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000233 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
234 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000235 } else if (const RValueReferenceType *DestTypeTmp =
236 DestType->getAsRValueReferenceType()) {
237 // Both the reference conversion and the rvalue rules apply.
238 Self.DefaultFunctionArrayConversion(SrcExpr);
239 SrcType = SrcExpr->getType();
240
241 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
242 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000243 } else {
244 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
245 // function-to-pointer standard conversions are performed on the
246 // expression v.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000247 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000248 SrcType = SrcExpr->getType();
249 }
250
251 // Canonicalize source for comparison.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000252 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000253
Sebastian Redldb647282009-01-27 23:18:31 +0000254 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType(),
255 *SrcMemPtr = SrcType->getAsMemberPointerType();
256 if (DestMemPtr && SrcMemPtr) {
257 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
258 // can be explicitly converted to an rvalue of type "pointer to member
259 // of Y of type T2" if T1 and T2 are both function types or both object
260 // types.
261 if (DestMemPtr->getPointeeType()->isFunctionType() !=
262 SrcMemPtr->getPointeeType()->isFunctionType()) {
263 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
264 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
265 return;
266 }
267
268 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
269 // constness.
270 if (CastsAwayConstness(Self, SrcType, DestType)) {
271 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
272 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
273 return;
274 }
275
276 // A valid member pointer cast.
277 return;
278 }
279
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280 bool destIsPtr = DestType->isPointerType();
281 bool srcIsPtr = SrcType->isPointerType();
282 if (!destIsPtr && !srcIsPtr) {
283 // Except for std::nullptr_t->integer, which is not supported yet, and
284 // lvalue->reference, which is handled above, at least one of the two
285 // arguments must be a pointer.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000286 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000287 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000288 return;
289 }
290
291 if (SrcType == DestType) {
292 // C++ 5.2.10p2 has a note that mentions that, subject to all other
293 // restrictions, a cast to the same type is allowed. The intent is not
294 // entirely clear here, since all other paragraphs explicitly forbid casts
295 // to the same type. However, the behavior of compilers is pretty consistent
Sebastian Redldb647282009-01-27 23:18:31 +0000296 // on this point: allow same-type conversion if the involved types are
297 // pointers, disallow otherwise.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000298 return;
299 }
300
301 // Note: Clang treats enumeration types as integral types. If this is ever
302 // changed for C++, the additional check here will be redundant.
303 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000304 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000305 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
306 // type large enough to hold it.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000307 if (Self.Context.getTypeSize(SrcType) >
308 Self.Context.getTypeSize(DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000309 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattnerd1625842008-11-24 06:25:27 +0000310 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000311 }
312 return;
313 }
314
315 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000316 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000317 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
318 // converted to a pointer.
319 return;
320 }
321
322 if (!destIsPtr || !srcIsPtr) {
323 // With the valid non-pointer conversions out of the way, we can be even
324 // more stringent.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000325 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000326 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000327 return;
328 }
329
330 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000331 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000332 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000333 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000334 return;
335 }
336
337 // Not casting away constness, so the only remaining check is for compatible
338 // pointer categories.
339
340 if (SrcType->isFunctionPointerType()) {
341 if (DestType->isFunctionPointerType()) {
342 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
343 // a pointer to a function of a different type.
344 return;
345 }
346
Sebastian Redl26d85b12008-11-05 21:50:06 +0000347 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
348 // an object type or vice versa is conditionally-supported.
349 // Compilers support it in C++03 too, though, because it's necessary for
350 // casting the return value of dlsym() and GetProcAddress().
351 // FIXME: Conditionally-supported behavior should be configurable in the
352 // TargetInfo or similar.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000353 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000354 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
355 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000356 }
357 return;
358 }
359
Sebastian Redl26d85b12008-11-05 21:50:06 +0000360 if (DestType->isFunctionPointerType()) {
361 // See above.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000362 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000363 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
364 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000365 }
366 return;
367 }
368
369 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
370 // a pointer to an object of different type.
371 // Void pointers are not specified, but supported by every compiler out there.
372 // So we finish by allowing everything that remains - it's got to be two
373 // object pointers.
374}
375
Sebastian Redldb647282009-01-27 23:18:31 +0000376/// CastsAwayConstness - Check if the pointer conversion from SrcType to
377/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
378/// the cast checkers. Both arguments must denote pointer (possibly to member)
379/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000380bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000381CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000382{
Sebastian Redldb647282009-01-27 23:18:31 +0000383 // Casting away constness is defined in C++ 5.2.11p8 with reference to
384 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
385 // the rules are non-trivial. So first we construct Tcv *...cv* as described
386 // in C++ 5.2.11p8.
387 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
388 "Source type is not pointer or pointer to member.");
389 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
390 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000391
392 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
393 llvm::SmallVector<unsigned, 8> cv1, cv2;
394
395 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000396 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000397 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
398 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
399 }
400 assert(cv1.size() > 0 && "Must have at least one pointer level.");
401
402 // Construct void pointers with those qualifiers (in reverse order of
403 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000404 QualType SrcConstruct = Self.Context.VoidTy;
405 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000406 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
407 i2 = cv2.rbegin();
408 i1 != cv1.rend(); ++i1, ++i2)
409 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000410 SrcConstruct = Self.Context.getPointerType(
411 SrcConstruct.getQualifiedType(*i1));
412 DestConstruct = Self.Context.getPointerType(
413 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000414 }
415
416 // Test if they're compatible.
417 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000418 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000419}
420
421/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
422/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
423/// implicit conversions explicit and getting rid of data loss warnings.
424void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000425CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
426 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000427{
428 // The order the tests is not entirely arbitrary. There is one conversion
429 // that can be handled in two different ways. Given:
430 // struct A {};
431 // struct B : public A {
432 // B(); B(const A&);
433 // };
434 // const A &a = B();
435 // the cast static_cast<const B&>(a) could be seen as either a static
436 // reference downcast, or an explicit invocation of the user-defined
437 // conversion using B's conversion constructor.
438 // DR 427 specifies that the downcast is to be applied here.
439
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000440 // FIXME: With N2812, casts to rvalue refs will change.
441
Sebastian Redl26d85b12008-11-05 21:50:06 +0000442 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
443 if (DestType->isVoidType()) {
444 return;
445 }
446
447 // C++ 5.2.9p5, reference downcast.
448 // See the function for details.
449 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000450 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000451 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000452 return;
453 }
454
455 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
456 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000457 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
458 TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000459 return;
460 }
461
462 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
463 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
464 // conversions, subject to further restrictions.
465 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
466 // of qualification conversions impossible.
467
468 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
469 // are applied to the expression.
470 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000471 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000472
Sebastian Redl37d6de32008-11-08 13:00:26 +0000473 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000474
475 // Reverse integral promotion/conversion. All such conversions are themselves
476 // again integral promotions or conversions and are thus already handled by
477 // p2 (TryDirectInitialization above).
478 // (Note: any data loss warnings should be suppressed.)
479 // The exception is the reverse of enum->integer, i.e. integer->enum (and
480 // enum->enum). See also C++ 5.2.9p7.
481 // The same goes for reverse floating point promotion/conversion and
482 // floating-integral conversions. Again, only floating->enum is relevant.
483 if (DestType->isEnumeralType()) {
484 if (SrcType->isComplexType() || SrcType->isVectorType()) {
485 // Fall through - these cannot be converted.
486 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
487 return;
488 }
489 }
490
491 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
492 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000493 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000494 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000495 return;
496 }
497
Sebastian Redl21593ac2009-01-28 18:33:18 +0000498 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
Sebastian Redl26d85b12008-11-05 21:50:06 +0000499 // conversion. C++ 5.2.9p9 has additional information.
500 // DR54's access restrictions apply here also.
Sebastian Redl21593ac2009-01-28 18:33:18 +0000501 if (TryStaticMemberPointerUpcast(Self, SrcType, DestType, OpRange)
502 > TSC_NotApplicable) {
503 return;
504 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000505
506 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
507 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
508 // just the usual constness stuff.
509 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
510 QualType SrcPointee = SrcPointer->getPointeeType();
511 if (SrcPointee->isVoidType()) {
512 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
513 QualType DestPointee = DestPointer->getPointeeType();
514 if (DestPointee->isObjectType()) {
515 // This is definitely the intended conversion, but it might fail due
516 // to a const violation.
517 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000518 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000519 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000520 }
521 return;
522 }
523 }
524 }
525 }
526
527 // We tried everything. Everything! Nothing works! :-(
528 // FIXME: Error reporting could be a lot better. Should store the reason
529 // why every substep failed and, at the end, select the most specific and
530 // report that.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000531 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000532 << "static_cast" << DestType << OrigSrcType
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000533 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000534}
535
536/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000537TryStaticCastResult
538TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
539 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000540{
541 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
542 // cast to type "reference to cv2 D", where D is a class derived from B,
543 // if a valid standard conversion from "pointer to D" to "pointer to B"
544 // exists, cv2 >= cv1, and B is not a virtual base class of D.
545 // In addition, DR54 clarifies that the base must be accessible in the
546 // current context. Although the wording of DR54 only applies to the pointer
547 // variant of this rule, the intent is clearly for it to apply to the this
548 // conversion as well.
549
Sebastian Redl37d6de32008-11-08 13:00:26 +0000550 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000551 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000552 }
553
554 const ReferenceType *DestReference = DestType->getAsReferenceType();
555 if (!DestReference) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000556 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000557 }
558 QualType DestPointee = DestReference->getPointeeType();
559
Sebastian Redl37d6de32008-11-08 13:00:26 +0000560 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000561 SrcExpr->getType(), DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000562}
563
564/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000565TryStaticCastResult
566TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
567 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000568{
569 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
570 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
571 // is a class derived from B, if a valid standard conversion from "pointer
572 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
573 // class of D.
574 // In addition, DR54 clarifies that the base must be accessible in the
575 // current context.
576
577 const PointerType *SrcPointer = SrcType->getAsPointerType();
578 if (!SrcPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000579 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000580 }
581
582 const PointerType *DestPointer = DestType->getAsPointerType();
583 if (!DestPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000584 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000585 }
586
Sebastian Redl37d6de32008-11-08 13:00:26 +0000587 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000588 DestPointer->getPointeeType(),
589 OpRange, SrcType, DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000590}
591
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000592/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
593/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl26d85b12008-11-05 21:50:06 +0000594/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000595TryStaticCastResult
596TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
597 const SourceRange &OpRange, QualType OrigSrcType,
598 QualType OrigDestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000599{
600 // Downcast can only happen in class hierarchies, so we need classes.
601 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000602 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000603 }
604
605 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
606 /*DetectVirtual=*/true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000607 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000608 return TSC_NotApplicable;
609 }
610
611 // Target type does derive from source type. Now we're serious. If an error
612 // appears now, it's not ignored.
613 // This may not be entirely in line with the standard. Take for example:
614 // struct A {};
615 // struct B : virtual A {
616 // B(A&);
617 // };
618 //
619 // void f()
620 // {
621 // (void)static_cast<const B&>(*((A*)0));
622 // }
623 // As far as the standard is concerned, p5 does not apply (A is virtual), so
624 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
625 // However, both GCC and Comeau reject this example, and accepting it would
626 // mean more complex code if we're to preserve the nice error message.
627 // FIXME: Being 100% compliant here would be nice to have.
628
629 // Must preserve cv, as always.
630 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000631 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000632 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000633 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000634 }
635
636 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000637 // This code is analoguous to that in CheckDerivedToBaseConversion, except
638 // that it builds the paths in reverse order.
639 // To sum up: record all paths to the base and build a nice string from
640 // them. Use it to spice up the error message.
641 Paths.clear();
642 Paths.setRecordingPaths(true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000643 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000644 std::string PathDisplayStr;
645 std::set<unsigned> DisplayedPaths;
646 for (BasePaths::paths_iterator Path = Paths.begin();
647 Path != Paths.end(); ++Path) {
648 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
649 // We haven't displayed a path to this particular base
650 // class subobject yet.
651 PathDisplayStr += "\n ";
652 for (BasePath::const_reverse_iterator Element = Path->rbegin();
653 Element != Path->rend(); ++Element)
654 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
655 PathDisplayStr += DestType.getAsString();
656 }
657 }
658
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000659 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattnerd1625842008-11-24 06:25:27 +0000660 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000661 << PathDisplayStr << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000662 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000663 }
664
665 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000666 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000667 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattnerd1625842008-11-24 06:25:27 +0000668 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000669 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000670 }
671
672 // FIXME: Test accessibility.
673
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000674 return TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000675}
676
Sebastian Redl21593ac2009-01-28 18:33:18 +0000677/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
678/// C++ 5.2.9p9 is valid:
679///
680/// An rvalue of type "pointer to member of D of type cv1 T" can be
681/// converted to an rvalue of type "pointer to member of B of type cv2 T",
682/// where B is a base class of D [...].
683///
684TryStaticCastResult
685TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
686 const SourceRange &OpRange)
687{
688 const MemberPointerType *SrcMemPtr = SrcType->getAsMemberPointerType();
689 if (!SrcMemPtr)
690 return TSC_NotApplicable;
691 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType();
692 if (!DestMemPtr)
693 return TSC_NotApplicable;
694
695 // T == T, modulo cv
696 if (Self.Context.getCanonicalType(
697 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
698 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
699 getUnqualifiedType()))
700 return TSC_NotApplicable;
701
702 // B base of D
703 QualType SrcClass(SrcMemPtr->getClass(), 0);
704 QualType DestClass(DestMemPtr->getClass(), 0);
705 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
706 /*DetectVirtual=*/true);
707 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
708 return TSC_NotApplicable;
709 }
710
711 // B is a base of D. But is it an allowed base? If not, it's a hard error.
712 if (Paths.isAmbiguous(DestClass)) {
713 Paths.clear();
714 Paths.setRecordingPaths(true);
715 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
716 assert(StillOkay);
717 StillOkay = StillOkay;
718 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
719 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
720 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
721 return TSC_Failed;
722 }
723
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000724 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +0000725 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
726 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
727 return TSC_Failed;
728 }
729
730 // FIXME: Test accessibility.
731
732 return TSC_Success;
733}
734
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000735/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
736/// is valid:
737///
738/// An expression e can be explicitly converted to a type T using a
739/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000740TryStaticCastResult
741TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
742 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000743{
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000744 if (DestType->isReferenceType()) {
745 // At this point of CheckStaticCast, if the destination is a reference,
746 // this has to work. There is no other way that works.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000747 return Self.CheckReferenceInit(SrcExpr, DestType) ?
748 TSC_Failed : TSC_Success;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000749 }
750 if (DestType->isRecordType()) {
751 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
752 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000753 }
754
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000755 // FIXME: To get a proper error from invalid conversions here, we need to
756 // reimplement more of this.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000757 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
758 SrcExpr, DestType);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000759 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
760 TSC_NotApplicable : TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000761}
762
763/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
764/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
765/// checked downcasts in class hierarchies.
766void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000767CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
768 const SourceRange &OpRange,
769 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000770{
771 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000772 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000773
774 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
775 // or "pointer to cv void".
776
777 QualType DestPointee;
778 const PointerType *DestPointer = DestType->getAsPointerType();
779 const ReferenceType *DestReference = DestType->getAsReferenceType();
780 if (DestPointer) {
781 DestPointee = DestPointer->getPointeeType();
782 } else if (DestReference) {
783 DestPointee = DestReference->getPointeeType();
784 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000785 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000786 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000787 return;
788 }
789
790 const RecordType *DestRecord = DestPointee->getAsRecordType();
791 if (DestPointee->isVoidType()) {
792 assert(DestPointer && "Reference to void is not possible");
793 } else if (DestRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000794 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000795 diag::err_bad_dynamic_cast_incomplete,
796 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000797 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000798 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000799 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000800 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000801 return;
802 }
803
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000804 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
805 // complete class type, [...]. If T is an lvalue reference type, v shall be
806 // an lvalue of a complete class type, [...]. If T is an rvalue reference
807 // type, v shall be an expression having a complete effective class type,
808 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000809
Sebastian Redl37d6de32008-11-08 13:00:26 +0000810 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000811 QualType SrcPointee;
812 if (DestPointer) {
813 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
814 SrcPointee = SrcPointer->getPointeeType();
815 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000816 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000817 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000818 return;
819 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000820 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000821 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000822 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000823 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000824 }
825 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000826 } else {
827 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000828 }
829
830 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
831 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000832 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000833 diag::err_bad_dynamic_cast_incomplete,
834 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000835 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000836 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000837 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000838 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000839 return;
840 }
841
842 assert((DestPointer || DestReference) &&
843 "Bad destination non-ptr/ref slipped through.");
844 assert((DestRecord || DestPointee->isVoidType()) &&
845 "Bad destination pointee slipped through.");
846 assert(SrcRecord && "Bad source pointee slipped through.");
847
848 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
849 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000850 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000851 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000852 return;
853 }
854
855 // C++ 5.2.7p3: If the type of v is the same as the required result type,
856 // [except for cv].
857 if (DestRecord == SrcRecord) {
858 return;
859 }
860
861 // C++ 5.2.7p5
862 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000863 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
864 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000865 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000866 // Diagnostic already emitted on error.
867 return;
868 }
869
870 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000871 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000872 assert(SrcDecl && "Definition missing");
873 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000874 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000875 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000876 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000877
878 // Done. Everything else is run-time checks.
879}