blob: afe539cd46570ac9836eaf9c058212652664a688 [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 Redl9cc11e72009-07-25 15:41:38 +000022enum TryCastResult {
23 TC_NotApplicable, ///< The cast method is not applicable.
24 TC_Success, ///< The cast method is appropriate and successful.
25 TC_Failed ///< The cast method is appropriate, but failed. A
26 ///< diagnostic has been emitted.
27};
28
29enum CastType {
30 CT_Const, ///< const_cast
31 CT_Static, ///< static_cast
32 CT_Reinterpret, ///< reinterpret_cast
33 CT_Dynamic, ///< dynamic_cast
34 CT_CStyle, ///< (Type)expr
35 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000036};
37
38static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
39 const SourceRange &OpRange,
40 const SourceRange &DestRange);
41static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
42 const SourceRange &OpRange,
43 const SourceRange &DestRange);
44static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
45 const SourceRange &OpRange);
46static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
47 const SourceRange &OpRange,
48 const SourceRange &DestRange);
49
50static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000051
52// The Try functions attempt a specific way of casting. If they succeed, they
53// return TC_Success. If their way of casting is not appropriate for the given
54// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
55// to emit if no other way succeeds. If their way of casting is appropriate but
56// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
57// they emit a specialized diagnostic.
58// All diagnostics returned by these functions must expect the same three
59// arguments:
60// %0: Cast Type (a value from the CastType enumeration)
61// %1: Source Type
62// %2: Destination Type
63static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
64 QualType DestType, unsigned &msg);
65static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
66 QualType DestType, bool CStyle,
67 const SourceRange &OpRange,
68 unsigned &msg);
69static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
70 QualType DestType, bool CStyle,
71 const SourceRange &OpRange,
72 unsigned &msg);
73static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
74 QualType DestType, bool CStyle,
75 const SourceRange &OpRange,
76 QualType OrigSrcType,
77 QualType OrigDestType, unsigned &msg);
78static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
79 QualType DestType,bool CStyle,
80 const SourceRange &OpRange,
81 unsigned &msg);
82static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
83 QualType DestType, bool CStyle,
84 const SourceRange &OpRange,
85 unsigned &msg);
86static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
87 QualType DestType, bool CStyle,
88 const SourceRange &OpRange,
89 unsigned &msg);
90static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
91 bool CStyle, unsigned &msg);
92static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
93 QualType DestType, bool CStyle,
94 const SourceRange &OpRange,
95 unsigned &msg);
Sebastian Redl37d6de32008-11-08 13:00:26 +000096
Sebastian Redl26d85b12008-11-05 21:50:06 +000097/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +000098Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +000099Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
100 SourceLocation LAngleBracketLoc, TypeTy *Ty,
101 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000102 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000103 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000104 Expr *Ex = E.takeAs<Expr>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000105 QualType DestType = QualType::getFromOpaquePtr(Ty);
106 SourceRange OpRange(OpLoc, RParenLoc);
107 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
108
Douglas Gregor9103bb22008-12-17 22:52:20 +0000109 // If the type is dependent, we won't do the semantic analysis now.
110 // FIXME: should we check this in a more fine-grained manner?
111 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
112
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113 switch (Kind) {
114 default: assert(0 && "Unknown C++ cast!");
115
116 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000117 if (!TypeDependent)
118 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000119 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
120 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000121
122 case tok::kw_dynamic_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000123 if (!TypeDependent)
124 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000125 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +0000126 CastExpr::CK_Unknown, Ex,
127 DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000128
129 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000130 if (!TypeDependent)
131 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000132 return Owned(new (Context) CXXReinterpretCastExpr(
133 DestType.getNonReferenceType(),
134 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000135
136 case tok::kw_static_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000137 if (!TypeDependent)
138 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000139 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +0000140 CastExpr::CK_Unknown, Ex,
141 DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000142 }
143
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000145}
146
Sebastian Redldb647282009-01-27 23:18:31 +0000147/// CastsAwayConstness - Check if the pointer conversion from SrcType to
148/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
149/// the cast checkers. Both arguments must denote pointer (possibly to member)
150/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000151bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000152CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000153{
Sebastian Redldb647282009-01-27 23:18:31 +0000154 // Casting away constness is defined in C++ 5.2.11p8 with reference to
155 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
156 // the rules are non-trivial. So first we construct Tcv *...cv* as described
157 // in C++ 5.2.11p8.
158 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
159 "Source type is not pointer or pointer to member.");
160 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
161 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000162
163 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
164 llvm::SmallVector<unsigned, 8> cv1, cv2;
165
166 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000167 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000168 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
169 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
170 }
171 assert(cv1.size() > 0 && "Must have at least one pointer level.");
172
173 // Construct void pointers with those qualifiers (in reverse order of
174 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000175 QualType SrcConstruct = Self.Context.VoidTy;
176 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000177 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
178 i2 = cv2.rbegin();
179 i1 != cv1.rend(); ++i1, ++i2)
180 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000181 SrcConstruct = Self.Context.getPointerType(
182 SrcConstruct.getQualifiedType(*i1));
183 DestConstruct = Self.Context.getPointerType(
184 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000185 }
186
187 // Test if they're compatible.
188 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000189 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000190}
191
Sebastian Redl26d85b12008-11-05 21:50:06 +0000192/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
193/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
194/// checked downcasts in class hierarchies.
195void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000196CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
197 const SourceRange &OpRange,
198 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000199{
200 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000201 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000202
203 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
204 // or "pointer to cv void".
205
206 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000207 const PointerType *DestPointer = DestType->getAs<PointerType>();
208 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000209 if (DestPointer) {
210 DestPointee = DestPointer->getPointeeType();
211 } else if (DestReference) {
212 DestPointee = DestReference->getPointeeType();
213 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000214 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000215 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216 return;
217 }
218
Ted Kremenek6217b802009-07-29 21:53:49 +0000219 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000220 if (DestPointee->isVoidType()) {
221 assert(DestPointer && "Reference to void is not possible");
222 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000223 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000224 diag::err_bad_dynamic_cast_incomplete,
225 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000226 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000227 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000228 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000229 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000230 return;
231 }
232
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000233 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
234 // complete class type, [...]. If T is an lvalue reference type, v shall be
235 // an lvalue of a complete class type, [...]. If T is an rvalue reference
236 // type, v shall be an expression having a complete effective class type,
237 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000238
Sebastian Redl37d6de32008-11-08 13:00:26 +0000239 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000240 QualType SrcPointee;
241 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000242 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000243 SrcPointee = SrcPointer->getPointeeType();
244 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000245 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000246 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000247 return;
248 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000249 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000250 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000251 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000252 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000253 }
254 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000255 } else {
256 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000257 }
258
Ted Kremenek6217b802009-07-29 21:53:49 +0000259 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000260 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000261 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000262 diag::err_bad_dynamic_cast_incomplete,
263 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000264 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000265 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000266 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000267 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268 return;
269 }
270
271 assert((DestPointer || DestReference) &&
272 "Bad destination non-ptr/ref slipped through.");
273 assert((DestRecord || DestPointee->isVoidType()) &&
274 "Bad destination pointee slipped through.");
275 assert(SrcRecord && "Bad source pointee slipped through.");
276
277 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
278 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000279 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000280 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000281 return;
282 }
283
284 // C++ 5.2.7p3: If the type of v is the same as the required result type,
285 // [except for cv].
286 if (DestRecord == SrcRecord) {
287 return;
288 }
289
290 // C++ 5.2.7p5
291 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000292 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
293 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000294 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000295 // Diagnostic already emitted on error.
296 return;
297 }
298
299 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000300 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000301 assert(SrcDecl && "Definition missing");
302 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000303 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000304 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000305 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306
307 // Done. Everything else is run-time checks.
308}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000309
310/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
311/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
312/// like this:
313/// const char *str = "literal";
314/// legacy_function(const_cast\<char*\>(str));
315void
316CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
317 const SourceRange &OpRange, const SourceRange &DestRange)
318{
319 if (!DestType->isLValueReferenceType())
320 Self.DefaultFunctionArrayConversion(SrcExpr);
321
322 unsigned msg = diag::err_bad_cxx_cast_generic;
323 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
324 && msg != 0)
325 Self.Diag(OpRange.getBegin(), msg) << CT_Const
326 << SrcExpr->getType() << DestType << OpRange;
327}
328
329/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
330/// valid.
331/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
332/// like this:
333/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
334void
335CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
336 const SourceRange &OpRange, const SourceRange &DestRange)
337{
338 if (!DestType->isLValueReferenceType())
339 Self.DefaultFunctionArrayConversion(SrcExpr);
340
341 unsigned msg = diag::err_bad_cxx_cast_generic;
342 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
343 != TC_Success && msg != 0)
344 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
345 << SrcExpr->getType() << DestType << OpRange;
346}
347
348
349/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
350/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
351/// implicit conversions explicit and getting rid of data loss warnings.
352void
353CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
354 const SourceRange &OpRange)
355{
356 // This test is outside everything else because it's the only case where
357 // a non-lvalue-reference target type does not lead to decay.
358 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
359 if (DestType->isVoidType()) {
360 return;
361 }
362
363 if (!DestType->isLValueReferenceType())
364 Self.DefaultFunctionArrayConversion(SrcExpr);
365
366 unsigned msg = diag::err_bad_cxx_cast_generic;
367 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
368 != TC_Success && msg != 0)
369 Self.Diag(OpRange.getBegin(), msg) << CT_Static
370 << SrcExpr->getType() << DestType << OpRange;
371}
372
373/// TryStaticCast - Check if a static cast can be performed, and do so if
374/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
375/// and casting away constness.
376static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
377 QualType DestType, bool CStyle,
378 const SourceRange &OpRange,
379 unsigned &msg)
380{
381 // The order the tests is not entirely arbitrary. There is one conversion
382 // that can be handled in two different ways. Given:
383 // struct A {};
384 // struct B : public A {
385 // B(); B(const A&);
386 // };
387 // const A &a = B();
388 // the cast static_cast<const B&>(a) could be seen as either a static
389 // reference downcast, or an explicit invocation of the user-defined
390 // conversion using B's conversion constructor.
391 // DR 427 specifies that the downcast is to be applied here.
392
393 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
394 // Done outside this function.
395
396 TryCastResult tcr;
397
398 // C++ 5.2.9p5, reference downcast.
399 // See the function for details.
400 // DR 427 specifies that this is to be applied before paragraph 2.
401 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
402 if (tcr != TC_NotApplicable)
403 return tcr;
404
405 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
406 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
407 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
408 if (tcr != TC_NotApplicable)
409 return tcr;
410
411 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
412 // [...] if the declaration "T t(e);" is well-formed, [...].
413 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg);
414 if (tcr != TC_NotApplicable)
415 return tcr;
416
417 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
418 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
419 // conversions, subject to further restrictions.
420 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
421 // of qualification conversions impossible.
422 // In the CStyle case, the earlier attempt to const_cast should have taken
423 // care of reverse qualification conversions.
424
425 QualType OrigSrcType = SrcExpr->getType();
426
427 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
428
429 // Reverse integral promotion/conversion. All such conversions are themselves
430 // again integral promotions or conversions and are thus already handled by
431 // p2 (TryDirectInitialization above).
432 // (Note: any data loss warnings should be suppressed.)
433 // The exception is the reverse of enum->integer, i.e. integer->enum (and
434 // enum->enum). See also C++ 5.2.9p7.
435 // The same goes for reverse floating point promotion/conversion and
436 // floating-integral conversions. Again, only floating->enum is relevant.
437 if (DestType->isEnumeralType()) {
438 if (SrcType->isComplexType() || SrcType->isVectorType()) {
439 // Fall through - these cannot be converted.
440 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
441 return TC_Success;
442 }
443
444 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
445 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
446 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
447 if (tcr != TC_NotApplicable)
448 return tcr;
449
450 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
451 // conversion. C++ 5.2.9p9 has additional information.
452 // DR54's access restrictions apply here also.
453 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
454 OpRange, msg);
455 if (tcr != TC_NotApplicable)
456 return tcr;
457
458 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
459 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
460 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000461 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000462 QualType SrcPointee = SrcPointer->getPointeeType();
463 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000464 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000465 QualType DestPointee = DestPointer->getPointeeType();
466 if (DestPointee->isIncompleteOrObjectType()) {
467 // This is definitely the intended conversion, but it might fail due
468 // to a const violation.
469 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
470 msg = diag::err_bad_cxx_cast_const_away;
471 return TC_Failed;
472 }
473 return TC_Success;
474 }
475 }
476 }
477 }
478
479 // We tried everything. Everything! Nothing works! :-(
480 return TC_NotApplicable;
481}
482
483/// Tests whether a conversion according to N2844 is valid.
484TryCastResult
485TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
486 unsigned &msg)
487{
488 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
489 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000490 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000491 if (!R)
492 return TC_NotApplicable;
493
494 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
495 return TC_NotApplicable;
496
497 // Because we try the reference downcast before this function, from now on
498 // this is the only cast possibility, so we issue an error if we fail now.
499 // FIXME: Should allow casting away constness if CStyle.
500 bool DerivedToBase;
501 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
502 DerivedToBase) <
503 Sema::Ref_Compatible_With_Added_Qualification) {
504 msg = diag::err_bad_lvalue_to_rvalue_cast;
505 return TC_Failed;
506 }
507
508 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
509 // than nothing.
510 return TC_Success;
511}
512
513/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
514TryCastResult
515TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
516 bool CStyle, const SourceRange &OpRange,
517 unsigned &msg)
518{
519 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
520 // cast to type "reference to cv2 D", where D is a class derived from B,
521 // if a valid standard conversion from "pointer to D" to "pointer to B"
522 // exists, cv2 >= cv1, and B is not a virtual base class of D.
523 // In addition, DR54 clarifies that the base must be accessible in the
524 // current context. Although the wording of DR54 only applies to the pointer
525 // variant of this rule, the intent is clearly for it to apply to the this
526 // conversion as well.
527
Ted Kremenek6217b802009-07-29 21:53:49 +0000528 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000529 if (!DestReference) {
530 return TC_NotApplicable;
531 }
532 bool RValueRef = DestReference->isRValueReferenceType();
533 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
534 // We know the left side is an lvalue reference, so we can suggest a reason.
535 msg = diag::err_bad_cxx_cast_rvalue;
536 return TC_NotApplicable;
537 }
538
539 QualType DestPointee = DestReference->getPointeeType();
540
541 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
542 OpRange, SrcExpr->getType(), DestType, msg);
543}
544
545/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
546TryCastResult
547TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
548 bool CStyle, const SourceRange &OpRange, unsigned &msg)
549{
550 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
551 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
552 // is a class derived from B, if a valid standard conversion from "pointer
553 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
554 // class of D.
555 // In addition, DR54 clarifies that the base must be accessible in the
556 // current context.
557
Ted Kremenek6217b802009-07-29 21:53:49 +0000558 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000559 if (!DestPointer) {
560 return TC_NotApplicable;
561 }
562
Ted Kremenek6217b802009-07-29 21:53:49 +0000563 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000564 if (!SrcPointer) {
565 msg = diag::err_bad_static_cast_pointer_nonpointer;
566 return TC_NotApplicable;
567 }
568
569 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
570 DestPointer->getPointeeType(), CStyle,
571 OpRange, SrcType, DestType, msg);
572}
573
574/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
575/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
576/// DestType, both of which must be canonical, is possible and allowed.
577TryCastResult
578TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
579 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
580 QualType OrigDestType, unsigned &msg)
581{
582 // Downcast can only happen in class hierarchies, so we need classes.
583 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
584 return TC_NotApplicable;
585 }
586
587 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
588 /*DetectVirtual=*/true);
589 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
590 return TC_NotApplicable;
591 }
592
593 // Target type does derive from source type. Now we're serious. If an error
594 // appears now, it's not ignored.
595 // This may not be entirely in line with the standard. Take for example:
596 // struct A {};
597 // struct B : virtual A {
598 // B(A&);
599 // };
600 //
601 // void f()
602 // {
603 // (void)static_cast<const B&>(*((A*)0));
604 // }
605 // As far as the standard is concerned, p5 does not apply (A is virtual), so
606 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
607 // However, both GCC and Comeau reject this example, and accepting it would
608 // mean more complex code if we're to preserve the nice error message.
609 // FIXME: Being 100% compliant here would be nice to have.
610
611 // Must preserve cv, as always, unless we're in C-style mode.
612 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
613 msg = diag::err_bad_cxx_cast_const_away;
614 return TC_Failed;
615 }
616
617 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
618 // This code is analoguous to that in CheckDerivedToBaseConversion, except
619 // that it builds the paths in reverse order.
620 // To sum up: record all paths to the base and build a nice string from
621 // them. Use it to spice up the error message.
622 if (!Paths.isRecordingPaths()) {
623 Paths.clear();
624 Paths.setRecordingPaths(true);
625 Self.IsDerivedFrom(DestType, SrcType, Paths);
626 }
627 std::string PathDisplayStr;
628 std::set<unsigned> DisplayedPaths;
629 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
630 PI != PE; ++PI) {
631 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
632 // We haven't displayed a path to this particular base
633 // class subobject yet.
634 PathDisplayStr += "\n ";
635 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
636 EI != EE; ++EI)
637 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
638 PathDisplayStr += DestType.getAsString();
639 }
640 }
641
642 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
643 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
644 << PathDisplayStr << OpRange;
645 msg = 0;
646 return TC_Failed;
647 }
648
649 if (Paths.getDetectedVirtual() != 0) {
650 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
651 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
652 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
653 msg = 0;
654 return TC_Failed;
655 }
656
657 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
658 diag::err_downcast_from_inaccessible_base, Paths,
659 OpRange.getBegin(), DeclarationName())) {
660 msg = 0;
661 return TC_Failed;
662 }
663
664 return TC_Success;
665}
666
667/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
668/// C++ 5.2.9p9 is valid:
669///
670/// An rvalue of type "pointer to member of D of type cv1 T" can be
671/// converted to an rvalue of type "pointer to member of B of type cv2 T",
672/// where B is a base class of D [...].
673///
674TryCastResult
675TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
676 bool CStyle, const SourceRange &OpRange,
677 unsigned &msg)
678{
Ted Kremenek6217b802009-07-29 21:53:49 +0000679 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000680 if (!DestMemPtr)
681 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000682 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000683 if (!SrcMemPtr) {
684 msg = diag::err_bad_static_cast_member_pointer_nonmp;
685 return TC_NotApplicable;
686 }
687
688 // T == T, modulo cv
689 if (Self.Context.getCanonicalType(
690 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
691 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
692 getUnqualifiedType()))
693 return TC_NotApplicable;
694
695 // B base of D
696 QualType SrcClass(SrcMemPtr->getClass(), 0);
697 QualType DestClass(DestMemPtr->getClass(), 0);
698 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
699 /*DetectVirtual=*/true);
700 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
701 return TC_NotApplicable;
702 }
703
704 // B is a base of D. But is it an allowed base? If not, it's a hard error.
705 if (Paths.isAmbiguous(DestClass)) {
706 Paths.clear();
707 Paths.setRecordingPaths(true);
708 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
709 assert(StillOkay);
710 StillOkay = StillOkay;
711 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
712 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
713 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
714 msg = 0;
715 return TC_Failed;
716 }
717
718 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
719 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
720 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
721 msg = 0;
722 return TC_Failed;
723 }
724
725 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
726 diag::err_downcast_from_inaccessible_base, Paths,
727 OpRange.getBegin(), DeclarationName())) {
728 msg = 0;
729 return TC_Failed;
730 }
731
732 return TC_Success;
733}
734
735/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
736/// is valid:
737///
738/// An expression e can be explicitly converted to a type T using a
739/// @c static_cast if the declaration "T t(e);" is well-formed [...].
740TryCastResult
741TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
742 bool CStyle, const SourceRange &OpRange, unsigned &msg)
743{
744 if (DestType->isReferenceType()) {
745 // At this point of CheckStaticCast, if the destination is a reference,
746 // this has to work. There is no other way that works.
747 // On the other hand, if we're checking a C-style cast, we've still got
748 // the reinterpret_cast way. In that case, we pass an ICS so we don't
749 // get error messages.
750 ImplicitConversionSequence ICS;
751 bool failed = Self.CheckReferenceInit(SrcExpr, DestType, CStyle ? &ICS : 0);
752 if (!failed)
753 return TC_Success;
754 if (CStyle)
755 return TC_NotApplicable;
756 // If we didn't pass the ICS, we already got an error message.
757 msg = 0;
758 return TC_Failed;
759 }
760 if (DestType->isRecordType()) {
761 // There are no further possibilities for the target type being a class,
762 // neither in static_cast nor in a C-style cast. So we can fail here.
763 // FIXME: We need to store this constructor in the AST.
764 if (Self.PerformInitializationByConstructor(DestType, &SrcExpr, 1,
765 OpRange.getBegin(), OpRange, DeclarationName(), Sema::IK_Direct))
766 return TC_Success;
767 // The function already emitted an error.
768 msg = 0;
769 return TC_Failed;
770 }
771
772 // FIXME: To get a proper error from invalid conversions here, we need to
773 // reimplement more of this.
774 // FIXME: This does not actually perform the conversion, and thus does not
775 // check for ambiguity or access.
776 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
777 SrcExpr, DestType);
778 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
779 TC_NotApplicable : TC_Success;
780}
781
782/// TryConstCast - See if a const_cast from source to destination is allowed,
783/// and perform it if it is.
784static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
785 bool CStyle, unsigned &msg) {
786 DestType = Self.Context.getCanonicalType(DestType);
787 QualType SrcType = SrcExpr->getType();
788 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000789 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000790 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
791 // Cannot const_cast non-lvalue to lvalue reference type. But if this
792 // is C-style, static_cast might find a way, so we simply suggest a
793 // message and tell the parent to keep searching.
794 msg = diag::err_bad_cxx_cast_rvalue;
795 return TC_NotApplicable;
796 }
797
798 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
799 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
800 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
801 SrcType = Self.Context.getPointerType(SrcType);
802 }
803
804 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
805 // the rules for const_cast are the same as those used for pointers.
806
807 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
808 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
809 // was a reference type, we converted it to a pointer above.
810 // The status of rvalue references isn't entirely clear, but it looks like
811 // conversion to them is simply invalid.
812 // C++ 5.2.11p3: For two pointer types [...]
813 if (!CStyle)
814 msg = diag::err_bad_const_cast_dest;
815 return TC_NotApplicable;
816 }
817 if (DestType->isFunctionPointerType() ||
818 DestType->isMemberFunctionPointerType()) {
819 // Cannot cast direct function pointers.
820 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
821 // T is the ultimate pointee of source and target type.
822 if (!CStyle)
823 msg = diag::err_bad_const_cast_dest;
824 return TC_NotApplicable;
825 }
826 SrcType = Self.Context.getCanonicalType(SrcType);
827
828 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
829 // completely equal.
830 // FIXME: const_cast should probably not be able to convert between pointers
831 // to different address spaces.
832 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
833 // in multi-level pointers may change, but the level count must be the same,
834 // as must be the final pointee type.
835 while (SrcType != DestType &&
836 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
837 SrcType = SrcType.getUnqualifiedType();
838 DestType = DestType.getUnqualifiedType();
839 }
840
841 // Since we're dealing in canonical types, the remainder must be the same.
842 if (SrcType != DestType)
843 return TC_NotApplicable;
844
845 return TC_Success;
846}
847
848static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
849 QualType DestType, bool CStyle,
850 const SourceRange &OpRange,
851 unsigned &msg) {
852 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
853
854 DestType = Self.Context.getCanonicalType(DestType);
855 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000856 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000857 bool LValue = DestTypeTmp->isLValueReferenceType();
858 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
859 // Cannot cast non-lvalue to reference type. See the similar comment in
860 // const_cast.
861 msg = diag::err_bad_cxx_cast_rvalue;
862 return TC_NotApplicable;
863 }
864
865 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
866 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
867 // built-in & and * operators.
868 // This code does this transformation for the checked types.
869 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
870 SrcType = Self.Context.getPointerType(SrcType);
871 }
872
873 // Canonicalize source for comparison.
874 SrcType = Self.Context.getCanonicalType(SrcType);
875
Ted Kremenek6217b802009-07-29 21:53:49 +0000876 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
877 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000878 if (DestMemPtr && SrcMemPtr) {
879 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
880 // can be explicitly converted to an rvalue of type "pointer to member
881 // of Y of type T2" if T1 and T2 are both function types or both object
882 // types.
883 if (DestMemPtr->getPointeeType()->isFunctionType() !=
884 SrcMemPtr->getPointeeType()->isFunctionType())
885 return TC_NotApplicable;
886
887 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
888 // constness.
889 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
890 // we accept it.
891 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
892 msg = diag::err_bad_cxx_cast_const_away;
893 return TC_Failed;
894 }
895
896 // A valid member pointer cast.
897 return TC_Success;
898 }
899
900 // See below for the enumeral issue.
901 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
902 !DestType->isEnumeralType()) {
903 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
904 // type large enough to hold it. A value of std::nullptr_t can be
905 // converted to an integral type; the conversion has the same meaning
906 // and validity as a conversion of (void*)0 to the integral type.
907 if (Self.Context.getTypeSize(SrcType) >
908 Self.Context.getTypeSize(DestType)) {
909 msg = diag::err_bad_reinterpret_cast_small_int;
910 return TC_Failed;
911 }
912 return TC_Success;
913 }
914
915 bool destIsPtr = DestType->isPointerType();
916 bool srcIsPtr = SrcType->isPointerType();
917 if (!destIsPtr && !srcIsPtr) {
918 // Except for std::nullptr_t->integer and lvalue->reference, which are
919 // handled above, at least one of the two arguments must be a pointer.
920 return TC_NotApplicable;
921 }
922
923 if (SrcType == DestType) {
924 // C++ 5.2.10p2 has a note that mentions that, subject to all other
925 // restrictions, a cast to the same type is allowed. The intent is not
926 // entirely clear here, since all other paragraphs explicitly forbid casts
927 // to the same type. However, the behavior of compilers is pretty consistent
928 // on this point: allow same-type conversion if the involved types are
929 // pointers, disallow otherwise.
930 return TC_Success;
931 }
932
933 // Note: Clang treats enumeration types as integral types. If this is ever
934 // changed for C++, the additional check here will be redundant.
935 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
936 assert(srcIsPtr && "One type must be a pointer");
937 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
938 // type large enough to hold it.
939 if (Self.Context.getTypeSize(SrcType) >
940 Self.Context.getTypeSize(DestType)) {
941 msg = diag::err_bad_reinterpret_cast_small_int;
942 return TC_Failed;
943 }
944 return TC_Success;
945 }
946
947 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
948 assert(destIsPtr && "One type must be a pointer");
949 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
950 // converted to a pointer.
951 return TC_Success;
952 }
953
954 if (!destIsPtr || !srcIsPtr) {
955 // With the valid non-pointer conversions out of the way, we can be even
956 // more stringent.
957 return TC_NotApplicable;
958 }
959
960 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
961 // The C-style cast operator can.
962 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
963 msg = diag::err_bad_cxx_cast_const_away;
964 return TC_Failed;
965 }
966
967 // Not casting away constness, so the only remaining check is for compatible
968 // pointer categories.
969
970 if (SrcType->isFunctionPointerType()) {
971 if (DestType->isFunctionPointerType()) {
972 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
973 // a pointer to a function of a different type.
974 return TC_Success;
975 }
976
977 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
978 // an object type or vice versa is conditionally-supported.
979 // Compilers support it in C++03 too, though, because it's necessary for
980 // casting the return value of dlsym() and GetProcAddress().
981 // FIXME: Conditionally-supported behavior should be configurable in the
982 // TargetInfo or similar.
983 if (!Self.getLangOptions().CPlusPlus0x)
984 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
985 return TC_Success;
986 }
987
988 if (DestType->isFunctionPointerType()) {
989 // See above.
990 if (!Self.getLangOptions().CPlusPlus0x)
991 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
992 return TC_Success;
993 }
994
995 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
996 // a pointer to an object of different type.
997 // Void pointers are not specified, but supported by every compiler out there.
998 // So we finish by allowing everything that remains - it's got to be two
999 // object pointers.
1000 return TC_Success;
1001}
1002
1003
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001004bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
1005 bool FunctionalStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001006{
1007 // This test is outside everything else because it's the only case where
1008 // a non-lvalue-reference target type does not lead to decay.
1009 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1010 if (CastTy->isVoidType())
1011 return false;
1012
1013 // If the type is dependent, we won't do any other semantic analysis now.
1014 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1015 return false;
1016
1017 if (!CastTy->isLValueReferenceType())
1018 DefaultFunctionArrayConversion(CastExpr);
1019
1020 // C++ [expr.cast]p5: The conversions performed by
1021 // - a const_cast,
1022 // - a static_cast,
1023 // - a static_cast followed by a const_cast,
1024 // - a reinterpret_cast, or
1025 // - a reinterpret_cast followed by a const_cast,
1026 // can be performed using the cast notation of explicit type conversion.
1027 // [...] If a conversion can be interpreted in more than one of the ways
1028 // listed above, the interpretation that appears first in the list is used,
1029 // even if a cast resulting from that interpretation is ill-formed.
1030 // In plain language, this means trying a const_cast ...
1031 unsigned msg = diag::err_bad_cxx_cast_generic;
1032 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,msg);
1033 if (tcr == TC_NotApplicable) {
1034 // ... or if that is not possible, a static_cast, ignoring const, ...
1035 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
1036 if (tcr == TC_NotApplicable) {
1037 // ... and finally a reinterpret_cast, ignoring const.
1038 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
1039 }
1040 }
1041
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001042 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001043 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001044 << CastExpr->getType() << CastTy << R;
1045
1046 return tcr != TC_Success;
1047}