blob: 0ae5d343cade7c63758f1e978b15708aa415a702 [file] [log] [blame]
Sebastian Redl26d85b12008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000018#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000019#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl9cc11e72009-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 Redl37d6de32008-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 Carlssoncdb61972009-08-07 22:21:05 +000046 const SourceRange &OpRange,
Anders Carlsson0aebc812009-09-09 21:33:21 +000047 CastExpr::CastKind &Kind,
48 CXXMethodDecl *&ConversionDecl);
Sebastian Redl37d6de32008-11-08 13:00:26 +000049static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
50 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000051 const SourceRange &DestRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000052 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000053
54static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000055
56// The Try functions attempt a specific way of casting. If they succeed, they
57// return TC_Success. If their way of casting is not appropriate for the given
58// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
59// to emit if no other way succeeds. If their way of casting is appropriate but
60// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
61// they emit a specialized diagnostic.
62// All diagnostics returned by these functions must expect the same three
63// arguments:
64// %0: Cast Type (a value from the CastType enumeration)
65// %1: Source Type
66// %2: Destination Type
67static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
68 QualType DestType, unsigned &msg);
69static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
70 QualType DestType, bool CStyle,
71 const SourceRange &OpRange,
72 unsigned &msg);
73static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
74 QualType DestType, bool CStyle,
75 const SourceRange &OpRange,
76 unsigned &msg);
77static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
78 QualType DestType, bool CStyle,
79 const SourceRange &OpRange,
80 QualType OrigSrcType,
81 QualType OrigDestType, unsigned &msg);
82static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
83 QualType DestType,bool CStyle,
84 const SourceRange &OpRange,
85 unsigned &msg);
86static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
87 QualType DestType, bool CStyle,
88 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000089 unsigned &msg,
90 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000091static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
92 QualType DestType, bool CStyle,
Mike Stump1eb44332009-09-09 15:08:12 +000093 CastExpr::CastKind &Kind,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000094 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +000095 unsigned &msg,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000096 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000097static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
98 bool CStyle, unsigned &msg);
99static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
100 QualType DestType, bool CStyle,
Mike Stump1eb44332009-09-09 15:08:12 +0000101 CastExpr::CastKind &Kind,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000102 const SourceRange &OpRange,
103 unsigned &msg);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000104
Sebastian Redl26d85b12008-11-05 21:50:06 +0000105/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000106Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000107Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
108 SourceLocation LAngleBracketLoc, TypeTy *Ty,
109 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000110 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000111 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000112 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000113 // FIXME: Preserve type source info.
114 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000115 SourceRange OpRange(OpLoc, RParenLoc);
116 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
117
Douglas Gregor9103bb22008-12-17 22:52:20 +0000118 // If the type is dependent, we won't do the semantic analysis now.
119 // FIXME: should we check this in a more fine-grained manner?
120 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
121
Sebastian Redl26d85b12008-11-05 21:50:06 +0000122 switch (Kind) {
123 default: assert(0 && "Unknown C++ cast!");
124
125 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000126 if (!TypeDependent)
127 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000128 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
129 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000130
Anders Carlsson714179b2009-08-02 19:07:59 +0000131 case tok::kw_dynamic_cast: {
132 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000133 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000134 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000135 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000136 Kind, Ex, DestType, OpLoc));
137 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000138 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000139 if (!TypeDependent)
140 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000141 return Owned(new (Context) CXXReinterpretCastExpr(
142 DestType.getNonReferenceType(),
143 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000144
Anders Carlssoncdb61972009-08-07 22:21:05 +0000145 case tok::kw_static_cast: {
146 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000147 if (!TypeDependent) {
148 CXXMethodDecl *Method = 0;
149
150 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
151
152 if (Method) {
153 OwningExprResult CastArg
154 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
155 Kind, Method, Owned(Ex));
156 if (CastArg.isInvalid())
157 return ExprError();
158
159 Ex = CastArg.takeAs<Expr>();
160 }
161 }
162
Sebastian Redlf53597f2009-03-15 17:47:39 +0000163 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000164 Kind, Ex, DestType, OpLoc));
165 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000166 }
167
Sebastian Redlf53597f2009-03-15 17:47:39 +0000168 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000169}
170
Sebastian Redldb647282009-01-27 23:18:31 +0000171/// CastsAwayConstness - Check if the pointer conversion from SrcType to
172/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
173/// the cast checkers. Both arguments must denote pointer (possibly to member)
174/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000175bool
Mike Stump1eb44332009-09-09 15:08:12 +0000176CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000177 // Casting away constness is defined in C++ 5.2.11p8 with reference to
178 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
179 // the rules are non-trivial. So first we construct Tcv *...cv* as described
180 // in C++ 5.2.11p8.
181 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
182 "Source type is not pointer or pointer to member.");
183 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
184 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000185
186 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
187 llvm::SmallVector<unsigned, 8> cv1, cv2;
188
189 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000190 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000191 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
192 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
193 }
194 assert(cv1.size() > 0 && "Must have at least one pointer level.");
195
196 // Construct void pointers with those qualifiers (in reverse order of
197 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000198 QualType SrcConstruct = Self.Context.VoidTy;
199 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000200 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
201 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000202 i1 != cv1.rend(); ++i1, ++i2) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000203 SrcConstruct = Self.Context.getPointerType(
204 SrcConstruct.getQualifiedType(*i1));
205 DestConstruct = Self.Context.getPointerType(
206 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000207 }
208
209 // Test if they're compatible.
210 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000211 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000212}
213
Sebastian Redl26d85b12008-11-05 21:50:06 +0000214/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
215/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
216/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000217static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000218CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
219 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000221 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000222 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000223
224 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
225 // or "pointer to cv void".
226
227 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000228 const PointerType *DestPointer = DestType->getAs<PointerType>();
229 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000230 if (DestPointer) {
231 DestPointee = DestPointer->getPointeeType();
232 } else if (DestReference) {
233 DestPointee = DestReference->getPointeeType();
234 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000235 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000236 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000237 return;
238 }
239
Ted Kremenek6217b802009-07-29 21:53:49 +0000240 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000241 if (DestPointee->isVoidType()) {
242 assert(DestPointer && "Reference to void is not possible");
243 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000244 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000245 PDiag(diag::err_bad_dynamic_cast_incomplete)
246 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000247 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000248 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000249 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000250 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000251 return;
252 }
253
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000254 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
255 // complete class type, [...]. If T is an lvalue reference type, v shall be
256 // an lvalue of a complete class type, [...]. If T is an rvalue reference
257 // type, v shall be an expression having a complete effective class type,
258 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000259
Sebastian Redl37d6de32008-11-08 13:00:26 +0000260 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000261 QualType SrcPointee;
262 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000263 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000264 SrcPointee = SrcPointer->getPointeeType();
265 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000266 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000267 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268 return;
269 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000270 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000271 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000272 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000273 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000274 }
275 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000276 } else {
277 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000278 }
279
Ted Kremenek6217b802009-07-29 21:53:49 +0000280 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000281 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000282 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000283 PDiag(diag::err_bad_dynamic_cast_incomplete)
284 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000285 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000286 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000287 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000288 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000289 return;
290 }
291
292 assert((DestPointer || DestReference) &&
293 "Bad destination non-ptr/ref slipped through.");
294 assert((DestRecord || DestPointee->isVoidType()) &&
295 "Bad destination pointee slipped through.");
296 assert(SrcRecord && "Bad source pointee slipped through.");
297
298 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
299 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000300 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000301 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302 return;
303 }
304
305 // C++ 5.2.7p3: If the type of v is the same as the required result type,
306 // [except for cv].
307 if (DestRecord == SrcRecord) {
308 return;
309 }
310
311 // C++ 5.2.7p5
312 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000313 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
314 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000315 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000316 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000317 // Diagnostic already emitted on error.
318 return;
319 }
320
321 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000322 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000323 assert(SrcDecl && "Definition missing");
324 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000325 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000326 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000327 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000328
329 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000330 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000331}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000332
333/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
334/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
335/// like this:
336/// const char *str = "literal";
337/// legacy_function(const_cast\<char*\>(str));
338void
339CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000340 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000341 if (!DestType->isLValueReferenceType())
342 Self.DefaultFunctionArrayConversion(SrcExpr);
343
344 unsigned msg = diag::err_bad_cxx_cast_generic;
345 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
346 && msg != 0)
347 Self.Diag(OpRange.getBegin(), msg) << CT_Const
348 << SrcExpr->getType() << DestType << OpRange;
349}
350
351/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
352/// valid.
353/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
354/// like this:
355/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
356void
357CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000359 if (!DestType->isLValueReferenceType())
360 Self.DefaultFunctionArrayConversion(SrcExpr);
361
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000362 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000363 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000364 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
365 OpRange, msg)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000366 != TC_Success && msg != 0)
367 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
368 << SrcExpr->getType() << DestType << OpRange;
369}
370
371
372/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
373/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
374/// implicit conversions explicit and getting rid of data loss warnings.
375void
376CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000377 const SourceRange &OpRange, CastExpr::CastKind &Kind,
378 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000379 // This test is outside everything else because it's the only case where
380 // a non-lvalue-reference target type does not lead to decay.
381 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
382 if (DestType->isVoidType()) {
383 return;
384 }
385
386 if (!DestType->isLValueReferenceType())
387 Self.DefaultFunctionArrayConversion(SrcExpr);
388
389 unsigned msg = diag::err_bad_cxx_cast_generic;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000391 OpRange, msg, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000392 != TC_Success && msg != 0)
393 Self.Diag(OpRange.getBegin(), msg) << CT_Static
394 << SrcExpr->getType() << DestType << OpRange;
395}
396
397/// TryStaticCast - Check if a static cast can be performed, and do so if
398/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
399/// and casting away constness.
400static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
401 QualType DestType, bool CStyle,
Mike Stump1eb44332009-09-09 15:08:12 +0000402 CastExpr::CastKind &Kind,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000403 const SourceRange &OpRange, unsigned &msg,
Mike Stump1eb44332009-09-09 15:08:12 +0000404 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000405 // The order the tests is not entirely arbitrary. There is one conversion
406 // that can be handled in two different ways. Given:
407 // struct A {};
408 // struct B : public A {
409 // B(); B(const A&);
410 // };
411 // const A &a = B();
412 // the cast static_cast<const B&>(a) could be seen as either a static
413 // reference downcast, or an explicit invocation of the user-defined
414 // conversion using B's conversion constructor.
415 // DR 427 specifies that the downcast is to be applied here.
416
417 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
418 // Done outside this function.
419
420 TryCastResult tcr;
421
422 // C++ 5.2.9p5, reference downcast.
423 // See the function for details.
424 // DR 427 specifies that this is to be applied before paragraph 2.
425 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
426 if (tcr != TC_NotApplicable)
427 return tcr;
428
429 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
430 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
431 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
432 if (tcr != TC_NotApplicable)
433 return tcr;
434
435 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
436 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000437 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
438 ConversionDecl);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000439 if (tcr != TC_NotApplicable) {
440 if (ConversionDecl) {
441 if (isa<CXXConstructorDecl>(ConversionDecl))
442 Kind = CastExpr::CK_ConstructorConversion;
443 else if (isa<CXXConversionDecl>(ConversionDecl))
444 Kind = CastExpr::CK_UserDefinedConversion;
445 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000446 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000447 }
448
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000449 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
450 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
451 // conversions, subject to further restrictions.
452 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
453 // of qualification conversions impossible.
454 // In the CStyle case, the earlier attempt to const_cast should have taken
455 // care of reverse qualification conversions.
456
457 QualType OrigSrcType = SrcExpr->getType();
458
459 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
460
461 // Reverse integral promotion/conversion. All such conversions are themselves
462 // again integral promotions or conversions and are thus already handled by
463 // p2 (TryDirectInitialization above).
464 // (Note: any data loss warnings should be suppressed.)
465 // The exception is the reverse of enum->integer, i.e. integer->enum (and
466 // enum->enum). See also C++ 5.2.9p7.
467 // The same goes for reverse floating point promotion/conversion and
468 // floating-integral conversions. Again, only floating->enum is relevant.
469 if (DestType->isEnumeralType()) {
470 if (SrcType->isComplexType() || SrcType->isVectorType()) {
471 // Fall through - these cannot be converted.
472 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
473 return TC_Success;
474 }
475
476 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
477 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
478 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
479 if (tcr != TC_NotApplicable)
480 return tcr;
481
482 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
483 // conversion. C++ 5.2.9p9 has additional information.
484 // DR54's access restrictions apply here also.
485 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
486 OpRange, msg);
487 if (tcr != TC_NotApplicable)
488 return tcr;
489
490 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
491 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
492 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000493 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000494 QualType SrcPointee = SrcPointer->getPointeeType();
495 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000496 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000497 QualType DestPointee = DestPointer->getPointeeType();
498 if (DestPointee->isIncompleteOrObjectType()) {
499 // This is definitely the intended conversion, but it might fail due
500 // to a const violation.
501 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
502 msg = diag::err_bad_cxx_cast_const_away;
503 return TC_Failed;
504 }
505 return TC_Success;
506 }
507 }
508 }
509 }
510
511 // We tried everything. Everything! Nothing works! :-(
512 return TC_NotApplicable;
513}
514
515/// Tests whether a conversion according to N2844 is valid.
516TryCastResult
517TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000518 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000519 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
520 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000521 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000522 if (!R)
523 return TC_NotApplicable;
524
525 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
526 return TC_NotApplicable;
527
528 // Because we try the reference downcast before this function, from now on
529 // this is the only cast possibility, so we issue an error if we fail now.
530 // FIXME: Should allow casting away constness if CStyle.
531 bool DerivedToBase;
532 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
533 DerivedToBase) <
534 Sema::Ref_Compatible_With_Added_Qualification) {
535 msg = diag::err_bad_lvalue_to_rvalue_cast;
536 return TC_Failed;
537 }
538
539 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
540 // than nothing.
541 return TC_Success;
542}
543
544/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
545TryCastResult
546TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
547 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000548 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000549 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
550 // cast to type "reference to cv2 D", where D is a class derived from B,
551 // if a valid standard conversion from "pointer to D" to "pointer to B"
552 // exists, cv2 >= cv1, and B is not a virtual base class of D.
553 // In addition, DR54 clarifies that the base must be accessible in the
554 // current context. Although the wording of DR54 only applies to the pointer
555 // variant of this rule, the intent is clearly for it to apply to the this
556 // conversion as well.
557
Ted Kremenek6217b802009-07-29 21:53:49 +0000558 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000559 if (!DestReference) {
560 return TC_NotApplicable;
561 }
562 bool RValueRef = DestReference->isRValueReferenceType();
563 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
564 // We know the left side is an lvalue reference, so we can suggest a reason.
565 msg = diag::err_bad_cxx_cast_rvalue;
566 return TC_NotApplicable;
567 }
568
569 QualType DestPointee = DestReference->getPointeeType();
570
571 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
572 OpRange, SrcExpr->getType(), DestType, msg);
573}
574
575/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
576TryCastResult
577TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 bool CStyle, const SourceRange &OpRange,
579 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000580 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
581 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
582 // is a class derived from B, if a valid standard conversion from "pointer
583 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
584 // class of D.
585 // In addition, DR54 clarifies that the base must be accessible in the
586 // current context.
587
Ted Kremenek6217b802009-07-29 21:53:49 +0000588 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000589 if (!DestPointer) {
590 return TC_NotApplicable;
591 }
592
Ted Kremenek6217b802009-07-29 21:53:49 +0000593 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000594 if (!SrcPointer) {
595 msg = diag::err_bad_static_cast_pointer_nonpointer;
596 return TC_NotApplicable;
597 }
598
599 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
600 DestPointer->getPointeeType(), CStyle,
601 OpRange, SrcType, DestType, msg);
602}
603
604/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
605/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
606/// DestType, both of which must be canonical, is possible and allowed.
607TryCastResult
608TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
609 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump1eb44332009-09-09 15:08:12 +0000610 QualType OrigDestType, unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000611 // Downcast can only happen in class hierarchies, so we need classes.
612 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
613 return TC_NotApplicable;
614 }
615
616 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
617 /*DetectVirtual=*/true);
618 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
619 return TC_NotApplicable;
620 }
621
622 // Target type does derive from source type. Now we're serious. If an error
623 // appears now, it's not ignored.
624 // This may not be entirely in line with the standard. Take for example:
625 // struct A {};
626 // struct B : virtual A {
627 // B(A&);
628 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000629 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000630 // void f()
631 // {
632 // (void)static_cast<const B&>(*((A*)0));
633 // }
634 // As far as the standard is concerned, p5 does not apply (A is virtual), so
635 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
636 // However, both GCC and Comeau reject this example, and accepting it would
637 // mean more complex code if we're to preserve the nice error message.
638 // FIXME: Being 100% compliant here would be nice to have.
639
640 // Must preserve cv, as always, unless we're in C-style mode.
641 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
642 msg = diag::err_bad_cxx_cast_const_away;
643 return TC_Failed;
644 }
645
646 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
647 // This code is analoguous to that in CheckDerivedToBaseConversion, except
648 // that it builds the paths in reverse order.
649 // To sum up: record all paths to the base and build a nice string from
650 // them. Use it to spice up the error message.
651 if (!Paths.isRecordingPaths()) {
652 Paths.clear();
653 Paths.setRecordingPaths(true);
654 Self.IsDerivedFrom(DestType, SrcType, Paths);
655 }
656 std::string PathDisplayStr;
657 std::set<unsigned> DisplayedPaths;
658 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
659 PI != PE; ++PI) {
660 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
661 // We haven't displayed a path to this particular base
662 // class subobject yet.
663 PathDisplayStr += "\n ";
664 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
665 EI != EE; ++EI)
666 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
667 PathDisplayStr += DestType.getAsString();
668 }
669 }
670
671 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
672 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
673 << PathDisplayStr << OpRange;
674 msg = 0;
675 return TC_Failed;
676 }
677
678 if (Paths.getDetectedVirtual() != 0) {
679 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
680 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
681 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
682 msg = 0;
683 return TC_Failed;
684 }
685
686 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
687 diag::err_downcast_from_inaccessible_base, Paths,
688 OpRange.getBegin(), DeclarationName())) {
689 msg = 0;
690 return TC_Failed;
691 }
692
693 return TC_Success;
694}
695
696/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
697/// C++ 5.2.9p9 is valid:
698///
699/// An rvalue of type "pointer to member of D of type cv1 T" can be
700/// converted to an rvalue of type "pointer to member of B of type cv2 T",
701/// where B is a base class of D [...].
702///
703TryCastResult
704TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
705 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000706 unsigned &msg) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000707 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000708 if (!DestMemPtr)
709 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000710 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000711 if (!SrcMemPtr) {
712 msg = diag::err_bad_static_cast_member_pointer_nonmp;
713 return TC_NotApplicable;
714 }
715
716 // T == T, modulo cv
717 if (Self.Context.getCanonicalType(
718 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
719 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
720 getUnqualifiedType()))
721 return TC_NotApplicable;
722
723 // B base of D
724 QualType SrcClass(SrcMemPtr->getClass(), 0);
725 QualType DestClass(DestMemPtr->getClass(), 0);
726 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
727 /*DetectVirtual=*/true);
728 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
729 return TC_NotApplicable;
730 }
731
732 // B is a base of D. But is it an allowed base? If not, it's a hard error.
733 if (Paths.isAmbiguous(DestClass)) {
734 Paths.clear();
735 Paths.setRecordingPaths(true);
736 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
737 assert(StillOkay);
738 StillOkay = StillOkay;
739 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
740 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
741 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
742 msg = 0;
743 return TC_Failed;
744 }
745
746 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
747 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
748 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
749 msg = 0;
750 return TC_Failed;
751 }
752
753 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
754 diag::err_downcast_from_inaccessible_base, Paths,
755 OpRange.getBegin(), DeclarationName())) {
756 msg = 0;
757 return TC_Failed;
758 }
759
760 return TC_Success;
761}
762
763/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
764/// is valid:
765///
766/// An expression e can be explicitly converted to a type T using a
767/// @c static_cast if the declaration "T t(e);" is well-formed [...].
768TryCastResult
769TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000770 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Mike Stump1eb44332009-09-09 15:08:12 +0000771 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000772 if (DestType->isRecordType()) {
773 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
774 diag::err_bad_dynamic_cast_incomplete)) {
775 msg = 0;
776 return TC_Failed;
777 }
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000780 if (DestType->isReferenceType()) {
781 // At this point of CheckStaticCast, if the destination is a reference,
782 // this has to work. There is no other way that works.
783 // On the other hand, if we're checking a C-style cast, we've still got
784 // the reinterpret_cast way. In that case, we pass an ICS so we don't
785 // get error messages.
786 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +0000787 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000788 /*SuppressUserConversions=*/false,
789 /*AllowExplicit=*/false,
790 /*ForceRValue=*/false,
791 CStyle ? &ICS : 0);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000792 if (!failed)
793 return TC_Success;
794 if (CStyle)
795 return TC_NotApplicable;
796 // If we didn't pass the ICS, we already got an error message.
797 msg = 0;
798 return TC_Failed;
799 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000800
801 // FIXME: To get a proper error from invalid conversions here, we need to
802 // reimplement more of this.
803 // FIXME: This does not actually perform the conversion, and thus does not
804 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000805 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000806 Self.TryImplicitConversion(SrcExpr, DestType,
807 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000808 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000809 /*ForceRValue=*/false,
810 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Anders Carlsson0aebc812009-09-09 21:33:21 +0000812 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000813 if (CXXMethodDecl *MD =
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000814 dyn_cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction))
815 ConversionDecl = MD;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000816 }
817
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000818 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
819 TC_NotApplicable : TC_Success;
820}
821
822/// TryConstCast - See if a const_cast from source to destination is allowed,
823/// and perform it if it is.
824static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
825 bool CStyle, unsigned &msg) {
826 DestType = Self.Context.getCanonicalType(DestType);
827 QualType SrcType = SrcExpr->getType();
828 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000829 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000830 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
831 // Cannot const_cast non-lvalue to lvalue reference type. But if this
832 // is C-style, static_cast might find a way, so we simply suggest a
833 // message and tell the parent to keep searching.
834 msg = diag::err_bad_cxx_cast_rvalue;
835 return TC_NotApplicable;
836 }
837
838 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
839 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
840 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
841 SrcType = Self.Context.getPointerType(SrcType);
842 }
843
844 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
845 // the rules for const_cast are the same as those used for pointers.
846
847 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
848 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
849 // was a reference type, we converted it to a pointer above.
850 // The status of rvalue references isn't entirely clear, but it looks like
851 // conversion to them is simply invalid.
852 // C++ 5.2.11p3: For two pointer types [...]
853 if (!CStyle)
854 msg = diag::err_bad_const_cast_dest;
855 return TC_NotApplicable;
856 }
857 if (DestType->isFunctionPointerType() ||
858 DestType->isMemberFunctionPointerType()) {
859 // Cannot cast direct function pointers.
860 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
861 // T is the ultimate pointee of source and target type.
862 if (!CStyle)
863 msg = diag::err_bad_const_cast_dest;
864 return TC_NotApplicable;
865 }
866 SrcType = Self.Context.getCanonicalType(SrcType);
867
868 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
869 // completely equal.
870 // FIXME: const_cast should probably not be able to convert between pointers
871 // to different address spaces.
872 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
873 // in multi-level pointers may change, but the level count must be the same,
874 // as must be the final pointee type.
875 while (SrcType != DestType &&
876 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
877 SrcType = SrcType.getUnqualifiedType();
878 DestType = DestType.getUnqualifiedType();
879 }
880
881 // Since we're dealing in canonical types, the remainder must be the same.
882 if (SrcType != DestType)
883 return TC_NotApplicable;
884
885 return TC_Success;
886}
887
888static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
889 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000890 CastExpr::CastKind &Kind,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000891 const SourceRange &OpRange,
892 unsigned &msg) {
893 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
894
895 DestType = Self.Context.getCanonicalType(DestType);
896 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000897 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000898 bool LValue = DestTypeTmp->isLValueReferenceType();
899 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
900 // Cannot cast non-lvalue to reference type. See the similar comment in
901 // const_cast.
902 msg = diag::err_bad_cxx_cast_rvalue;
903 return TC_NotApplicable;
904 }
905
906 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
907 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
908 // built-in & and * operators.
909 // This code does this transformation for the checked types.
910 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
911 SrcType = Self.Context.getPointerType(SrcType);
912 }
913
914 // Canonicalize source for comparison.
915 SrcType = Self.Context.getCanonicalType(SrcType);
916
Ted Kremenek6217b802009-07-29 21:53:49 +0000917 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
918 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000919 if (DestMemPtr && SrcMemPtr) {
920 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
921 // can be explicitly converted to an rvalue of type "pointer to member
922 // of Y of type T2" if T1 and T2 are both function types or both object
923 // types.
924 if (DestMemPtr->getPointeeType()->isFunctionType() !=
925 SrcMemPtr->getPointeeType()->isFunctionType())
926 return TC_NotApplicable;
927
928 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
929 // constness.
930 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
931 // we accept it.
932 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
933 msg = diag::err_bad_cxx_cast_const_away;
934 return TC_Failed;
935 }
936
937 // A valid member pointer cast.
938 return TC_Success;
939 }
940
941 // See below for the enumeral issue.
942 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
943 !DestType->isEnumeralType()) {
944 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
945 // type large enough to hold it. A value of std::nullptr_t can be
946 // converted to an integral type; the conversion has the same meaning
947 // and validity as a conversion of (void*)0 to the integral type.
948 if (Self.Context.getTypeSize(SrcType) >
949 Self.Context.getTypeSize(DestType)) {
950 msg = diag::err_bad_reinterpret_cast_small_int;
951 return TC_Failed;
952 }
953 return TC_Success;
954 }
955
956 bool destIsPtr = DestType->isPointerType();
957 bool srcIsPtr = SrcType->isPointerType();
958 if (!destIsPtr && !srcIsPtr) {
959 // Except for std::nullptr_t->integer and lvalue->reference, which are
960 // handled above, at least one of the two arguments must be a pointer.
961 return TC_NotApplicable;
962 }
963
964 if (SrcType == DestType) {
965 // C++ 5.2.10p2 has a note that mentions that, subject to all other
966 // restrictions, a cast to the same type is allowed. The intent is not
967 // entirely clear here, since all other paragraphs explicitly forbid casts
968 // to the same type. However, the behavior of compilers is pretty consistent
969 // on this point: allow same-type conversion if the involved types are
970 // pointers, disallow otherwise.
971 return TC_Success;
972 }
973
974 // Note: Clang treats enumeration types as integral types. If this is ever
975 // changed for C++, the additional check here will be redundant.
976 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
977 assert(srcIsPtr && "One type must be a pointer");
978 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
979 // type large enough to hold it.
980 if (Self.Context.getTypeSize(SrcType) >
981 Self.Context.getTypeSize(DestType)) {
982 msg = diag::err_bad_reinterpret_cast_small_int;
983 return TC_Failed;
984 }
985 return TC_Success;
986 }
987
988 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
989 assert(destIsPtr && "One type must be a pointer");
990 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
991 // converted to a pointer.
992 return TC_Success;
993 }
994
995 if (!destIsPtr || !srcIsPtr) {
996 // With the valid non-pointer conversions out of the way, we can be even
997 // more stringent.
998 return TC_NotApplicable;
999 }
1000
1001 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1002 // The C-style cast operator can.
1003 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1004 msg = diag::err_bad_cxx_cast_const_away;
1005 return TC_Failed;
1006 }
1007
1008 // Not casting away constness, so the only remaining check is for compatible
1009 // pointer categories.
1010
1011 if (SrcType->isFunctionPointerType()) {
1012 if (DestType->isFunctionPointerType()) {
1013 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1014 // a pointer to a function of a different type.
1015 return TC_Success;
1016 }
1017
1018 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1019 // an object type or vice versa is conditionally-supported.
1020 // Compilers support it in C++03 too, though, because it's necessary for
1021 // casting the return value of dlsym() and GetProcAddress().
1022 // FIXME: Conditionally-supported behavior should be configurable in the
1023 // TargetInfo or similar.
1024 if (!Self.getLangOptions().CPlusPlus0x)
1025 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1026 return TC_Success;
1027 }
1028
1029 if (DestType->isFunctionPointerType()) {
1030 // See above.
1031 if (!Self.getLangOptions().CPlusPlus0x)
1032 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1033 return TC_Success;
1034 }
1035
1036 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1037 // a pointer to an object of different type.
1038 // Void pointers are not specified, but supported by every compiler out there.
1039 // So we finish by allowing everything that remains - it's got to be two
1040 // object pointers.
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001041 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001042 return TC_Success;
1043}
1044
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001045bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001046 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001047 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048 // This test is outside everything else because it's the only case where
1049 // a non-lvalue-reference target type does not lead to decay.
1050 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1051 if (CastTy->isVoidType())
1052 return false;
1053
1054 // If the type is dependent, we won't do any other semantic analysis now.
1055 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1056 return false;
1057
1058 if (!CastTy->isLValueReferenceType())
1059 DefaultFunctionArrayConversion(CastExpr);
1060
1061 // C++ [expr.cast]p5: The conversions performed by
1062 // - a const_cast,
1063 // - a static_cast,
1064 // - a static_cast followed by a const_cast,
1065 // - a reinterpret_cast, or
1066 // - a reinterpret_cast followed by a const_cast,
1067 // can be performed using the cast notation of explicit type conversion.
1068 // [...] If a conversion can be interpreted in more than one of the ways
1069 // listed above, the interpretation that appears first in the list is used,
1070 // even if a cast resulting from that interpretation is ill-formed.
1071 // In plain language, this means trying a const_cast ...
1072 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001073 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1074 msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001075 if (tcr == TC_NotApplicable) {
1076 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001077 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind, R, msg,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001078 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001079 if (tcr == TC_NotApplicable) {
1080 // ... and finally a reinterpret_cast, ignoring const.
Mike Stump1eb44332009-09-09 15:08:12 +00001081 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind,
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001082 R, msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001083 }
1084 }
1085
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001086 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001087 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001088 << CastExpr->getType() << CastTy << R;
1089
1090 return tcr != TC_Success;
1091}