blob: ac85b79b390b2f85e4333e9c2c197d1521879aff [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"
Anders Carlssona21e7872009-08-26 23:45:07 +000018#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000019#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl0e35d042009-07-25 15:41:38 +000023enum TryCastResult {
24 TC_NotApplicable, ///< The cast method is not applicable.
25 TC_Success, ///< The cast method is appropriate and successful.
26 TC_Failed ///< The cast method is appropriate, but failed. A
27 ///< diagnostic has been emitted.
28};
29
30enum CastType {
31 CT_Const, ///< const_cast
32 CT_Static, ///< static_cast
33 CT_Reinterpret, ///< reinterpret_cast
34 CT_Dynamic, ///< dynamic_cast
35 CT_CStyle, ///< (Type)expr
36 CT_Functional ///< Type(expr)
Sebastian Redlf831eeb2008-11-08 13:00:26 +000037};
38
39static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
40 const SourceRange &OpRange,
41 const SourceRange &DestRange);
42static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
43 const SourceRange &OpRange,
44 const SourceRange &DestRange);
45static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson9583fa72009-08-07 22:21:05 +000046 const SourceRange &OpRange,
47 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000048static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
49 const SourceRange &OpRange,
Mike Stump25cf7602009-09-09 15:08:12 +000050 const SourceRange &DestRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +000051 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000052
53static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl0e35d042009-07-25 15:41:38 +000054
55// The Try functions attempt a specific way of casting. If they succeed, they
56// return TC_Success. If their way of casting is not appropriate for the given
57// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
58// to emit if no other way succeeds. If their way of casting is appropriate but
59// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
60// they emit a specialized diagnostic.
61// All diagnostics returned by these functions must expect the same three
62// arguments:
63// %0: Cast Type (a value from the CastType enumeration)
64// %1: Source Type
65// %2: Destination Type
66static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
67 QualType DestType, unsigned &msg);
68static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
69 QualType DestType, bool CStyle,
70 const SourceRange &OpRange,
71 unsigned &msg);
72static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
73 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
75 unsigned &msg);
76static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
77 QualType DestType, bool CStyle,
78 const SourceRange &OpRange,
79 QualType OrigSrcType,
80 QualType OrigDestType, unsigned &msg);
81static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
82 QualType DestType,bool CStyle,
83 const SourceRange &OpRange,
84 unsigned &msg);
85static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
86 QualType DestType, bool CStyle,
87 const SourceRange &OpRange,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +000088 unsigned &msg,
89 CXXMethodDecl *&ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +000090static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
91 QualType DestType, bool CStyle,
Mike Stump25cf7602009-09-09 15:08:12 +000092 CastExpr::CastKind &Kind,
Sebastian Redl0e35d042009-07-25 15:41:38 +000093 const SourceRange &OpRange,
Anders Carlssonf1957c82009-09-01 20:52:42 +000094 unsigned &msg,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +000095 CXXMethodDecl *&ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +000096static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
97 bool CStyle, unsigned &msg);
98static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
99 QualType DestType, bool CStyle,
Mike Stump25cf7602009-09-09 15:08:12 +0000100 CastExpr::CastKind &Kind,
Sebastian Redl0e35d042009-07-25 15:41:38 +0000101 const SourceRange &OpRange,
102 unsigned &msg);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000103
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000104/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000105Action::OwningExprResult
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000106Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
107 SourceLocation LAngleBracketLoc, TypeTy *Ty,
108 SourceLocation RAngleBracketLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000109 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000110 SourceLocation RParenLoc) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000111 Expr *Ex = E.takeAs<Expr>();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000112 // FIXME: Preserve type source info.
113 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000114 SourceRange OpRange(OpLoc, RParenLoc);
115 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
116
Douglas Gregore6be68a2008-12-17 22:52:20 +0000117 // If the type is dependent, we won't do the semantic analysis now.
118 // FIXME: should we check this in a more fine-grained manner?
119 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
120
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000121 switch (Kind) {
122 default: assert(0 && "Unknown C++ cast!");
123
124 case tok::kw_const_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000125 if (!TypeDependent)
126 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000127 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
128 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000129
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000130 case tok::kw_dynamic_cast: {
131 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000132 if (!TypeDependent)
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000133 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000134 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000135 Kind, Ex, DestType, OpLoc));
136 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000137 case tok::kw_reinterpret_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000138 if (!TypeDependent)
139 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXReinterpretCastExpr(
141 DestType.getNonReferenceType(),
142 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000143
Anders Carlsson9583fa72009-08-07 22:21:05 +0000144 case tok::kw_static_cast: {
145 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000146 if (!TypeDependent)
Anders Carlsson9583fa72009-08-07 22:21:05 +0000147 CheckStaticCast(*this, Ex, DestType, OpRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000148 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +0000149 Kind, Ex, DestType, OpLoc));
150 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000151 }
152
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000153 return ExprError();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000154}
155
Sebastian Redl04b3f352009-01-27 23:18:31 +0000156/// CastsAwayConstness - Check if the pointer conversion from SrcType to
157/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
158/// the cast checkers. Both arguments must denote pointer (possibly to member)
159/// types.
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000160bool
Mike Stump25cf7602009-09-09 15:08:12 +0000161CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redl04b3f352009-01-27 23:18:31 +0000162 // Casting away constness is defined in C++ 5.2.11p8 with reference to
163 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
164 // the rules are non-trivial. So first we construct Tcv *...cv* as described
165 // in C++ 5.2.11p8.
166 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
167 "Source type is not pointer or pointer to member.");
168 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
169 "Destination type is not pointer or pointer to member.");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000170
171 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
172 llvm::SmallVector<unsigned, 8> cv1, cv2;
173
174 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000175 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000176 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
177 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
178 }
179 assert(cv1.size() > 0 && "Must have at least one pointer level.");
180
181 // Construct void pointers with those qualifiers (in reverse order of
182 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000183 QualType SrcConstruct = Self.Context.VoidTy;
184 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000185 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
186 i2 = cv2.rbegin();
Mike Stump25cf7602009-09-09 15:08:12 +0000187 i1 != cv1.rend(); ++i1, ++i2) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000188 SrcConstruct = Self.Context.getPointerType(
189 SrcConstruct.getQualifiedType(*i1));
190 DestConstruct = Self.Context.getPointerType(
191 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000192 }
193
194 // Test if they're compatible.
195 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000196 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000197}
198
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000199/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
200/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
201/// checked downcasts in class hierarchies.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000202static void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000203CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
204 const SourceRange &OpRange,
Mike Stump25cf7602009-09-09 15:08:12 +0000205 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000206 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000207 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000208
209 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
210 // or "pointer to cv void".
211
212 QualType DestPointee;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000213 const PointerType *DestPointer = DestType->getAs<PointerType>();
214 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000215 if (DestPointer) {
216 DestPointee = DestPointer->getPointeeType();
217 } else if (DestReference) {
218 DestPointee = DestReference->getPointeeType();
219 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000220 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000221 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000222 return;
223 }
224
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000225 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000226 if (DestPointee->isVoidType()) {
227 assert(DestPointer && "Reference to void is not possible");
228 } else if (DestRecord) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000229 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssona21e7872009-08-26 23:45:07 +0000230 PDiag(diag::err_bad_dynamic_cast_incomplete)
231 << DestRange))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000232 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000233 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000234 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000235 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000236 return;
237 }
238
Sebastian Redlce6fff02009-03-16 23:22:08 +0000239 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
240 // complete class type, [...]. If T is an lvalue reference type, v shall be
241 // an lvalue of a complete class type, [...]. If T is an rvalue reference
242 // type, v shall be an expression having a complete effective class type,
243 // [...]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000244
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000245 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000246 QualType SrcPointee;
247 if (DestPointer) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000248 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000249 SrcPointee = SrcPointer->getPointeeType();
250 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000251 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000252 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000253 return;
254 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000255 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000256 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000257 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000258 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000259 }
260 SrcPointee = SrcType;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000261 } else {
262 SrcPointee = SrcType;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000263 }
264
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000265 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000266 if (SrcRecord) {
Douglas Gregorc84d8932009-03-09 16:13:40 +0000267 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssona21e7872009-08-26 23:45:07 +0000268 PDiag(diag::err_bad_dynamic_cast_incomplete)
269 << SrcExpr->getSourceRange()))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000270 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000271 } else {
Chris Lattner77d52da2008-11-20 06:06:08 +0000272 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000273 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000274 return;
275 }
276
277 assert((DestPointer || DestReference) &&
278 "Bad destination non-ptr/ref slipped through.");
279 assert((DestRecord || DestPointee->isVoidType()) &&
280 "Bad destination pointee slipped through.");
281 assert(SrcRecord && "Bad source pointee slipped through.");
282
283 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
284 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000285 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000286 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000287 return;
288 }
289
290 // C++ 5.2.7p3: If the type of v is the same as the required result type,
291 // [except for cv].
292 if (DestRecord == SrcRecord) {
293 return;
294 }
295
296 // C++ 5.2.7p5
297 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000298 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
299 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner4bfd2232008-11-24 06:25:27 +0000300 OpRange.getBegin(), OpRange);
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000301 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000302 // Diagnostic already emitted on error.
303 return;
304 }
305
306 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000307 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000308 assert(SrcDecl && "Definition missing");
309 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner77d52da2008-11-20 06:06:08 +0000310 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000311 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000312 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000313
314 // Done. Everything else is run-time checks.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000315 Kind = CastExpr::CK_Dynamic;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000316}
Sebastian Redl0e35d042009-07-25 15:41:38 +0000317
318/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
319/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
320/// like this:
321/// const char *str = "literal";
322/// legacy_function(const_cast\<char*\>(str));
323void
324CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump25cf7602009-09-09 15:08:12 +0000325 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000326 if (!DestType->isLValueReferenceType())
327 Self.DefaultFunctionArrayConversion(SrcExpr);
328
329 unsigned msg = diag::err_bad_cxx_cast_generic;
330 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
331 && msg != 0)
332 Self.Diag(OpRange.getBegin(), msg) << CT_Const
333 << SrcExpr->getType() << DestType << OpRange;
334}
335
336/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
337/// valid.
338/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
339/// like this:
340/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
341void
342CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump25cf7602009-09-09 15:08:12 +0000343 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000344 if (!DestType->isLValueReferenceType())
345 Self.DefaultFunctionArrayConversion(SrcExpr);
346
Anders Carlssonf1957c82009-09-01 20:52:42 +0000347 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl0e35d042009-07-25 15:41:38 +0000348 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1957c82009-09-01 20:52:42 +0000349 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
350 OpRange, msg)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000351 != TC_Success && msg != 0)
352 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
353 << SrcExpr->getType() << DestType << OpRange;
354}
355
356
357/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
358/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
359/// implicit conversions explicit and getting rid of data loss warnings.
360void
361CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump25cf7602009-09-09 15:08:12 +0000362 const SourceRange &OpRange, CastExpr::CastKind &Kind) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000363 // This test is outside everything else because it's the only case where
364 // a non-lvalue-reference target type does not lead to decay.
365 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
366 if (DestType->isVoidType()) {
367 return;
368 }
369
370 if (!DestType->isLValueReferenceType())
371 Self.DefaultFunctionArrayConversion(SrcExpr);
372
373 unsigned msg = diag::err_bad_cxx_cast_generic;
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000374 CXXMethodDecl *ConversionDecl = 0;
Mike Stump25cf7602009-09-09 15:08:12 +0000375 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
Anders Carlssonf1957c82009-09-01 20:52:42 +0000376 OpRange, msg, ConversionDecl)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000377 != TC_Success && msg != 0)
378 Self.Diag(OpRange.getBegin(), msg) << CT_Static
379 << SrcExpr->getType() << DestType << OpRange;
380}
381
382/// TryStaticCast - Check if a static cast can be performed, and do so if
383/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
384/// and casting away constness.
385static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
386 QualType DestType, bool CStyle,
Mike Stump25cf7602009-09-09 15:08:12 +0000387 CastExpr::CastKind &Kind,
Anders Carlssonf1957c82009-09-01 20:52:42 +0000388 const SourceRange &OpRange, unsigned &msg,
Mike Stump25cf7602009-09-09 15:08:12 +0000389 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000390 // The order the tests is not entirely arbitrary. There is one conversion
391 // that can be handled in two different ways. Given:
392 // struct A {};
393 // struct B : public A {
394 // B(); B(const A&);
395 // };
396 // const A &a = B();
397 // the cast static_cast<const B&>(a) could be seen as either a static
398 // reference downcast, or an explicit invocation of the user-defined
399 // conversion using B's conversion constructor.
400 // DR 427 specifies that the downcast is to be applied here.
401
402 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
403 // Done outside this function.
404
405 TryCastResult tcr;
406
407 // C++ 5.2.9p5, reference downcast.
408 // See the function for details.
409 // DR 427 specifies that this is to be applied before paragraph 2.
410 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
411 if (tcr != TC_NotApplicable)
412 return tcr;
413
414 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
415 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
416 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
417 if (tcr != TC_NotApplicable)
418 return tcr;
419
420 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
421 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000422 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
423 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +0000424 if (tcr != TC_NotApplicable)
425 return tcr;
426
427 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
428 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
429 // conversions, subject to further restrictions.
430 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
431 // of qualification conversions impossible.
432 // In the CStyle case, the earlier attempt to const_cast should have taken
433 // care of reverse qualification conversions.
434
435 QualType OrigSrcType = SrcExpr->getType();
436
437 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
438
439 // Reverse integral promotion/conversion. All such conversions are themselves
440 // again integral promotions or conversions and are thus already handled by
441 // p2 (TryDirectInitialization above).
442 // (Note: any data loss warnings should be suppressed.)
443 // The exception is the reverse of enum->integer, i.e. integer->enum (and
444 // enum->enum). See also C++ 5.2.9p7.
445 // The same goes for reverse floating point promotion/conversion and
446 // floating-integral conversions. Again, only floating->enum is relevant.
447 if (DestType->isEnumeralType()) {
448 if (SrcType->isComplexType() || SrcType->isVectorType()) {
449 // Fall through - these cannot be converted.
450 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
451 return TC_Success;
452 }
453
454 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
455 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
456 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
457 if (tcr != TC_NotApplicable)
458 return tcr;
459
460 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
461 // conversion. C++ 5.2.9p9 has additional information.
462 // DR54's access restrictions apply here also.
463 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
464 OpRange, msg);
465 if (tcr != TC_NotApplicable)
466 return tcr;
467
468 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
469 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
470 // just the usual constness stuff.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000471 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000472 QualType SrcPointee = SrcPointer->getPointeeType();
473 if (SrcPointee->isVoidType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000474 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000475 QualType DestPointee = DestPointer->getPointeeType();
476 if (DestPointee->isIncompleteOrObjectType()) {
477 // This is definitely the intended conversion, but it might fail due
478 // to a const violation.
479 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
480 msg = diag::err_bad_cxx_cast_const_away;
481 return TC_Failed;
482 }
483 return TC_Success;
484 }
485 }
486 }
487 }
488
489 // We tried everything. Everything! Nothing works! :-(
490 return TC_NotApplicable;
491}
492
493/// Tests whether a conversion according to N2844 is valid.
494TryCastResult
495TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump25cf7602009-09-09 15:08:12 +0000496 unsigned &msg) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000497 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
498 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000499 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000500 if (!R)
501 return TC_NotApplicable;
502
503 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
504 return TC_NotApplicable;
505
506 // Because we try the reference downcast before this function, from now on
507 // this is the only cast possibility, so we issue an error if we fail now.
508 // FIXME: Should allow casting away constness if CStyle.
509 bool DerivedToBase;
510 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
511 DerivedToBase) <
512 Sema::Ref_Compatible_With_Added_Qualification) {
513 msg = diag::err_bad_lvalue_to_rvalue_cast;
514 return TC_Failed;
515 }
516
517 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
518 // than nothing.
519 return TC_Success;
520}
521
522/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
523TryCastResult
524TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
525 bool CStyle, const SourceRange &OpRange,
Mike Stump25cf7602009-09-09 15:08:12 +0000526 unsigned &msg) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000527 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
528 // cast to type "reference to cv2 D", where D is a class derived from B,
529 // if a valid standard conversion from "pointer to D" to "pointer to B"
530 // exists, cv2 >= cv1, and B is not a virtual base class of D.
531 // In addition, DR54 clarifies that the base must be accessible in the
532 // current context. Although the wording of DR54 only applies to the pointer
533 // variant of this rule, the intent is clearly for it to apply to the this
534 // conversion as well.
535
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000536 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000537 if (!DestReference) {
538 return TC_NotApplicable;
539 }
540 bool RValueRef = DestReference->isRValueReferenceType();
541 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
542 // We know the left side is an lvalue reference, so we can suggest a reason.
543 msg = diag::err_bad_cxx_cast_rvalue;
544 return TC_NotApplicable;
545 }
546
547 QualType DestPointee = DestReference->getPointeeType();
548
549 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
550 OpRange, SrcExpr->getType(), DestType, msg);
551}
552
553/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
554TryCastResult
555TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump25cf7602009-09-09 15:08:12 +0000556 bool CStyle, const SourceRange &OpRange,
557 unsigned &msg) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000558 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
559 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
560 // is a class derived from B, if a valid standard conversion from "pointer
561 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
562 // class of D.
563 // In addition, DR54 clarifies that the base must be accessible in the
564 // current context.
565
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000566 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000567 if (!DestPointer) {
568 return TC_NotApplicable;
569 }
570
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000571 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000572 if (!SrcPointer) {
573 msg = diag::err_bad_static_cast_pointer_nonpointer;
574 return TC_NotApplicable;
575 }
576
577 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
578 DestPointer->getPointeeType(), CStyle,
579 OpRange, SrcType, DestType, msg);
580}
581
582/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
583/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
584/// DestType, both of which must be canonical, is possible and allowed.
585TryCastResult
586TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
587 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump25cf7602009-09-09 15:08:12 +0000588 QualType OrigDestType, unsigned &msg) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000589 // Downcast can only happen in class hierarchies, so we need classes.
590 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
591 return TC_NotApplicable;
592 }
593
594 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
595 /*DetectVirtual=*/true);
596 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
597 return TC_NotApplicable;
598 }
599
600 // Target type does derive from source type. Now we're serious. If an error
601 // appears now, it's not ignored.
602 // This may not be entirely in line with the standard. Take for example:
603 // struct A {};
604 // struct B : virtual A {
605 // B(A&);
606 // };
Mike Stump25cf7602009-09-09 15:08:12 +0000607 //
Sebastian Redl0e35d042009-07-25 15:41:38 +0000608 // void f()
609 // {
610 // (void)static_cast<const B&>(*((A*)0));
611 // }
612 // As far as the standard is concerned, p5 does not apply (A is virtual), so
613 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
614 // However, both GCC and Comeau reject this example, and accepting it would
615 // mean more complex code if we're to preserve the nice error message.
616 // FIXME: Being 100% compliant here would be nice to have.
617
618 // Must preserve cv, as always, unless we're in C-style mode.
619 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
620 msg = diag::err_bad_cxx_cast_const_away;
621 return TC_Failed;
622 }
623
624 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
625 // This code is analoguous to that in CheckDerivedToBaseConversion, except
626 // that it builds the paths in reverse order.
627 // To sum up: record all paths to the base and build a nice string from
628 // them. Use it to spice up the error message.
629 if (!Paths.isRecordingPaths()) {
630 Paths.clear();
631 Paths.setRecordingPaths(true);
632 Self.IsDerivedFrom(DestType, SrcType, Paths);
633 }
634 std::string PathDisplayStr;
635 std::set<unsigned> DisplayedPaths;
636 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
637 PI != PE; ++PI) {
638 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
639 // We haven't displayed a path to this particular base
640 // class subobject yet.
641 PathDisplayStr += "\n ";
642 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
643 EI != EE; ++EI)
644 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
645 PathDisplayStr += DestType.getAsString();
646 }
647 }
648
649 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
650 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
651 << PathDisplayStr << OpRange;
652 msg = 0;
653 return TC_Failed;
654 }
655
656 if (Paths.getDetectedVirtual() != 0) {
657 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
658 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
659 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
660 msg = 0;
661 return TC_Failed;
662 }
663
664 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
665 diag::err_downcast_from_inaccessible_base, Paths,
666 OpRange.getBegin(), DeclarationName())) {
667 msg = 0;
668 return TC_Failed;
669 }
670
671 return TC_Success;
672}
673
674/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
675/// C++ 5.2.9p9 is valid:
676///
677/// An rvalue of type "pointer to member of D of type cv1 T" can be
678/// converted to an rvalue of type "pointer to member of B of type cv2 T",
679/// where B is a base class of D [...].
680///
681TryCastResult
682TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
683 bool CStyle, const SourceRange &OpRange,
Mike Stump25cf7602009-09-09 15:08:12 +0000684 unsigned &msg) {
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,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000748 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Mike Stump25cf7602009-09-09 15:08:12 +0000749 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond23693c2009-09-07 18:25:47 +0000750 if (DestType->isRecordType()) {
751 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
752 diag::err_bad_dynamic_cast_incomplete)) {
753 msg = 0;
754 return TC_Failed;
755 }
756 }
Mike Stump25cf7602009-09-09 15:08:12 +0000757
Sebastian Redl0e35d042009-07-25 15:41:38 +0000758 if (DestType->isReferenceType()) {
759 // At this point of CheckStaticCast, if the destination is a reference,
760 // this has to work. There is no other way that works.
761 // On the other hand, if we're checking a C-style cast, we've still got
762 // the reinterpret_cast way. In that case, we pass an ICS so we don't
763 // get error messages.
764 ImplicitConversionSequence ICS;
Mike Stump25cf7602009-09-09 15:08:12 +0000765 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Anders Carlsson8f809f92009-08-27 17:30:43 +0000766 /*SuppressUserConversions=*/false,
767 /*AllowExplicit=*/false,
768 /*ForceRValue=*/false,
769 CStyle ? &ICS : 0);
Sebastian Redl0e35d042009-07-25 15:41:38 +0000770 if (!failed)
771 return TC_Success;
772 if (CStyle)
773 return TC_NotApplicable;
774 // If we didn't pass the ICS, we already got an error message.
775 msg = 0;
776 return TC_Failed;
777 }
Sebastian Redl0e35d042009-07-25 15:41:38 +0000778
779 // FIXME: To get a proper error from invalid conversions here, we need to
780 // reimplement more of this.
781 // FIXME: This does not actually perform the conversion, and thus does not
782 // check for ambiguity or access.
Mike Stump25cf7602009-09-09 15:08:12 +0000783 ImplicitConversionSequence ICS =
Anders Carlsson6ed4a612009-08-27 17:24:15 +0000784 Self.TryImplicitConversion(SrcExpr, DestType,
785 /*SuppressUserConversions=*/false,
Anders Carlssonca468502009-08-28 16:22:20 +0000786 /*AllowExplicit=*/true,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000787 /*ForceRValue=*/false,
788 /*InOverloadResolution=*/false);
Mike Stump25cf7602009-09-09 15:08:12 +0000789
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000790 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
Mike Stump25cf7602009-09-09 15:08:12 +0000791 if (CXXMethodDecl *MD =
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000792 dyn_cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction))
793 ConversionDecl = MD;
Sebastian Redl0e35d042009-07-25 15:41:38 +0000794 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
795 TC_NotApplicable : TC_Success;
796}
797
798/// TryConstCast - See if a const_cast from source to destination is allowed,
799/// and perform it if it is.
800static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
801 bool CStyle, unsigned &msg) {
802 DestType = Self.Context.getCanonicalType(DestType);
803 QualType SrcType = SrcExpr->getType();
804 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000805 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000806 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
807 // Cannot const_cast non-lvalue to lvalue reference type. But if this
808 // is C-style, static_cast might find a way, so we simply suggest a
809 // message and tell the parent to keep searching.
810 msg = diag::err_bad_cxx_cast_rvalue;
811 return TC_NotApplicable;
812 }
813
814 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
815 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
816 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
817 SrcType = Self.Context.getPointerType(SrcType);
818 }
819
820 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
821 // the rules for const_cast are the same as those used for pointers.
822
823 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
824 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
825 // was a reference type, we converted it to a pointer above.
826 // The status of rvalue references isn't entirely clear, but it looks like
827 // conversion to them is simply invalid.
828 // C++ 5.2.11p3: For two pointer types [...]
829 if (!CStyle)
830 msg = diag::err_bad_const_cast_dest;
831 return TC_NotApplicable;
832 }
833 if (DestType->isFunctionPointerType() ||
834 DestType->isMemberFunctionPointerType()) {
835 // Cannot cast direct function pointers.
836 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
837 // T is the ultimate pointee of source and target type.
838 if (!CStyle)
839 msg = diag::err_bad_const_cast_dest;
840 return TC_NotApplicable;
841 }
842 SrcType = Self.Context.getCanonicalType(SrcType);
843
844 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
845 // completely equal.
846 // FIXME: const_cast should probably not be able to convert between pointers
847 // to different address spaces.
848 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
849 // in multi-level pointers may change, but the level count must be the same,
850 // as must be the final pointee type.
851 while (SrcType != DestType &&
852 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
853 SrcType = SrcType.getUnqualifiedType();
854 DestType = DestType.getUnqualifiedType();
855 }
856
857 // Since we're dealing in canonical types, the remainder must be the same.
858 if (SrcType != DestType)
859 return TC_NotApplicable;
860
861 return TC_Success;
862}
863
864static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
865 QualType DestType, bool CStyle,
Anders Carlssonf1957c82009-09-01 20:52:42 +0000866 CastExpr::CastKind &Kind,
Sebastian Redl0e35d042009-07-25 15:41:38 +0000867 const SourceRange &OpRange,
868 unsigned &msg) {
869 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
870
871 DestType = Self.Context.getCanonicalType(DestType);
872 QualType SrcType = SrcExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000873 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000874 bool LValue = DestTypeTmp->isLValueReferenceType();
875 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
876 // Cannot cast non-lvalue to reference type. See the similar comment in
877 // const_cast.
878 msg = diag::err_bad_cxx_cast_rvalue;
879 return TC_NotApplicable;
880 }
881
882 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
883 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
884 // built-in & and * operators.
885 // This code does this transformation for the checked types.
886 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
887 SrcType = Self.Context.getPointerType(SrcType);
888 }
889
890 // Canonicalize source for comparison.
891 SrcType = Self.Context.getCanonicalType(SrcType);
892
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000893 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
894 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000895 if (DestMemPtr && SrcMemPtr) {
896 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
897 // can be explicitly converted to an rvalue of type "pointer to member
898 // of Y of type T2" if T1 and T2 are both function types or both object
899 // types.
900 if (DestMemPtr->getPointeeType()->isFunctionType() !=
901 SrcMemPtr->getPointeeType()->isFunctionType())
902 return TC_NotApplicable;
903
904 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
905 // constness.
906 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
907 // we accept it.
908 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
909 msg = diag::err_bad_cxx_cast_const_away;
910 return TC_Failed;
911 }
912
913 // A valid member pointer cast.
914 return TC_Success;
915 }
916
917 // See below for the enumeral issue.
918 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
919 !DestType->isEnumeralType()) {
920 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
921 // type large enough to hold it. A value of std::nullptr_t can be
922 // converted to an integral type; the conversion has the same meaning
923 // and validity as a conversion of (void*)0 to the integral type.
924 if (Self.Context.getTypeSize(SrcType) >
925 Self.Context.getTypeSize(DestType)) {
926 msg = diag::err_bad_reinterpret_cast_small_int;
927 return TC_Failed;
928 }
929 return TC_Success;
930 }
931
932 bool destIsPtr = DestType->isPointerType();
933 bool srcIsPtr = SrcType->isPointerType();
934 if (!destIsPtr && !srcIsPtr) {
935 // Except for std::nullptr_t->integer and lvalue->reference, which are
936 // handled above, at least one of the two arguments must be a pointer.
937 return TC_NotApplicable;
938 }
939
940 if (SrcType == DestType) {
941 // C++ 5.2.10p2 has a note that mentions that, subject to all other
942 // restrictions, a cast to the same type is allowed. The intent is not
943 // entirely clear here, since all other paragraphs explicitly forbid casts
944 // to the same type. However, the behavior of compilers is pretty consistent
945 // on this point: allow same-type conversion if the involved types are
946 // pointers, disallow otherwise.
947 return TC_Success;
948 }
949
950 // Note: Clang treats enumeration types as integral types. If this is ever
951 // changed for C++, the additional check here will be redundant.
952 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
953 assert(srcIsPtr && "One type must be a pointer");
954 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
955 // type large enough to hold it.
956 if (Self.Context.getTypeSize(SrcType) >
957 Self.Context.getTypeSize(DestType)) {
958 msg = diag::err_bad_reinterpret_cast_small_int;
959 return TC_Failed;
960 }
961 return TC_Success;
962 }
963
964 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
965 assert(destIsPtr && "One type must be a pointer");
966 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
967 // converted to a pointer.
968 return TC_Success;
969 }
970
971 if (!destIsPtr || !srcIsPtr) {
972 // With the valid non-pointer conversions out of the way, we can be even
973 // more stringent.
974 return TC_NotApplicable;
975 }
976
977 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
978 // The C-style cast operator can.
979 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
980 msg = diag::err_bad_cxx_cast_const_away;
981 return TC_Failed;
982 }
983
984 // Not casting away constness, so the only remaining check is for compatible
985 // pointer categories.
986
987 if (SrcType->isFunctionPointerType()) {
988 if (DestType->isFunctionPointerType()) {
989 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
990 // a pointer to a function of a different type.
991 return TC_Success;
992 }
993
994 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
995 // an object type or vice versa is conditionally-supported.
996 // Compilers support it in C++03 too, though, because it's necessary for
997 // casting the return value of dlsym() and GetProcAddress().
998 // FIXME: Conditionally-supported behavior should be configurable in the
999 // TargetInfo or similar.
1000 if (!Self.getLangOptions().CPlusPlus0x)
1001 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1002 return TC_Success;
1003 }
1004
1005 if (DestType->isFunctionPointerType()) {
1006 // See above.
1007 if (!Self.getLangOptions().CPlusPlus0x)
1008 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1009 return TC_Success;
1010 }
1011
1012 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1013 // a pointer to an object of different type.
1014 // Void pointers are not specified, but supported by every compiler out there.
1015 // So we finish by allowing everything that remains - it's got to be two
1016 // object pointers.
Anders Carlssonf1957c82009-09-01 20:52:42 +00001017 Kind = CastExpr::CK_BitCast;
Sebastian Redl0e35d042009-07-25 15:41:38 +00001018 return TC_Success;
1019}
1020
Sebastian Redlc358b622009-07-29 13:50:23 +00001021bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00001022 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump25cf7602009-09-09 15:08:12 +00001023 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00001024 // This test is outside everything else because it's the only case where
1025 // a non-lvalue-reference target type does not lead to decay.
1026 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1027 if (CastTy->isVoidType())
1028 return false;
1029
1030 // If the type is dependent, we won't do any other semantic analysis now.
1031 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1032 return false;
1033
1034 if (!CastTy->isLValueReferenceType())
1035 DefaultFunctionArrayConversion(CastExpr);
1036
1037 // C++ [expr.cast]p5: The conversions performed by
1038 // - a const_cast,
1039 // - a static_cast,
1040 // - a static_cast followed by a const_cast,
1041 // - a reinterpret_cast, or
1042 // - a reinterpret_cast followed by a const_cast,
1043 // can be performed using the cast notation of explicit type conversion.
1044 // [...] If a conversion can be interpreted in more than one of the ways
1045 // listed above, the interpretation that appears first in the list is used,
1046 // even if a cast resulting from that interpretation is ill-formed.
1047 // In plain language, this means trying a const_cast ...
1048 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1957c82009-09-01 20:52:42 +00001049 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1050 msg);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001051 if (tcr == TC_NotApplicable) {
1052 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssonf1957c82009-09-01 20:52:42 +00001053 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind, R, msg,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00001054 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001055 if (tcr == TC_NotApplicable) {
1056 // ... and finally a reinterpret_cast, ignoring const.
Mike Stump25cf7602009-09-09 15:08:12 +00001057 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind,
Anders Carlssonf1957c82009-09-01 20:52:42 +00001058 R, msg);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001059 }
1060 }
1061
Sebastian Redl0e35d042009-07-25 15:41:38 +00001062 if (tcr != TC_Success && msg != 0)
Sebastian Redlc358b622009-07-29 13:50:23 +00001063 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001064 << CastExpr->getType() << CastTy << R;
1065
1066 return tcr != TC_Success;
1067}