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