blob: f5bef4a1f2d079adb6ee041e5b238d13c13484e5 [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);
Sebastian Redl157be832009-03-22 22:30:06 +000042static TryStaticCastResult TryLValueToRValueCast(
43 Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
Sebastian Redl37d6de32008-11-08 13:00:26 +000044static TryStaticCastResult TryStaticReferenceDowncast(
45 Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
46static TryStaticCastResult TryStaticPointerDowncast(
47 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
Sebastian Redl21593ac2009-01-28 18:33:18 +000048static TryStaticCastResult TryStaticMemberPointerUpcast(
49 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
Sebastian Redl37d6de32008-11-08 13:00:26 +000050static TryStaticCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
51 QualType DestType,
52 const SourceRange &OpRange,
53 QualType OrigSrcType,
54 QualType OrigDestType);
55static TryStaticCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
56 QualType DestType,
57 const SourceRange &OpRange);
58
Sebastian Redl26d85b12008-11-05 21:50:06 +000059/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +000060Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +000061Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
62 SourceLocation LAngleBracketLoc, TypeTy *Ty,
63 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +000064 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +000065 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +000066 Expr *Ex = E.takeAs<Expr>();
Sebastian Redl26d85b12008-11-05 21:50:06 +000067 QualType DestType = QualType::getFromOpaquePtr(Ty);
68 SourceRange OpRange(OpLoc, RParenLoc);
69 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
70
Douglas Gregor9103bb22008-12-17 22:52:20 +000071 // If the type is dependent, we won't do the semantic analysis now.
72 // FIXME: should we check this in a more fine-grained manner?
73 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
74
Sebastian Redl26d85b12008-11-05 21:50:06 +000075 switch (Kind) {
76 default: assert(0 && "Unknown C++ cast!");
77
78 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000079 if (!TypeDependent)
80 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000081 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
82 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +000083
84 case tok::kw_dynamic_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000085 if (!TypeDependent)
86 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000087 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
88 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +000089
90 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000091 if (!TypeDependent)
92 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +000093 return Owned(new (Context) CXXReinterpretCastExpr(
94 DestType.getNonReferenceType(),
95 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +000096
97 case tok::kw_static_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000098 if (!TypeDependent)
99 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000100 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
101 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000102 }
103
Sebastian Redlf53597f2009-03-15 17:47:39 +0000104 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000105}
106
107/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
108/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
109/// like this:
110/// const char *str = "literal";
111/// legacy_function(const_cast\<char*\>(str));
112void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000113CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
114 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000115{
116 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
117
Sebastian Redl37d6de32008-11-08 13:00:26 +0000118 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000119 QualType SrcType = SrcExpr->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000120 if (const LValueReferenceType *DestTypeTmp =
121 DestType->getAsLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000122 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000123 // Cannot cast non-lvalue to lvalue reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000124 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000125 << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000126 return;
127 }
128
129 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
130 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000131 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
132 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000133 } else {
134 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
135 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
136 // conversions are performed on the expression.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000137 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000138 SrcType = SrcExpr->getType();
139 }
140
Sebastian Redlf20269b2009-01-26 22:19:12 +0000141 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
142 // the rules for const_cast are the same as those used for pointers.
143
144 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000145 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
146 // was a reference type, we converted it to a pointer above.
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000147 // The status of rvalue references isn't entirely clear, but it looks like
148 // conversion to them is simply invalid.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000149 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000150 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000151 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000152 return;
153 }
Sebastian Redlf20269b2009-01-26 22:19:12 +0000154 if (DestType->isFunctionPointerType() ||
155 DestType->isMemberFunctionPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000156 // Cannot cast direct function pointers.
157 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
158 // T is the ultimate pointee of source and target type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000159 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000160 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000161 return;
162 }
Sebastian Redl37d6de32008-11-08 13:00:26 +0000163 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000164
165 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
166 // completely equal.
167 // FIXME: const_cast should probably not be able to convert between pointers
168 // to different address spaces.
169 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
170 // in multi-level pointers may change, but the level count must be the same,
171 // as must be the final pointee type.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000172 while (SrcType != DestType &&
173 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000174 SrcType = SrcType.getUnqualifiedType();
175 DestType = DestType.getUnqualifiedType();
176 }
177
178 // Doug Gregor said to disallow this until users complain.
179#if 0
180 // If we end up with constant arrays of equal size, unwrap those too. A cast
181 // from const int [N] to int (&)[N] is invalid by my reading of the
182 // standard, but g++ accepts it even with -ansi -pedantic.
183 // No more than one level, though, so don't embed this in the unwrap loop
184 // above.
185 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redl37d6de32008-11-08 13:00:26 +0000186 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
187 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000188 {
189 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
190 // Different array sizes.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000191 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000192 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000193 return;
194 }
195 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
196 DestType = DestTypeArr->getElementType().getUnqualifiedType();
197 }
198#endif
199
200 // Since we're dealing in canonical types, the remainder must be the same.
201 if (SrcType != DestType) {
202 // Cast between unrelated types.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000203 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000204 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000205 return;
206 }
207}
208
209/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
210/// valid.
211/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
212/// like this:
213/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
214void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000215CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
216 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000217{
218 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
219
Sebastian Redl37d6de32008-11-08 13:00:26 +0000220 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000221 QualType SrcType = SrcExpr->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000222 if (const LValueReferenceType *DestTypeTmp =
223 DestType->getAsLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000224 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000226 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000227 << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000228 return;
229 }
230
231 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
232 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
233 // built-in & and * operators.
234 // This code does this transformation for the checked types.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000235 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
236 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000237 } else if (const RValueReferenceType *DestTypeTmp =
238 DestType->getAsRValueReferenceType()) {
239 // Both the reference conversion and the rvalue rules apply.
240 Self.DefaultFunctionArrayConversion(SrcExpr);
241 SrcType = SrcExpr->getType();
242
243 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
244 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000245 } else {
246 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
247 // function-to-pointer standard conversions are performed on the
248 // expression v.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000249 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000250 SrcType = SrcExpr->getType();
251 }
252
253 // Canonicalize source for comparison.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000254 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000255
Sebastian Redldb647282009-01-27 23:18:31 +0000256 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType(),
257 *SrcMemPtr = SrcType->getAsMemberPointerType();
258 if (DestMemPtr && SrcMemPtr) {
259 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
260 // can be explicitly converted to an rvalue of type "pointer to member
261 // of Y of type T2" if T1 and T2 are both function types or both object
262 // types.
263 if (DestMemPtr->getPointeeType()->isFunctionType() !=
264 SrcMemPtr->getPointeeType()->isFunctionType()) {
265 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
266 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
267 return;
268 }
269
270 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
271 // constness.
272 if (CastsAwayConstness(Self, SrcType, DestType)) {
273 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
274 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
275 return;
276 }
277
278 // A valid member pointer cast.
279 return;
280 }
281
Sebastian Redl26d85b12008-11-05 21:50:06 +0000282 bool destIsPtr = DestType->isPointerType();
283 bool srcIsPtr = SrcType->isPointerType();
284 if (!destIsPtr && !srcIsPtr) {
285 // Except for std::nullptr_t->integer, which is not supported yet, and
286 // lvalue->reference, which is handled above, at least one of the two
287 // arguments must be a pointer.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000288 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000289 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 return;
291 }
292
293 if (SrcType == DestType) {
294 // C++ 5.2.10p2 has a note that mentions that, subject to all other
295 // restrictions, a cast to the same type is allowed. The intent is not
296 // entirely clear here, since all other paragraphs explicitly forbid casts
297 // to the same type. However, the behavior of compilers is pretty consistent
Sebastian Redldb647282009-01-27 23:18:31 +0000298 // on this point: allow same-type conversion if the involved types are
299 // pointers, disallow otherwise.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000300 return;
301 }
302
303 // Note: Clang treats enumeration types as integral types. If this is ever
304 // changed for C++, the additional check here will be redundant.
305 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000306 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000307 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
308 // type large enough to hold it.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000309 if (Self.Context.getTypeSize(SrcType) >
310 Self.Context.getTypeSize(DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000311 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattnerd1625842008-11-24 06:25:27 +0000312 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313 }
314 return;
315 }
316
317 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000318 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000319 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
320 // converted to a pointer.
321 return;
322 }
323
324 if (!destIsPtr || !srcIsPtr) {
325 // With the valid non-pointer conversions out of the way, we can be even
326 // more stringent.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000327 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000328 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000329 return;
330 }
331
332 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000333 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000334 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000335 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000336 return;
337 }
338
339 // Not casting away constness, so the only remaining check is for compatible
340 // pointer categories.
341
342 if (SrcType->isFunctionPointerType()) {
343 if (DestType->isFunctionPointerType()) {
344 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
345 // a pointer to a function of a different type.
346 return;
347 }
348
Sebastian Redl26d85b12008-11-05 21:50:06 +0000349 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
350 // an object type or vice versa is conditionally-supported.
351 // Compilers support it in C++03 too, though, because it's necessary for
352 // casting the return value of dlsym() and GetProcAddress().
353 // FIXME: Conditionally-supported behavior should be configurable in the
354 // TargetInfo or similar.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000355 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000356 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
357 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000358 }
359 return;
360 }
361
Sebastian Redl26d85b12008-11-05 21:50:06 +0000362 if (DestType->isFunctionPointerType()) {
363 // See above.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000364 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000365 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
366 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000367 }
368 return;
369 }
370
371 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
372 // a pointer to an object of different type.
373 // Void pointers are not specified, but supported by every compiler out there.
374 // So we finish by allowing everything that remains - it's got to be two
375 // object pointers.
376}
377
Sebastian Redldb647282009-01-27 23:18:31 +0000378/// CastsAwayConstness - Check if the pointer conversion from SrcType to
379/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
380/// the cast checkers. Both arguments must denote pointer (possibly to member)
381/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000382bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000383CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000384{
Sebastian Redldb647282009-01-27 23:18:31 +0000385 // Casting away constness is defined in C++ 5.2.11p8 with reference to
386 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
387 // the rules are non-trivial. So first we construct Tcv *...cv* as described
388 // in C++ 5.2.11p8.
389 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
390 "Source type is not pointer or pointer to member.");
391 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
392 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000393
394 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
395 llvm::SmallVector<unsigned, 8> cv1, cv2;
396
397 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000398 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000399 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
400 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
401 }
402 assert(cv1.size() > 0 && "Must have at least one pointer level.");
403
404 // Construct void pointers with those qualifiers (in reverse order of
405 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000406 QualType SrcConstruct = Self.Context.VoidTy;
407 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000408 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
409 i2 = cv2.rbegin();
410 i1 != cv1.rend(); ++i1, ++i2)
411 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000412 SrcConstruct = Self.Context.getPointerType(
413 SrcConstruct.getQualifiedType(*i1));
414 DestConstruct = Self.Context.getPointerType(
415 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000416 }
417
418 // Test if they're compatible.
419 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000420 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000421}
422
423/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
424/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
425/// implicit conversions explicit and getting rid of data loss warnings.
426void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000427CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
428 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000429{
430 // The order the tests is not entirely arbitrary. There is one conversion
431 // that can be handled in two different ways. Given:
432 // struct A {};
433 // struct B : public A {
434 // B(); B(const A&);
435 // };
436 // const A &a = B();
437 // the cast static_cast<const B&>(a) could be seen as either a static
438 // reference downcast, or an explicit invocation of the user-defined
439 // conversion using B's conversion constructor.
440 // DR 427 specifies that the downcast is to be applied here.
441
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000442 // FIXME: With N2812, casts to rvalue refs will change.
443
Sebastian Redl26d85b12008-11-05 21:50:06 +0000444 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
445 if (DestType->isVoidType()) {
446 return;
447 }
448
449 // C++ 5.2.9p5, reference downcast.
450 // See the function for details.
451 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000452 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000453 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000454 return;
455 }
456
Sebastian Redl157be832009-03-22 22:30:06 +0000457 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
458 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
459 if (TryLValueToRValueCast(Self, SrcExpr, DestType, OpRange) >
460 TSC_NotApplicable) {
461 return;
462 }
463
Sebastian Redl26d85b12008-11-05 21:50:06 +0000464 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
465 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000466 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
467 TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000468 return;
469 }
470
471 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
472 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
473 // conversions, subject to further restrictions.
474 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
475 // of qualification conversions impossible.
476
477 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
478 // are applied to the expression.
479 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000480 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000481
Sebastian Redl37d6de32008-11-08 13:00:26 +0000482 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000483
484 // Reverse integral promotion/conversion. All such conversions are themselves
485 // again integral promotions or conversions and are thus already handled by
486 // p2 (TryDirectInitialization above).
487 // (Note: any data loss warnings should be suppressed.)
488 // The exception is the reverse of enum->integer, i.e. integer->enum (and
489 // enum->enum). See also C++ 5.2.9p7.
490 // The same goes for reverse floating point promotion/conversion and
491 // floating-integral conversions. Again, only floating->enum is relevant.
492 if (DestType->isEnumeralType()) {
493 if (SrcType->isComplexType() || SrcType->isVectorType()) {
494 // Fall through - these cannot be converted.
495 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
496 return;
497 }
498 }
499
500 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
501 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000502 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000503 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000504 return;
505 }
506
Sebastian Redl21593ac2009-01-28 18:33:18 +0000507 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
Sebastian Redl26d85b12008-11-05 21:50:06 +0000508 // conversion. C++ 5.2.9p9 has additional information.
509 // DR54's access restrictions apply here also.
Sebastian Redl21593ac2009-01-28 18:33:18 +0000510 if (TryStaticMemberPointerUpcast(Self, SrcType, DestType, OpRange)
511 > TSC_NotApplicable) {
512 return;
513 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000514
515 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
516 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
517 // just the usual constness stuff.
518 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
519 QualType SrcPointee = SrcPointer->getPointeeType();
520 if (SrcPointee->isVoidType()) {
521 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
522 QualType DestPointee = DestPointer->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000523 if (DestPointee->isIncompleteOrObjectType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000524 // This is definitely the intended conversion, but it might fail due
525 // to a const violation.
526 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000527 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000528 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000529 }
530 return;
531 }
532 }
533 }
534 }
535
536 // We tried everything. Everything! Nothing works! :-(
537 // FIXME: Error reporting could be a lot better. Should store the reason
538 // why every substep failed and, at the end, select the most specific and
539 // report that.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000540 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000541 << "static_cast" << DestType << OrigSrcType
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000542 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000543}
544
Sebastian Redl157be832009-03-22 22:30:06 +0000545/// Tests whether a conversion according to N2844 is valid.
546TryStaticCastResult
547TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
548 const SourceRange &OpRange)
549{
550 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
551 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
552 const RValueReferenceType *R = DestType->getAsRValueReferenceType();
553 if (!R)
554 return TSC_NotApplicable;
555
556 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
557 return TSC_NotApplicable;
558
559 // Because we try the reference downcast before this function, from now on
560 // this is the only cast possibility, so we issue an error if we fail now.
561 bool DerivedToBase;
562 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
563 DerivedToBase) <
564 Sema::Ref_Compatible_With_Added_Qualification) {
565 Self.Diag(OpRange.getBegin(), diag::err_bad_lvalue_to_rvalue_cast)
566 << SrcExpr->getType() << R->getPointeeType() << OpRange;
567 return TSC_Failed;
568 }
569
570 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
571 // than nothing.
572 return TSC_Success;
573}
574
Sebastian Redl26d85b12008-11-05 21:50:06 +0000575/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000576TryStaticCastResult
577TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
578 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000579{
580 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
581 // cast to type "reference to cv2 D", where D is a class derived from B,
582 // if a valid standard conversion from "pointer to D" to "pointer to B"
583 // exists, cv2 >= cv1, and B is not a virtual base class of D.
584 // In addition, DR54 clarifies that the base must be accessible in the
585 // current context. Although the wording of DR54 only applies to the pointer
586 // variant of this rule, the intent is clearly for it to apply to the this
587 // conversion as well.
588
Sebastian Redl37d6de32008-11-08 13:00:26 +0000589 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000590 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000591 }
592
593 const ReferenceType *DestReference = DestType->getAsReferenceType();
594 if (!DestReference) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000595 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000596 }
597 QualType DestPointee = DestReference->getPointeeType();
598
Sebastian Redl37d6de32008-11-08 13:00:26 +0000599 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000600 SrcExpr->getType(), DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000601}
602
603/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000604TryStaticCastResult
605TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
606 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000607{
608 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
609 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
610 // is a class derived from B, if a valid standard conversion from "pointer
611 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
612 // class of D.
613 // In addition, DR54 clarifies that the base must be accessible in the
614 // current context.
615
616 const PointerType *SrcPointer = SrcType->getAsPointerType();
617 if (!SrcPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000618 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000619 }
620
621 const PointerType *DestPointer = DestType->getAsPointerType();
622 if (!DestPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000623 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000624 }
625
Sebastian Redl37d6de32008-11-08 13:00:26 +0000626 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000627 DestPointer->getPointeeType(),
628 OpRange, SrcType, DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000629}
630
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000631/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
632/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl26d85b12008-11-05 21:50:06 +0000633/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000634TryStaticCastResult
635TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
636 const SourceRange &OpRange, QualType OrigSrcType,
637 QualType OrigDestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000638{
639 // Downcast can only happen in class hierarchies, so we need classes.
640 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000641 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000642 }
643
644 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
645 /*DetectVirtual=*/true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000646 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000647 return TSC_NotApplicable;
648 }
649
650 // Target type does derive from source type. Now we're serious. If an error
651 // appears now, it's not ignored.
652 // This may not be entirely in line with the standard. Take for example:
653 // struct A {};
654 // struct B : virtual A {
655 // B(A&);
656 // };
657 //
658 // void f()
659 // {
660 // (void)static_cast<const B&>(*((A*)0));
661 // }
662 // As far as the standard is concerned, p5 does not apply (A is virtual), so
663 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
664 // However, both GCC and Comeau reject this example, and accepting it would
665 // mean more complex code if we're to preserve the nice error message.
666 // FIXME: Being 100% compliant here would be nice to have.
667
668 // Must preserve cv, as always.
669 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000670 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000671 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000672 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000673 }
674
675 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000676 // This code is analoguous to that in CheckDerivedToBaseConversion, except
677 // that it builds the paths in reverse order.
678 // To sum up: record all paths to the base and build a nice string from
679 // them. Use it to spice up the error message.
680 Paths.clear();
681 Paths.setRecordingPaths(true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000682 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000683 std::string PathDisplayStr;
684 std::set<unsigned> DisplayedPaths;
685 for (BasePaths::paths_iterator Path = Paths.begin();
686 Path != Paths.end(); ++Path) {
687 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
688 // We haven't displayed a path to this particular base
689 // class subobject yet.
690 PathDisplayStr += "\n ";
691 for (BasePath::const_reverse_iterator Element = Path->rbegin();
692 Element != Path->rend(); ++Element)
693 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
694 PathDisplayStr += DestType.getAsString();
695 }
696 }
697
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000698 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattnerd1625842008-11-24 06:25:27 +0000699 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000700 << PathDisplayStr << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000701 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000702 }
703
704 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000705 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000706 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattnerd1625842008-11-24 06:25:27 +0000707 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000708 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000709 }
710
711 // FIXME: Test accessibility.
712
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000713 return TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000714}
715
Sebastian Redl21593ac2009-01-28 18:33:18 +0000716/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
717/// C++ 5.2.9p9 is valid:
718///
719/// An rvalue of type "pointer to member of D of type cv1 T" can be
720/// converted to an rvalue of type "pointer to member of B of type cv2 T",
721/// where B is a base class of D [...].
722///
723TryStaticCastResult
724TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
725 const SourceRange &OpRange)
726{
727 const MemberPointerType *SrcMemPtr = SrcType->getAsMemberPointerType();
728 if (!SrcMemPtr)
729 return TSC_NotApplicable;
730 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType();
731 if (!DestMemPtr)
732 return TSC_NotApplicable;
733
734 // T == T, modulo cv
735 if (Self.Context.getCanonicalType(
736 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
737 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
738 getUnqualifiedType()))
739 return TSC_NotApplicable;
740
741 // B base of D
742 QualType SrcClass(SrcMemPtr->getClass(), 0);
743 QualType DestClass(DestMemPtr->getClass(), 0);
744 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
745 /*DetectVirtual=*/true);
746 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
747 return TSC_NotApplicable;
748 }
749
750 // B is a base of D. But is it an allowed base? If not, it's a hard error.
751 if (Paths.isAmbiguous(DestClass)) {
752 Paths.clear();
753 Paths.setRecordingPaths(true);
754 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
755 assert(StillOkay);
756 StillOkay = StillOkay;
757 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
758 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
759 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
760 return TSC_Failed;
761 }
762
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000763 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +0000764 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
765 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
766 return TSC_Failed;
767 }
768
769 // FIXME: Test accessibility.
770
771 return TSC_Success;
772}
773
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000774/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
775/// is valid:
776///
777/// An expression e can be explicitly converted to a type T using a
778/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000779TryStaticCastResult
780TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
781 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000782{
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000783 if (DestType->isReferenceType()) {
784 // At this point of CheckStaticCast, if the destination is a reference,
785 // this has to work. There is no other way that works.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000786 return Self.CheckReferenceInit(SrcExpr, DestType) ?
787 TSC_Failed : TSC_Success;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000788 }
789 if (DestType->isRecordType()) {
790 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
791 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000792 }
793
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000794 // FIXME: To get a proper error from invalid conversions here, we need to
795 // reimplement more of this.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000796 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
797 SrcExpr, DestType);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000798 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
799 TSC_NotApplicable : TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000800}
801
802/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
803/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
804/// checked downcasts in class hierarchies.
805void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000806CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
807 const SourceRange &OpRange,
808 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000809{
810 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000811 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000812
813 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
814 // or "pointer to cv void".
815
816 QualType DestPointee;
817 const PointerType *DestPointer = DestType->getAsPointerType();
818 const ReferenceType *DestReference = DestType->getAsReferenceType();
819 if (DestPointer) {
820 DestPointee = DestPointer->getPointeeType();
821 } else if (DestReference) {
822 DestPointee = DestReference->getPointeeType();
823 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000824 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000825 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000826 return;
827 }
828
829 const RecordType *DestRecord = DestPointee->getAsRecordType();
830 if (DestPointee->isVoidType()) {
831 assert(DestPointer && "Reference to void is not possible");
832 } else if (DestRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000833 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000834 diag::err_bad_dynamic_cast_incomplete,
835 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000836 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000837 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000838 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000839 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000840 return;
841 }
842
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000843 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
844 // complete class type, [...]. If T is an lvalue reference type, v shall be
845 // an lvalue of a complete class type, [...]. If T is an rvalue reference
846 // type, v shall be an expression having a complete effective class type,
847 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000848
Sebastian Redl37d6de32008-11-08 13:00:26 +0000849 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000850 QualType SrcPointee;
851 if (DestPointer) {
852 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
853 SrcPointee = SrcPointer->getPointeeType();
854 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000855 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000856 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000857 return;
858 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000859 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000860 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000861 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000862 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000863 }
864 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000865 } else {
866 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000867 }
868
869 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
870 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000871 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000872 diag::err_bad_dynamic_cast_incomplete,
873 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000874 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000875 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000876 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000877 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000878 return;
879 }
880
881 assert((DestPointer || DestReference) &&
882 "Bad destination non-ptr/ref slipped through.");
883 assert((DestRecord || DestPointee->isVoidType()) &&
884 "Bad destination pointee slipped through.");
885 assert(SrcRecord && "Bad source pointee slipped through.");
886
887 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
888 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000889 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000890 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000891 return;
892 }
893
894 // C++ 5.2.7p3: If the type of v is the same as the required result type,
895 // [except for cv].
896 if (DestRecord == SrcRecord) {
897 return;
898 }
899
900 // C++ 5.2.7p5
901 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000902 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
903 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000904 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000905 // Diagnostic already emitted on error.
906 return;
907 }
908
909 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000910 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000911 assert(SrcDecl && "Definition missing");
912 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000913 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000914 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000915 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000916
917 // Done. Everything else is run-time checks.
918}