blob: 0dedd3a4bc73ba06fcc176476237145782c3c0a5 [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 =
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000121 DestType->getAs<LValueReferenceType>()) {
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 =
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000223 DestType->getAs<LValueReferenceType>()) {
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 =
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000238 DestType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000239 // 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
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000256 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
257 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redldb647282009-01-27 23:18:31 +0000258 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 Redl6e8ed162009-05-10 18:38:11 +0000282 // See below for the enumeral issue.
283 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
284 !DestType->isEnumeralType()) {
285 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
286 // type large enough to hold it. A value of std::nullptr_t can be
287 // converted to an integral type; the conversion has the same meaning
288 // and validity as a conversion of (void*)0 to the integral type.
289 if (Self.Context.getTypeSize(SrcType) >
290 Self.Context.getTypeSize(DestType)) {
291 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
292 << OrigDestType << DestRange;
293 }
294 return;
295 }
296
Sebastian Redl26d85b12008-11-05 21:50:06 +0000297 bool destIsPtr = DestType->isPointerType();
298 bool srcIsPtr = SrcType->isPointerType();
299 if (!destIsPtr && !srcIsPtr) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000300 // Except for std::nullptr_t->integer and lvalue->reference, which are
301 // handled above, at least one of the two arguments must be a pointer.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000302 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000303 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000304 return;
305 }
306
307 if (SrcType == DestType) {
308 // C++ 5.2.10p2 has a note that mentions that, subject to all other
309 // restrictions, a cast to the same type is allowed. The intent is not
310 // entirely clear here, since all other paragraphs explicitly forbid casts
311 // to the same type. However, the behavior of compilers is pretty consistent
Sebastian Redldb647282009-01-27 23:18:31 +0000312 // on this point: allow same-type conversion if the involved types are
313 // pointers, disallow otherwise.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000314 return;
315 }
316
317 // Note: Clang treats enumeration types as integral types. If this is ever
318 // changed for C++, the additional check here will be redundant.
319 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000320 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
322 // type large enough to hold it.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000323 if (Self.Context.getTypeSize(SrcType) >
324 Self.Context.getTypeSize(DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000325 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattnerd1625842008-11-24 06:25:27 +0000326 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000327 }
328 return;
329 }
330
331 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000332 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000333 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
334 // converted to a pointer.
335 return;
336 }
337
338 if (!destIsPtr || !srcIsPtr) {
339 // With the valid non-pointer conversions out of the way, we can be even
340 // more stringent.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000341 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000342 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000343 return;
344 }
345
346 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000347 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000348 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000349 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000350 return;
351 }
352
353 // Not casting away constness, so the only remaining check is for compatible
354 // pointer categories.
355
356 if (SrcType->isFunctionPointerType()) {
357 if (DestType->isFunctionPointerType()) {
358 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
359 // a pointer to a function of a different type.
360 return;
361 }
362
Sebastian Redl26d85b12008-11-05 21:50:06 +0000363 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
364 // an object type or vice versa is conditionally-supported.
365 // Compilers support it in C++03 too, though, because it's necessary for
366 // casting the return value of dlsym() and GetProcAddress().
367 // FIXME: Conditionally-supported behavior should be configurable in the
368 // TargetInfo or similar.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000369 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000370 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
371 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000372 }
373 return;
374 }
375
Sebastian Redl26d85b12008-11-05 21:50:06 +0000376 if (DestType->isFunctionPointerType()) {
377 // See above.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000378 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000379 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
380 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000381 }
382 return;
383 }
384
385 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
386 // a pointer to an object of different type.
387 // Void pointers are not specified, but supported by every compiler out there.
388 // So we finish by allowing everything that remains - it's got to be two
389 // object pointers.
390}
391
Sebastian Redldb647282009-01-27 23:18:31 +0000392/// CastsAwayConstness - Check if the pointer conversion from SrcType to
393/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
394/// the cast checkers. Both arguments must denote pointer (possibly to member)
395/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000396bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000397CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000398{
Sebastian Redldb647282009-01-27 23:18:31 +0000399 // Casting away constness is defined in C++ 5.2.11p8 with reference to
400 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
401 // the rules are non-trivial. So first we construct Tcv *...cv* as described
402 // in C++ 5.2.11p8.
403 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
404 "Source type is not pointer or pointer to member.");
405 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
406 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000407
408 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
409 llvm::SmallVector<unsigned, 8> cv1, cv2;
410
411 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000412 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000413 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
414 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
415 }
416 assert(cv1.size() > 0 && "Must have at least one pointer level.");
417
418 // Construct void pointers with those qualifiers (in reverse order of
419 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000420 QualType SrcConstruct = Self.Context.VoidTy;
421 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000422 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
423 i2 = cv2.rbegin();
424 i1 != cv1.rend(); ++i1, ++i2)
425 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000426 SrcConstruct = Self.Context.getPointerType(
427 SrcConstruct.getQualifiedType(*i1));
428 DestConstruct = Self.Context.getPointerType(
429 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000430 }
431
432 // Test if they're compatible.
433 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000434 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000435}
436
437/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
438/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
439/// implicit conversions explicit and getting rid of data loss warnings.
440void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000441CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
442 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000443{
444 // The order the tests is not entirely arbitrary. There is one conversion
445 // that can be handled in two different ways. Given:
446 // struct A {};
447 // struct B : public A {
448 // B(); B(const A&);
449 // };
450 // const A &a = B();
451 // the cast static_cast<const B&>(a) could be seen as either a static
452 // reference downcast, or an explicit invocation of the user-defined
453 // conversion using B's conversion constructor.
454 // DR 427 specifies that the downcast is to be applied here.
455
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000456 // FIXME: With N2812, casts to rvalue refs will change.
457
Sebastian Redl26d85b12008-11-05 21:50:06 +0000458 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
459 if (DestType->isVoidType()) {
460 return;
461 }
462
463 // C++ 5.2.9p5, reference downcast.
464 // See the function for details.
465 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000466 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000467 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000468 return;
469 }
470
Sebastian Redl157be832009-03-22 22:30:06 +0000471 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
472 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
473 if (TryLValueToRValueCast(Self, SrcExpr, DestType, OpRange) >
474 TSC_NotApplicable) {
475 return;
476 }
477
Sebastian Redl26d85b12008-11-05 21:50:06 +0000478 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
479 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000480 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
481 TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000482 return;
483 }
484
485 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
486 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
487 // conversions, subject to further restrictions.
488 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
489 // of qualification conversions impossible.
490
491 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
492 // are applied to the expression.
493 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000494 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000495
Sebastian Redl37d6de32008-11-08 13:00:26 +0000496 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000497
498 // Reverse integral promotion/conversion. All such conversions are themselves
499 // again integral promotions or conversions and are thus already handled by
500 // p2 (TryDirectInitialization above).
501 // (Note: any data loss warnings should be suppressed.)
502 // The exception is the reverse of enum->integer, i.e. integer->enum (and
503 // enum->enum). See also C++ 5.2.9p7.
504 // The same goes for reverse floating point promotion/conversion and
505 // floating-integral conversions. Again, only floating->enum is relevant.
506 if (DestType->isEnumeralType()) {
507 if (SrcType->isComplexType() || SrcType->isVectorType()) {
508 // Fall through - these cannot be converted.
509 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
510 return;
511 }
512 }
513
514 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
515 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000516 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000517 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000518 return;
519 }
520
Sebastian Redl21593ac2009-01-28 18:33:18 +0000521 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
Sebastian Redl26d85b12008-11-05 21:50:06 +0000522 // conversion. C++ 5.2.9p9 has additional information.
523 // DR54's access restrictions apply here also.
Sebastian Redl21593ac2009-01-28 18:33:18 +0000524 if (TryStaticMemberPointerUpcast(Self, SrcType, DestType, OpRange)
525 > TSC_NotApplicable) {
526 return;
527 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000528
529 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
530 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
531 // just the usual constness stuff.
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000532 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000533 QualType SrcPointee = SrcPointer->getPointeeType();
534 if (SrcPointee->isVoidType()) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000535 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000536 QualType DestPointee = DestPointer->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +0000537 if (DestPointee->isIncompleteOrObjectType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000538 // This is definitely the intended conversion, but it might fail due
539 // to a const violation.
540 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000541 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000542 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000543 }
544 return;
545 }
546 }
547 }
548 }
549
550 // We tried everything. Everything! Nothing works! :-(
Mike Stump390b4cc2009-05-16 07:39:55 +0000551 // FIXME: Error reporting could be a lot better. Should store the reason why
552 // every substep failed and, at the end, select the most specific and report
553 // that.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000554 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000555 << "static_cast" << DestType << OrigSrcType
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000556 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000557}
558
Sebastian Redl157be832009-03-22 22:30:06 +0000559/// Tests whether a conversion according to N2844 is valid.
560TryStaticCastResult
561TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
562 const SourceRange &OpRange)
563{
564 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
565 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000566 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl157be832009-03-22 22:30:06 +0000567 if (!R)
568 return TSC_NotApplicable;
569
570 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
571 return TSC_NotApplicable;
572
573 // Because we try the reference downcast before this function, from now on
574 // this is the only cast possibility, so we issue an error if we fail now.
575 bool DerivedToBase;
576 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
577 DerivedToBase) <
578 Sema::Ref_Compatible_With_Added_Qualification) {
579 Self.Diag(OpRange.getBegin(), diag::err_bad_lvalue_to_rvalue_cast)
580 << SrcExpr->getType() << R->getPointeeType() << OpRange;
581 return TSC_Failed;
582 }
583
584 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
585 // than nothing.
586 return TSC_Success;
587}
588
Sebastian Redl26d85b12008-11-05 21:50:06 +0000589/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000590TryStaticCastResult
591TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
592 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000593{
594 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
595 // cast to type "reference to cv2 D", where D is a class derived from B,
596 // if a valid standard conversion from "pointer to D" to "pointer to B"
597 // exists, cv2 >= cv1, and B is not a virtual base class of D.
598 // In addition, DR54 clarifies that the base must be accessible in the
599 // current context. Although the wording of DR54 only applies to the pointer
600 // variant of this rule, the intent is clearly for it to apply to the this
601 // conversion as well.
602
Sebastian Redl37d6de32008-11-08 13:00:26 +0000603 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000604 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000605 }
606
Ted Kremenek808825c2009-07-17 01:01:15 +0000607 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000608 if (!DestReference) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000609 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000610 }
611 QualType DestPointee = DestReference->getPointeeType();
612
Sebastian Redl37d6de32008-11-08 13:00:26 +0000613 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000614 SrcExpr->getType(), DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000615}
616
617/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000618TryStaticCastResult
619TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
620 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000621{
622 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
623 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
624 // is a class derived from B, if a valid standard conversion from "pointer
625 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
626 // class of D.
627 // In addition, DR54 clarifies that the base must be accessible in the
628 // current context.
629
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000630 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000631 if (!SrcPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000632 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000633 }
634
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000635 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000636 if (!DestPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000637 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000638 }
639
Sebastian Redl37d6de32008-11-08 13:00:26 +0000640 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000641 DestPointer->getPointeeType(),
642 OpRange, SrcType, DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000643}
644
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000645/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
646/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl26d85b12008-11-05 21:50:06 +0000647/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000648TryStaticCastResult
649TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
650 const SourceRange &OpRange, QualType OrigSrcType,
651 QualType OrigDestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000652{
653 // Downcast can only happen in class hierarchies, so we need classes.
654 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000655 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000656 }
657
658 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
659 /*DetectVirtual=*/true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000660 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000661 return TSC_NotApplicable;
662 }
663
664 // Target type does derive from source type. Now we're serious. If an error
665 // appears now, it's not ignored.
666 // This may not be entirely in line with the standard. Take for example:
667 // struct A {};
668 // struct B : virtual A {
669 // B(A&);
670 // };
671 //
672 // void f()
673 // {
674 // (void)static_cast<const B&>(*((A*)0));
675 // }
676 // As far as the standard is concerned, p5 does not apply (A is virtual), so
677 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
678 // However, both GCC and Comeau reject this example, and accepting it would
679 // mean more complex code if we're to preserve the nice error message.
680 // FIXME: Being 100% compliant here would be nice to have.
681
682 // Must preserve cv, as always.
683 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000684 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000685 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000686 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000687 }
688
689 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000690 // This code is analoguous to that in CheckDerivedToBaseConversion, except
691 // that it builds the paths in reverse order.
692 // To sum up: record all paths to the base and build a nice string from
693 // them. Use it to spice up the error message.
694 Paths.clear();
695 Paths.setRecordingPaths(true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000696 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000697 std::string PathDisplayStr;
698 std::set<unsigned> DisplayedPaths;
699 for (BasePaths::paths_iterator Path = Paths.begin();
700 Path != Paths.end(); ++Path) {
701 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
702 // We haven't displayed a path to this particular base
703 // class subobject yet.
704 PathDisplayStr += "\n ";
705 for (BasePath::const_reverse_iterator Element = Path->rbegin();
706 Element != Path->rend(); ++Element)
707 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
708 PathDisplayStr += DestType.getAsString();
709 }
710 }
711
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000712 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattnerd1625842008-11-24 06:25:27 +0000713 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000714 << PathDisplayStr << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000715 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000716 }
717
718 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000719 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000720 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattnerd1625842008-11-24 06:25:27 +0000721 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000722 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000723 }
724
725 // FIXME: Test accessibility.
726
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000727 return TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000728}
729
Sebastian Redl21593ac2009-01-28 18:33:18 +0000730/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
731/// C++ 5.2.9p9 is valid:
732///
733/// An rvalue of type "pointer to member of D of type cv1 T" can be
734/// converted to an rvalue of type "pointer to member of B of type cv2 T",
735/// where B is a base class of D [...].
736///
737TryStaticCastResult
738TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
739 const SourceRange &OpRange)
740{
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000741 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +0000742 if (!SrcMemPtr)
743 return TSC_NotApplicable;
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000744 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +0000745 if (!DestMemPtr)
746 return TSC_NotApplicable;
747
748 // T == T, modulo cv
749 if (Self.Context.getCanonicalType(
750 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
751 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
752 getUnqualifiedType()))
753 return TSC_NotApplicable;
754
755 // B base of D
756 QualType SrcClass(SrcMemPtr->getClass(), 0);
757 QualType DestClass(DestMemPtr->getClass(), 0);
758 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
759 /*DetectVirtual=*/true);
760 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
761 return TSC_NotApplicable;
762 }
763
764 // B is a base of D. But is it an allowed base? If not, it's a hard error.
765 if (Paths.isAmbiguous(DestClass)) {
766 Paths.clear();
767 Paths.setRecordingPaths(true);
768 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
769 assert(StillOkay);
770 StillOkay = StillOkay;
771 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
772 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
773 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
774 return TSC_Failed;
775 }
776
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000777 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +0000778 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
779 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
780 return TSC_Failed;
781 }
782
783 // FIXME: Test accessibility.
784
785 return TSC_Success;
786}
787
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000788/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
789/// is valid:
790///
791/// An expression e can be explicitly converted to a type T using a
792/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000793TryStaticCastResult
794TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
795 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000796{
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000797 if (DestType->isReferenceType()) {
798 // At this point of CheckStaticCast, if the destination is a reference,
799 // this has to work. There is no other way that works.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000800 return Self.CheckReferenceInit(SrcExpr, DestType) ?
801 TSC_Failed : TSC_Success;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000802 }
803 if (DestType->isRecordType()) {
804 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
805 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000806 }
807
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000808 // FIXME: To get a proper error from invalid conversions here, we need to
809 // reimplement more of this.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000810 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
811 SrcExpr, DestType);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000812 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
813 TSC_NotApplicable : TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000814}
815
816/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
817/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
818/// checked downcasts in class hierarchies.
819void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000820CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
821 const SourceRange &OpRange,
822 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000823{
824 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000825 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000826
827 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
828 // or "pointer to cv void".
829
830 QualType DestPointee;
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000831 const PointerType *DestPointer = DestType->getAs<PointerType>();
Ted Kremenek808825c2009-07-17 01:01:15 +0000832 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000833 if (DestPointer) {
834 DestPointee = DestPointer->getPointeeType();
835 } else if (DestReference) {
836 DestPointee = DestReference->getPointeeType();
837 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000838 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000839 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000840 return;
841 }
842
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000843 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000844 if (DestPointee->isVoidType()) {
845 assert(DestPointer && "Reference to void is not possible");
846 } else if (DestRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000847 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000848 diag::err_bad_dynamic_cast_incomplete,
849 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000850 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000851 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000852 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000853 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000854 return;
855 }
856
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000857 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
858 // complete class type, [...]. If T is an lvalue reference type, v shall be
859 // an lvalue of a complete class type, [...]. If T is an rvalue reference
860 // type, v shall be an expression having a complete effective class type,
861 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000862
Sebastian Redl37d6de32008-11-08 13:00:26 +0000863 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000864 QualType SrcPointee;
865 if (DestPointer) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +0000866 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000867 SrcPointee = SrcPointer->getPointeeType();
868 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000869 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000870 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000871 return;
872 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000873 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000874 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000875 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000876 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000877 }
878 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000879 } else {
880 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000881 }
882
Ted Kremenek5cad1f72009-07-17 01:20:38 +0000883 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000884 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000885 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000886 diag::err_bad_dynamic_cast_incomplete,
887 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000888 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000889 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000890 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000891 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000892 return;
893 }
894
895 assert((DestPointer || DestReference) &&
896 "Bad destination non-ptr/ref slipped through.");
897 assert((DestRecord || DestPointee->isVoidType()) &&
898 "Bad destination pointee slipped through.");
899 assert(SrcRecord && "Bad source pointee slipped through.");
900
901 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
902 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000903 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000904 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000905 return;
906 }
907
908 // C++ 5.2.7p3: If the type of v is the same as the required result type,
909 // [except for cv].
910 if (DestRecord == SrcRecord) {
911 return;
912 }
913
914 // C++ 5.2.7p5
915 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000916 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
917 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000918 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000919 // Diagnostic already emitted on error.
920 return;
921 }
922
923 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000924 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000925 assert(SrcDecl && "Definition missing");
926 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000927 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000928 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000929 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000930
931 // Done. Everything else is run-time checks.
932}