blob: fbde930f0b57e7d4199a22d9725fe6aa369269e6 [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.
58Action::ExprResult
59Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
60 SourceLocation LAngleBracketLoc, TypeTy *Ty,
61 SourceLocation RAngleBracketLoc,
62 SourceLocation LParenLoc, ExprTy *E,
63 SourceLocation RParenLoc) {
64 Expr *Ex = (Expr*)E;
65 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);
Ted Kremenek8189cde2009-02-07 01:47:29 +000079 return new (Context) CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
80 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);
Ted Kremenek8189cde2009-02-07 01:47:29 +000085 return new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
86 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);
Ted Kremenek8189cde2009-02-07 01:47:29 +000091 return new (Context) CXXReinterpretCastExpr(DestType.getNonReferenceType(),
92 Ex, DestType, OpLoc);
Sebastian Redl26d85b12008-11-05 21:50:06 +000093
94 case tok::kw_static_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000095 if (!TypeDependent)
96 CheckStaticCast(*this, Ex, DestType, OpRange);
Ted Kremenek8189cde2009-02-07 01:47:29 +000097 return new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
98 DestType, OpLoc);
Sebastian Redl26d85b12008-11-05 21:50:06 +000099 }
100
101 return true;
102}
103
104/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
105/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
106/// like this:
107/// const char *str = "literal";
108/// legacy_function(const_cast\<char*\>(str));
109void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000110CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
111 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000112{
113 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
114
Sebastian Redl37d6de32008-11-08 13:00:26 +0000115 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000116 QualType SrcType = SrcExpr->getType();
117 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000118 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000119 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000120 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000121 << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000122 return;
123 }
124
125 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
126 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000127 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
128 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000129 } else {
130 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
131 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
132 // conversions are performed on the expression.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000133 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000134 SrcType = SrcExpr->getType();
135 }
136
Sebastian Redlf20269b2009-01-26 22:19:12 +0000137 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
138 // the rules for const_cast are the same as those used for pointers.
139
140 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000141 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
142 // was a reference type, we converted it to a pointer above.
143 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000144 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000145 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000146 return;
147 }
Sebastian Redlf20269b2009-01-26 22:19:12 +0000148 if (DestType->isFunctionPointerType() ||
149 DestType->isMemberFunctionPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000150 // Cannot cast direct function pointers.
151 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
152 // T is the ultimate pointee of source and target type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000153 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000154 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000155 return;
156 }
Sebastian Redl37d6de32008-11-08 13:00:26 +0000157 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000158
159 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
160 // completely equal.
161 // FIXME: const_cast should probably not be able to convert between pointers
162 // to different address spaces.
163 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
164 // in multi-level pointers may change, but the level count must be the same,
165 // as must be the final pointee type.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000166 while (SrcType != DestType &&
167 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000168 SrcType = SrcType.getUnqualifiedType();
169 DestType = DestType.getUnqualifiedType();
170 }
171
172 // Doug Gregor said to disallow this until users complain.
173#if 0
174 // If we end up with constant arrays of equal size, unwrap those too. A cast
175 // from const int [N] to int (&)[N] is invalid by my reading of the
176 // standard, but g++ accepts it even with -ansi -pedantic.
177 // No more than one level, though, so don't embed this in the unwrap loop
178 // above.
179 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redl37d6de32008-11-08 13:00:26 +0000180 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
181 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000182 {
183 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
184 // Different array sizes.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000185 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000186 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000187 return;
188 }
189 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
190 DestType = DestTypeArr->getElementType().getUnqualifiedType();
191 }
192#endif
193
194 // Since we're dealing in canonical types, the remainder must be the same.
195 if (SrcType != DestType) {
196 // Cast between unrelated types.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000197 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000198 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000199 return;
200 }
201}
202
203/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
204/// valid.
205/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
206/// like this:
207/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
208void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000209CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
210 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000211{
212 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
213
Sebastian Redl37d6de32008-11-08 13:00:26 +0000214 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215 QualType SrcType = SrcExpr->getType();
216 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000217 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000218 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000219 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000220 << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000221 return;
222 }
223
224 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
225 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
226 // built-in & and * operators.
227 // This code does this transformation for the checked types.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000228 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
229 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000230 } else {
231 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
232 // function-to-pointer standard conversions are performed on the
233 // expression v.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000234 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000235 SrcType = SrcExpr->getType();
236 }
237
238 // Canonicalize source for comparison.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000239 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000240
Sebastian Redldb647282009-01-27 23:18:31 +0000241 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType(),
242 *SrcMemPtr = SrcType->getAsMemberPointerType();
243 if (DestMemPtr && SrcMemPtr) {
244 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
245 // can be explicitly converted to an rvalue of type "pointer to member
246 // of Y of type T2" if T1 and T2 are both function types or both object
247 // types.
248 if (DestMemPtr->getPointeeType()->isFunctionType() !=
249 SrcMemPtr->getPointeeType()->isFunctionType()) {
250 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
251 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
252 return;
253 }
254
255 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
256 // constness.
257 if (CastsAwayConstness(Self, SrcType, DestType)) {
258 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
259 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
260 return;
261 }
262
263 // A valid member pointer cast.
264 return;
265 }
266
Sebastian Redl26d85b12008-11-05 21:50:06 +0000267 bool destIsPtr = DestType->isPointerType();
268 bool srcIsPtr = SrcType->isPointerType();
269 if (!destIsPtr && !srcIsPtr) {
270 // Except for std::nullptr_t->integer, which is not supported yet, and
271 // lvalue->reference, which is handled above, at least one of the two
272 // arguments must be a pointer.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000273 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000274 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000275 return;
276 }
277
278 if (SrcType == DestType) {
279 // C++ 5.2.10p2 has a note that mentions that, subject to all other
280 // restrictions, a cast to the same type is allowed. The intent is not
281 // entirely clear here, since all other paragraphs explicitly forbid casts
282 // to the same type. However, the behavior of compilers is pretty consistent
Sebastian Redldb647282009-01-27 23:18:31 +0000283 // on this point: allow same-type conversion if the involved types are
284 // pointers, disallow otherwise.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000285 return;
286 }
287
288 // Note: Clang treats enumeration types as integral types. If this is ever
289 // changed for C++, the additional check here will be redundant.
290 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000291 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000292 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
293 // type large enough to hold it.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000294 if (Self.Context.getTypeSize(SrcType) >
295 Self.Context.getTypeSize(DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000296 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattnerd1625842008-11-24 06:25:27 +0000297 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000298 }
299 return;
300 }
301
302 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000303 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000304 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
305 // converted to a pointer.
306 return;
307 }
308
309 if (!destIsPtr || !srcIsPtr) {
310 // With the valid non-pointer conversions out of the way, we can be even
311 // more stringent.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000312 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000313 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000314 return;
315 }
316
317 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000318 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000319 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000320 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 return;
322 }
323
324 // Not casting away constness, so the only remaining check is for compatible
325 // pointer categories.
326
327 if (SrcType->isFunctionPointerType()) {
328 if (DestType->isFunctionPointerType()) {
329 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
330 // a pointer to a function of a different type.
331 return;
332 }
333
Sebastian Redl26d85b12008-11-05 21:50:06 +0000334 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
335 // an object type or vice versa is conditionally-supported.
336 // Compilers support it in C++03 too, though, because it's necessary for
337 // casting the return value of dlsym() and GetProcAddress().
338 // FIXME: Conditionally-supported behavior should be configurable in the
339 // TargetInfo or similar.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000340 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000341 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
342 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000343 }
344 return;
345 }
346
Sebastian Redl26d85b12008-11-05 21:50:06 +0000347 if (DestType->isFunctionPointerType()) {
348 // See above.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000349 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000350 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
351 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000352 }
353 return;
354 }
355
356 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
357 // a pointer to an object of different type.
358 // Void pointers are not specified, but supported by every compiler out there.
359 // So we finish by allowing everything that remains - it's got to be two
360 // object pointers.
361}
362
Sebastian Redldb647282009-01-27 23:18:31 +0000363/// CastsAwayConstness - Check if the pointer conversion from SrcType to
364/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
365/// the cast checkers. Both arguments must denote pointer (possibly to member)
366/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000367bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000368CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000369{
Sebastian Redldb647282009-01-27 23:18:31 +0000370 // Casting away constness is defined in C++ 5.2.11p8 with reference to
371 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
372 // the rules are non-trivial. So first we construct Tcv *...cv* as described
373 // in C++ 5.2.11p8.
374 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
375 "Source type is not pointer or pointer to member.");
376 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
377 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000378
379 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
380 llvm::SmallVector<unsigned, 8> cv1, cv2;
381
382 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000383 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000384 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
385 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
386 }
387 assert(cv1.size() > 0 && "Must have at least one pointer level.");
388
389 // Construct void pointers with those qualifiers (in reverse order of
390 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000391 QualType SrcConstruct = Self.Context.VoidTy;
392 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000393 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
394 i2 = cv2.rbegin();
395 i1 != cv1.rend(); ++i1, ++i2)
396 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000397 SrcConstruct = Self.Context.getPointerType(
398 SrcConstruct.getQualifiedType(*i1));
399 DestConstruct = Self.Context.getPointerType(
400 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000401 }
402
403 // Test if they're compatible.
404 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000405 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000406}
407
408/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
409/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
410/// implicit conversions explicit and getting rid of data loss warnings.
411void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000412CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
413 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000414{
415 // The order the tests is not entirely arbitrary. There is one conversion
416 // that can be handled in two different ways. Given:
417 // struct A {};
418 // struct B : public A {
419 // B(); B(const A&);
420 // };
421 // const A &a = B();
422 // the cast static_cast<const B&>(a) could be seen as either a static
423 // reference downcast, or an explicit invocation of the user-defined
424 // conversion using B's conversion constructor.
425 // DR 427 specifies that the downcast is to be applied here.
426
427 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
428 if (DestType->isVoidType()) {
429 return;
430 }
431
432 // C++ 5.2.9p5, reference downcast.
433 // See the function for details.
434 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000435 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000436 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000437 return;
438 }
439
440 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
441 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000442 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
443 TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000444 return;
445 }
446
447 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
448 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
449 // conversions, subject to further restrictions.
450 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
451 // of qualification conversions impossible.
452
453 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
454 // are applied to the expression.
455 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000456 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000457
Sebastian Redl37d6de32008-11-08 13:00:26 +0000458 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000459
460 // Reverse integral promotion/conversion. All such conversions are themselves
461 // again integral promotions or conversions and are thus already handled by
462 // p2 (TryDirectInitialization above).
463 // (Note: any data loss warnings should be suppressed.)
464 // The exception is the reverse of enum->integer, i.e. integer->enum (and
465 // enum->enum). See also C++ 5.2.9p7.
466 // The same goes for reverse floating point promotion/conversion and
467 // floating-integral conversions. Again, only floating->enum is relevant.
468 if (DestType->isEnumeralType()) {
469 if (SrcType->isComplexType() || SrcType->isVectorType()) {
470 // Fall through - these cannot be converted.
471 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
472 return;
473 }
474 }
475
476 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
477 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000478 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000479 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000480 return;
481 }
482
Sebastian Redl21593ac2009-01-28 18:33:18 +0000483 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
Sebastian Redl26d85b12008-11-05 21:50:06 +0000484 // conversion. C++ 5.2.9p9 has additional information.
485 // DR54's access restrictions apply here also.
Sebastian Redl21593ac2009-01-28 18:33:18 +0000486 if (TryStaticMemberPointerUpcast(Self, SrcType, DestType, OpRange)
487 > TSC_NotApplicable) {
488 return;
489 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000490
491 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
492 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
493 // just the usual constness stuff.
494 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
495 QualType SrcPointee = SrcPointer->getPointeeType();
496 if (SrcPointee->isVoidType()) {
497 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
498 QualType DestPointee = DestPointer->getPointeeType();
499 if (DestPointee->isObjectType()) {
500 // This is definitely the intended conversion, but it might fail due
501 // to a const violation.
502 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000503 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000504 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000505 }
506 return;
507 }
508 }
509 }
510 }
511
512 // We tried everything. Everything! Nothing works! :-(
513 // FIXME: Error reporting could be a lot better. Should store the reason
514 // why every substep failed and, at the end, select the most specific and
515 // report that.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000516 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000517 << "static_cast" << DestType << OrigSrcType
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000518 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000519}
520
521/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000522TryStaticCastResult
523TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
524 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000525{
526 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
527 // cast to type "reference to cv2 D", where D is a class derived from B,
528 // if a valid standard conversion from "pointer to D" to "pointer to B"
529 // exists, cv2 >= cv1, and B is not a virtual base class of D.
530 // In addition, DR54 clarifies that the base must be accessible in the
531 // current context. Although the wording of DR54 only applies to the pointer
532 // variant of this rule, the intent is clearly for it to apply to the this
533 // conversion as well.
534
Sebastian Redl37d6de32008-11-08 13:00:26 +0000535 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000536 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000537 }
538
539 const ReferenceType *DestReference = DestType->getAsReferenceType();
540 if (!DestReference) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000541 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000542 }
543 QualType DestPointee = DestReference->getPointeeType();
544
Sebastian Redl37d6de32008-11-08 13:00:26 +0000545 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000546 SrcExpr->getType(), DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000547}
548
549/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000550TryStaticCastResult
551TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
552 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000553{
554 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
555 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
556 // is a class derived from B, if a valid standard conversion from "pointer
557 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
558 // class of D.
559 // In addition, DR54 clarifies that the base must be accessible in the
560 // current context.
561
562 const PointerType *SrcPointer = SrcType->getAsPointerType();
563 if (!SrcPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000564 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000565 }
566
567 const PointerType *DestPointer = DestType->getAsPointerType();
568 if (!DestPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000569 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000570 }
571
Sebastian Redl37d6de32008-11-08 13:00:26 +0000572 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000573 DestPointer->getPointeeType(),
574 OpRange, SrcType, DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000575}
576
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000577/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
578/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl26d85b12008-11-05 21:50:06 +0000579/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000580TryStaticCastResult
581TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
582 const SourceRange &OpRange, QualType OrigSrcType,
583 QualType OrigDestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000584{
585 // Downcast can only happen in class hierarchies, so we need classes.
586 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000587 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000588 }
589
590 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
591 /*DetectVirtual=*/true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000592 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000593 return TSC_NotApplicable;
594 }
595
596 // Target type does derive from source type. Now we're serious. If an error
597 // appears now, it's not ignored.
598 // This may not be entirely in line with the standard. Take for example:
599 // struct A {};
600 // struct B : virtual A {
601 // B(A&);
602 // };
603 //
604 // void f()
605 // {
606 // (void)static_cast<const B&>(*((A*)0));
607 // }
608 // As far as the standard is concerned, p5 does not apply (A is virtual), so
609 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
610 // However, both GCC and Comeau reject this example, and accepting it would
611 // mean more complex code if we're to preserve the nice error message.
612 // FIXME: Being 100% compliant here would be nice to have.
613
614 // Must preserve cv, as always.
615 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000616 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000617 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000618 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000619 }
620
621 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000622 // This code is analoguous to that in CheckDerivedToBaseConversion, except
623 // that it builds the paths in reverse order.
624 // To sum up: record all paths to the base and build a nice string from
625 // them. Use it to spice up the error message.
626 Paths.clear();
627 Paths.setRecordingPaths(true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000628 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000629 std::string PathDisplayStr;
630 std::set<unsigned> DisplayedPaths;
631 for (BasePaths::paths_iterator Path = Paths.begin();
632 Path != Paths.end(); ++Path) {
633 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
634 // We haven't displayed a path to this particular base
635 // class subobject yet.
636 PathDisplayStr += "\n ";
637 for (BasePath::const_reverse_iterator Element = Path->rbegin();
638 Element != Path->rend(); ++Element)
639 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
640 PathDisplayStr += DestType.getAsString();
641 }
642 }
643
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000644 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattnerd1625842008-11-24 06:25:27 +0000645 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000646 << PathDisplayStr << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000647 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000648 }
649
650 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000651 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000652 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattnerd1625842008-11-24 06:25:27 +0000653 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000654 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000655 }
656
657 // FIXME: Test accessibility.
658
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000659 return TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000660}
661
Sebastian Redl21593ac2009-01-28 18:33:18 +0000662/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
663/// C++ 5.2.9p9 is valid:
664///
665/// An rvalue of type "pointer to member of D of type cv1 T" can be
666/// converted to an rvalue of type "pointer to member of B of type cv2 T",
667/// where B is a base class of D [...].
668///
669TryStaticCastResult
670TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
671 const SourceRange &OpRange)
672{
673 const MemberPointerType *SrcMemPtr = SrcType->getAsMemberPointerType();
674 if (!SrcMemPtr)
675 return TSC_NotApplicable;
676 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType();
677 if (!DestMemPtr)
678 return TSC_NotApplicable;
679
680 // T == T, modulo cv
681 if (Self.Context.getCanonicalType(
682 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
683 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
684 getUnqualifiedType()))
685 return TSC_NotApplicable;
686
687 // B base of D
688 QualType SrcClass(SrcMemPtr->getClass(), 0);
689 QualType DestClass(DestMemPtr->getClass(), 0);
690 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
691 /*DetectVirtual=*/true);
692 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
693 return TSC_NotApplicable;
694 }
695
696 // B is a base of D. But is it an allowed base? If not, it's a hard error.
697 if (Paths.isAmbiguous(DestClass)) {
698 Paths.clear();
699 Paths.setRecordingPaths(true);
700 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
701 assert(StillOkay);
702 StillOkay = StillOkay;
703 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
704 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
705 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
706 return TSC_Failed;
707 }
708
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000709 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +0000710 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
711 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
712 return TSC_Failed;
713 }
714
715 // FIXME: Test accessibility.
716
717 return TSC_Success;
718}
719
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000720/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
721/// is valid:
722///
723/// An expression e can be explicitly converted to a type T using a
724/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000725TryStaticCastResult
726TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
727 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000728{
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000729 if (DestType->isReferenceType()) {
730 // At this point of CheckStaticCast, if the destination is a reference,
731 // this has to work. There is no other way that works.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000732 return Self.CheckReferenceInit(SrcExpr, DestType) ?
733 TSC_Failed : TSC_Success;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000734 }
735 if (DestType->isRecordType()) {
736 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
737 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000738 }
739
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000740 // FIXME: To get a proper error from invalid conversions here, we need to
741 // reimplement more of this.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000742 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
743 SrcExpr, DestType);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000744 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
745 TSC_NotApplicable : TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000746}
747
748/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
749/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
750/// checked downcasts in class hierarchies.
751void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000752CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
753 const SourceRange &OpRange,
754 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000755{
756 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000757 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000758
759 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
760 // or "pointer to cv void".
761
762 QualType DestPointee;
763 const PointerType *DestPointer = DestType->getAsPointerType();
764 const ReferenceType *DestReference = DestType->getAsReferenceType();
765 if (DestPointer) {
766 DestPointee = DestPointer->getPointeeType();
767 } else if (DestReference) {
768 DestPointee = DestReference->getPointeeType();
769 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000770 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000772 return;
773 }
774
775 const RecordType *DestRecord = DestPointee->getAsRecordType();
776 if (DestPointee->isVoidType()) {
777 assert(DestPointer && "Reference to void is not possible");
778 } else if (DestRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000779 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000780 diag::err_bad_dynamic_cast_incomplete,
781 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000782 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000783 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000784 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000785 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000786 return;
787 }
788
789 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
790 // complete class type, [...]. If T is a reference type, v shall be an
791 // lvalue of a complete class type, [...].
792
Sebastian Redl37d6de32008-11-08 13:00:26 +0000793 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000794 QualType SrcPointee;
795 if (DestPointer) {
796 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
797 SrcPointee = SrcPointer->getPointeeType();
798 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000799 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000800 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000801 return;
802 }
803 } else {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000804 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000805 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000806 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000807 }
808 SrcPointee = SrcType;
809 }
810
811 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
812 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000813 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000814 diag::err_bad_dynamic_cast_incomplete,
815 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000816 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000817 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000818 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000819 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000820 return;
821 }
822
823 assert((DestPointer || DestReference) &&
824 "Bad destination non-ptr/ref slipped through.");
825 assert((DestRecord || DestPointee->isVoidType()) &&
826 "Bad destination pointee slipped through.");
827 assert(SrcRecord && "Bad source pointee slipped through.");
828
829 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
830 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000831 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000832 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000833 return;
834 }
835
836 // C++ 5.2.7p3: If the type of v is the same as the required result type,
837 // [except for cv].
838 if (DestRecord == SrcRecord) {
839 return;
840 }
841
842 // C++ 5.2.7p5
843 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000844 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
845 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000846 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000847 // Diagnostic already emitted on error.
848 return;
849 }
850
851 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000852 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000853 assert(SrcDecl && "Definition missing");
854 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000855 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000856 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000857 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000858
859 // Done. Everything else is run-time checks.
860}