blob: af1e2e000881ba6b669454eb68fae89578b3e1fe [file] [log] [blame]
Sebastian Redl2b6b14c2008-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"
18#include "clang/Basic/Diagnostic.h"
19#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redlf831eeb2008-11-08 13:00:26 +000023enum TryStaticCastResult {
24 TSC_NotApplicable, ///< The cast method is not applicable.
25 TSC_Success, ///< The cast method is appropriate and successful.
26 TSC_Failed ///< The cast method is appropriate, but failed. A
27 ///< diagnostic has been emitted.
28};
29
30static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
31 const SourceRange &OpRange,
32 const SourceRange &DestRange);
33static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
34 const SourceRange &OpRange,
35 const SourceRange &DestRange);
36static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
37 const SourceRange &OpRange);
38static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
39 const SourceRange &OpRange,
40 const SourceRange &DestRange);
41
42static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
43static TryStaticCastResult TryStaticReferenceDowncast(
44 Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
45static TryStaticCastResult TryStaticPointerDowncast(
46 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
47static TryStaticCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
48 QualType DestType,
49 const SourceRange &OpRange,
50 QualType OrigSrcType,
51 QualType OrigDestType);
52static TryStaticCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
53 QualType DestType,
54 const SourceRange &OpRange);
55
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000056/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
57Action::ExprResult
58Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
59 SourceLocation LAngleBracketLoc, TypeTy *Ty,
60 SourceLocation RAngleBracketLoc,
61 SourceLocation LParenLoc, ExprTy *E,
62 SourceLocation RParenLoc) {
63 Expr *Ex = (Expr*)E;
64 QualType DestType = QualType::getFromOpaquePtr(Ty);
65 SourceRange OpRange(OpLoc, RParenLoc);
66 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
67
68 switch (Kind) {
69 default: assert(0 && "Unknown C++ cast!");
70
71 case tok::kw_const_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000072 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000073 return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
74 DestType, OpLoc);
75
76 case tok::kw_dynamic_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000077 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000078 return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
79 DestType, OpLoc);
80
81 case tok::kw_reinterpret_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000082 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000083 return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex,
84 DestType, OpLoc);
85
86 case tok::kw_static_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000087 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000088 return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
89 DestType, OpLoc);
90 }
91
92 return true;
93}
94
95/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
96/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
97/// like this:
98/// const char *str = "literal";
99/// legacy_function(const_cast\<char*\>(str));
100void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000101CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
102 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000103{
104 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
105
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000106 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000107 QualType SrcType = SrcExpr->getType();
108 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000109 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000110 // Cannot cast non-lvalue to reference type.
Chris Lattner70b93d82008-11-18 22:52:51 +0000111 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000112 << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000113 return;
114 }
115
116 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
117 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000118 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
119 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000120 } else {
121 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
122 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
123 // conversions are performed on the expression.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000124 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000125 SrcType = SrcExpr->getType();
126 }
127
128 if (!DestType->isPointerType()) {
129 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
130 // was a reference type, we converted it to a pointer above.
131 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattner70b93d82008-11-18 22:52:51 +0000132 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000133 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000134 return;
135 }
136 if (DestType->isFunctionPointerType()) {
137 // Cannot cast direct function pointers.
138 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
139 // T is the ultimate pointee of source and target type.
Chris Lattner70b93d82008-11-18 22:52:51 +0000140 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000141 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000142 return;
143 }
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000144 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000145
146 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
147 // completely equal.
148 // FIXME: const_cast should probably not be able to convert between pointers
149 // to different address spaces.
150 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
151 // in multi-level pointers may change, but the level count must be the same,
152 // as must be the final pointee type.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000153 while (SrcType != DestType &&
154 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000155 SrcType = SrcType.getUnqualifiedType();
156 DestType = DestType.getUnqualifiedType();
157 }
158
159 // Doug Gregor said to disallow this until users complain.
160#if 0
161 // If we end up with constant arrays of equal size, unwrap those too. A cast
162 // from const int [N] to int (&)[N] is invalid by my reading of the
163 // standard, but g++ accepts it even with -ansi -pedantic.
164 // No more than one level, though, so don't embed this in the unwrap loop
165 // above.
166 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000167 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
168 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000169 {
170 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
171 // Different array sizes.
Chris Lattner70b93d82008-11-18 22:52:51 +0000172 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000173 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000174 return;
175 }
176 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
177 DestType = DestTypeArr->getElementType().getUnqualifiedType();
178 }
179#endif
180
181 // Since we're dealing in canonical types, the remainder must be the same.
182 if (SrcType != DestType) {
183 // Cast between unrelated types.
Chris Lattner70b93d82008-11-18 22:52:51 +0000184 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000185 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000186 return;
187 }
188}
189
190/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
191/// valid.
192/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
193/// like this:
194/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
195void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000196CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
197 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000198{
199 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
200
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000201 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000202 QualType SrcType = SrcExpr->getType();
203 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000204 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000205 // Cannot cast non-lvalue to reference type.
Chris Lattner70b93d82008-11-18 22:52:51 +0000206 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000207 << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000208 return;
209 }
210
211 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
212 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
213 // built-in & and * operators.
214 // This code does this transformation for the checked types.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000215 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
216 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000217 } else {
218 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
219 // function-to-pointer standard conversions are performed on the
220 // expression v.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000221 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000222 SrcType = SrcExpr->getType();
223 }
224
225 // Canonicalize source for comparison.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000226 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000227
228 bool destIsPtr = DestType->isPointerType();
229 bool srcIsPtr = SrcType->isPointerType();
230 if (!destIsPtr && !srcIsPtr) {
231 // Except for std::nullptr_t->integer, which is not supported yet, and
232 // lvalue->reference, which is handled above, at least one of the two
233 // arguments must be a pointer.
Chris Lattner70b93d82008-11-18 22:52:51 +0000234 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000235 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000236 return;
237 }
238
239 if (SrcType == DestType) {
240 // C++ 5.2.10p2 has a note that mentions that, subject to all other
241 // restrictions, a cast to the same type is allowed. The intent is not
242 // entirely clear here, since all other paragraphs explicitly forbid casts
243 // to the same type. However, the behavior of compilers is pretty consistent
244 // on this point: allow same-type conversion if the involved are pointers,
245 // disallow otherwise.
246 return;
247 }
248
249 // Note: Clang treats enumeration types as integral types. If this is ever
250 // changed for C++, the additional check here will be redundant.
251 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000252 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000253 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
254 // type large enough to hold it.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000255 if (Self.Context.getTypeSize(SrcType) >
256 Self.Context.getTypeSize(DestType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000257 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000258 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000259 }
260 return;
261 }
262
263 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000264 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000265 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
266 // converted to a pointer.
267 return;
268 }
269
270 if (!destIsPtr || !srcIsPtr) {
271 // With the valid non-pointer conversions out of the way, we can be even
272 // more stringent.
Chris Lattner70b93d82008-11-18 22:52:51 +0000273 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000274 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000275 return;
276 }
277
278 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000279 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000280 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000281 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000282 return;
283 }
284
285 // Not casting away constness, so the only remaining check is for compatible
286 // pointer categories.
287
288 if (SrcType->isFunctionPointerType()) {
289 if (DestType->isFunctionPointerType()) {
290 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
291 // a pointer to a function of a different type.
292 return;
293 }
294
295 // FIXME: Handle member pointers.
296
297 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
298 // an object type or vice versa is conditionally-supported.
299 // Compilers support it in C++03 too, though, because it's necessary for
300 // casting the return value of dlsym() and GetProcAddress().
301 // FIXME: Conditionally-supported behavior should be configurable in the
302 // TargetInfo or similar.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000303 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000304 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
305 << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000306 }
307 return;
308 }
309
310 // FIXME: Handle member pointers.
311
312 if (DestType->isFunctionPointerType()) {
313 // See above.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000314 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000315 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
316 << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000317 }
318 return;
319 }
320
321 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
322 // a pointer to an object of different type.
323 // Void pointers are not specified, but supported by every compiler out there.
324 // So we finish by allowing everything that remains - it's got to be two
325 // object pointers.
326}
327
328/// CastsAwayConstness - Check if the pointer conversion from SrcType
329/// to DestType casts away constness as defined in C++
330/// 5.2.11p8ff. This is used by the cast checkers. Both arguments
331/// must denote pointer types.
332bool
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000333CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000334{
335 // Casting away constness is defined in C++ 5.2.11p8 with reference to
336 // C++ 4.4.
337 // We piggyback on Sema::IsQualificationConversion for this, since the rules
338 // are non-trivial. So first we construct Tcv *...cv* as described in
339 // C++ 5.2.11p8.
340
341 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
342 llvm::SmallVector<unsigned, 8> cv1, cv2;
343
344 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000345 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000346 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
347 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
348 }
349 assert(cv1.size() > 0 && "Must have at least one pointer level.");
350
351 // Construct void pointers with those qualifiers (in reverse order of
352 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000353 QualType SrcConstruct = Self.Context.VoidTy;
354 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000355 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
356 i2 = cv2.rbegin();
357 i1 != cv1.rend(); ++i1, ++i2)
358 {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000359 SrcConstruct = Self.Context.getPointerType(
360 SrcConstruct.getQualifiedType(*i1));
361 DestConstruct = Self.Context.getPointerType(
362 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000363 }
364
365 // Test if they're compatible.
366 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000367 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000368}
369
370/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
371/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
372/// implicit conversions explicit and getting rid of data loss warnings.
373void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000374CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
375 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000376{
377 // The order the tests is not entirely arbitrary. There is one conversion
378 // that can be handled in two different ways. Given:
379 // struct A {};
380 // struct B : public A {
381 // B(); B(const A&);
382 // };
383 // const A &a = B();
384 // the cast static_cast<const B&>(a) could be seen as either a static
385 // reference downcast, or an explicit invocation of the user-defined
386 // conversion using B's conversion constructor.
387 // DR 427 specifies that the downcast is to be applied here.
388
389 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
390 if (DestType->isVoidType()) {
391 return;
392 }
393
394 // C++ 5.2.9p5, reference downcast.
395 // See the function for details.
396 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000397 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000398 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000399 return;
400 }
401
402 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
403 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000404 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
405 TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000406 return;
407 }
408
409 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
410 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
411 // conversions, subject to further restrictions.
412 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
413 // of qualification conversions impossible.
414
415 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
416 // are applied to the expression.
417 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000418 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000419
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000420 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000421
422 // Reverse integral promotion/conversion. All such conversions are themselves
423 // again integral promotions or conversions and are thus already handled by
424 // p2 (TryDirectInitialization above).
425 // (Note: any data loss warnings should be suppressed.)
426 // The exception is the reverse of enum->integer, i.e. integer->enum (and
427 // enum->enum). See also C++ 5.2.9p7.
428 // The same goes for reverse floating point promotion/conversion and
429 // floating-integral conversions. Again, only floating->enum is relevant.
430 if (DestType->isEnumeralType()) {
431 if (SrcType->isComplexType() || SrcType->isVectorType()) {
432 // Fall through - these cannot be converted.
433 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
434 return;
435 }
436 }
437
438 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
439 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000440 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000441 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000442 return;
443 }
444
445 // Reverse member pointer conversion. C++ 5.11 specifies member pointer
446 // conversion. C++ 5.2.9p9 has additional information.
447 // DR54's access restrictions apply here also.
448 // FIXME: Don't have member pointers yet.
449
450 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
451 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
452 // just the usual constness stuff.
453 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
454 QualType SrcPointee = SrcPointer->getPointeeType();
455 if (SrcPointee->isVoidType()) {
456 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
457 QualType DestPointee = DestPointer->getPointeeType();
458 if (DestPointee->isObjectType()) {
459 // This is definitely the intended conversion, but it might fail due
460 // to a const violation.
461 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000462 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000463 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000464 }
465 return;
466 }
467 }
468 }
469 }
470
471 // We tried everything. Everything! Nothing works! :-(
472 // FIXME: Error reporting could be a lot better. Should store the reason
473 // why every substep failed and, at the end, select the most specific and
474 // report that.
Chris Lattner70b93d82008-11-18 22:52:51 +0000475 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000476 << "static_cast" << DestType << OrigSrcType
Chris Lattner70b93d82008-11-18 22:52:51 +0000477 << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000478}
479
480/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000481TryStaticCastResult
482TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
483 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000484{
485 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
486 // cast to type "reference to cv2 D", where D is a class derived from B,
487 // if a valid standard conversion from "pointer to D" to "pointer to B"
488 // exists, cv2 >= cv1, and B is not a virtual base class of D.
489 // In addition, DR54 clarifies that the base must be accessible in the
490 // current context. Although the wording of DR54 only applies to the pointer
491 // variant of this rule, the intent is clearly for it to apply to the this
492 // conversion as well.
493
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000494 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000495 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000496 }
497
498 const ReferenceType *DestReference = DestType->getAsReferenceType();
499 if (!DestReference) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000500 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000501 }
502 QualType DestPointee = DestReference->getPointeeType();
503
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000504 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000505 SrcExpr->getType(), DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000506}
507
508/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000509TryStaticCastResult
510TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
511 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000512{
513 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
514 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
515 // is a class derived from B, if a valid standard conversion from "pointer
516 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
517 // class of D.
518 // In addition, DR54 clarifies that the base must be accessible in the
519 // current context.
520
521 const PointerType *SrcPointer = SrcType->getAsPointerType();
522 if (!SrcPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000523 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000524 }
525
526 const PointerType *DestPointer = DestType->getAsPointerType();
527 if (!DestPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000528 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000529 }
530
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000531 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000532 DestPointer->getPointeeType(),
533 OpRange, SrcType, DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000534}
535
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000536/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
537/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000538/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000539TryStaticCastResult
540TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
541 const SourceRange &OpRange, QualType OrigSrcType,
542 QualType OrigDestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000543{
544 // Downcast can only happen in class hierarchies, so we need classes.
545 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000546 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000547 }
548
549 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
550 /*DetectVirtual=*/true);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000551 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000552 return TSC_NotApplicable;
553 }
554
555 // Target type does derive from source type. Now we're serious. If an error
556 // appears now, it's not ignored.
557 // This may not be entirely in line with the standard. Take for example:
558 // struct A {};
559 // struct B : virtual A {
560 // B(A&);
561 // };
562 //
563 // void f()
564 // {
565 // (void)static_cast<const B&>(*((A*)0));
566 // }
567 // As far as the standard is concerned, p5 does not apply (A is virtual), so
568 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
569 // However, both GCC and Comeau reject this example, and accepting it would
570 // mean more complex code if we're to preserve the nice error message.
571 // FIXME: Being 100% compliant here would be nice to have.
572
573 // Must preserve cv, as always.
574 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000575 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000576 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000577 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000578 }
579
580 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000581 // This code is analoguous to that in CheckDerivedToBaseConversion, except
582 // that it builds the paths in reverse order.
583 // To sum up: record all paths to the base and build a nice string from
584 // them. Use it to spice up the error message.
585 Paths.clear();
586 Paths.setRecordingPaths(true);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000587 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000588 std::string PathDisplayStr;
589 std::set<unsigned> DisplayedPaths;
590 for (BasePaths::paths_iterator Path = Paths.begin();
591 Path != Paths.end(); ++Path) {
592 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
593 // We haven't displayed a path to this particular base
594 // class subobject yet.
595 PathDisplayStr += "\n ";
596 for (BasePath::const_reverse_iterator Element = Path->rbegin();
597 Element != Path->rend(); ++Element)
598 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
599 PathDisplayStr += DestType.getAsString();
600 }
601 }
602
Chris Lattner70b93d82008-11-18 22:52:51 +0000603 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000604 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattner70b93d82008-11-18 22:52:51 +0000605 << PathDisplayStr << OpRange;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000606 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000607 }
608
609 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000610 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattner70b93d82008-11-18 22:52:51 +0000611 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000612 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000613 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000614 }
615
616 // FIXME: Test accessibility.
617
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000618 return TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000619}
620
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000621/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
622/// is valid:
623///
624/// An expression e can be explicitly converted to a type T using a
625/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000626TryStaticCastResult
627TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
628 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000629{
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000630 if (DestType->isReferenceType()) {
631 // At this point of CheckStaticCast, if the destination is a reference,
632 // this has to work. There is no other way that works.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000633 return Self.CheckReferenceInit(SrcExpr, DestType) ?
634 TSC_Failed : TSC_Success;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000635 }
636 if (DestType->isRecordType()) {
637 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
638 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000639 }
640
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000641 // FIXME: To get a proper error from invalid conversions here, we need to
642 // reimplement more of this.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000643 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
644 SrcExpr, DestType);
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000645 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
646 TSC_NotApplicable : TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000647}
648
649/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
650/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
651/// checked downcasts in class hierarchies.
652void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000653CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
654 const SourceRange &OpRange,
655 const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000656{
657 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000658 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000659
660 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
661 // or "pointer to cv void".
662
663 QualType DestPointee;
664 const PointerType *DestPointer = DestType->getAsPointerType();
665 const ReferenceType *DestReference = DestType->getAsReferenceType();
666 if (DestPointer) {
667 DestPointee = DestPointer->getPointeeType();
668 } else if (DestReference) {
669 DestPointee = DestReference->getPointeeType();
670 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000671 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000672 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000673 return;
674 }
675
676 const RecordType *DestRecord = DestPointee->getAsRecordType();
677 if (DestPointee->isVoidType()) {
678 assert(DestPointer && "Reference to void is not possible");
679 } else if (DestRecord) {
680 if (!DestRecord->getDecl()->isDefinition()) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000681 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000682 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000683 return;
684 }
685 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000686 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000687 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000688 return;
689 }
690
691 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
692 // complete class type, [...]. If T is a reference type, v shall be an
693 // lvalue of a complete class type, [...].
694
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000695 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000696 QualType SrcPointee;
697 if (DestPointer) {
698 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
699 SrcPointee = SrcPointer->getPointeeType();
700 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000701 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000702 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000703 return;
704 }
705 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000706 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000707 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000708 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000709 }
710 SrcPointee = SrcType;
711 }
712
713 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
714 if (SrcRecord) {
715 if (!SrcRecord->getDecl()->isDefinition()) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000716 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000717 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000718 return;
719 }
720 } else {
Chris Lattner77d52da2008-11-20 06:06:08 +0000721 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000722 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000723 return;
724 }
725
726 assert((DestPointer || DestReference) &&
727 "Bad destination non-ptr/ref slipped through.");
728 assert((DestRecord || DestPointee->isVoidType()) &&
729 "Bad destination pointee slipped through.");
730 assert(SrcRecord && "Bad source pointee slipped through.");
731
732 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
733 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000734 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000735 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000736 return;
737 }
738
739 // C++ 5.2.7p3: If the type of v is the same as the required result type,
740 // [except for cv].
741 if (DestRecord == SrcRecord) {
742 return;
743 }
744
745 // C++ 5.2.7p5
746 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000747 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
748 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner4bfd2232008-11-24 06:25:27 +0000749 OpRange.getBegin(), OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000750 // Diagnostic already emitted on error.
751 return;
752 }
753
754 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000755 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000756 assert(SrcDecl && "Definition missing");
757 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner77d52da2008-11-20 06:06:08 +0000758 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000759 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000760 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000761
762 // Done. Everything else is run-time checks.
763}