blob: bf396041b473b7c931a5dbdeabd7cc30f6bc8ced [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"
Sebastian Redl26d85b12008-11-05 21:50:06 +000015#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.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,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000044 const SourceRange &DestRange,
45 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000046static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000047 const SourceRange &OpRange,
Anders Carlsson0aebc812009-09-09 21:33:21 +000048 CastExpr::CastKind &Kind,
49 CXXMethodDecl *&ConversionDecl);
Sebastian Redl37d6de32008-11-08 13:00:26 +000050static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
51 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000052 const SourceRange &DestRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000053 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000054
55static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000056
57// The Try functions attempt a specific way of casting. If they succeed, they
58// return TC_Success. If their way of casting is not appropriate for the given
59// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
60// to emit if no other way succeeds. If their way of casting is appropriate but
61// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
62// they emit a specialized diagnostic.
63// All diagnostics returned by these functions must expect the same three
64// arguments:
65// %0: Cast Type (a value from the CastType enumeration)
66// %1: Source Type
67// %2: Destination Type
68static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
69 QualType DestType, unsigned &msg);
70static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, bool CStyle,
72 const SourceRange &OpRange,
73 unsigned &msg);
74static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
75 QualType DestType, bool CStyle,
76 const SourceRange &OpRange,
77 unsigned &msg);
78static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
81 QualType OrigSrcType,
82 QualType OrigDestType, unsigned &msg);
83static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
84 QualType DestType,bool CStyle,
85 const SourceRange &OpRange,
86 unsigned &msg);
87static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
88 QualType DestType, bool CStyle,
89 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000090 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000091 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000092 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000093static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
94 QualType DestType, bool CStyle,
95 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +000096 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000097 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000098 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000099static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
100 bool CStyle, unsigned &msg);
101static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
102 QualType DestType, bool CStyle,
103 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000104 unsigned &msg,
105 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000106
Sebastian Redl26d85b12008-11-05 21:50:06 +0000107/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000109Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
110 SourceLocation LAngleBracketLoc, TypeTy *Ty,
111 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000112 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000114 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000115 // FIXME: Preserve type source info.
116 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000117 SourceRange OpRange(OpLoc, RParenLoc);
118 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
119
Douglas Gregor9103bb22008-12-17 22:52:20 +0000120 // If the type is dependent, we won't do the semantic analysis now.
121 // FIXME: should we check this in a more fine-grained manner?
122 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
123
Sebastian Redl26d85b12008-11-05 21:50:06 +0000124 switch (Kind) {
125 default: assert(0 && "Unknown C++ cast!");
126
127 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000128 if (!TypeDependent)
129 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
131 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000132
Anders Carlsson714179b2009-08-02 19:07:59 +0000133 case tok::kw_dynamic_cast: {
134 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000135 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000136 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000138 Kind, Ex, DestType, OpLoc));
139 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000140 case tok::kw_reinterpret_cast: {
141 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000142 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000143 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 return Owned(new (Context) CXXReinterpretCastExpr(
145 DestType.getNonReferenceType(),
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000146 Kind, Ex, DestType, OpLoc));
147 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000148 case tok::kw_static_cast: {
149 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000150 if (!TypeDependent) {
151 CXXMethodDecl *Method = 0;
152
153 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
154
155 if (Method) {
156 OwningExprResult CastArg
157 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
158 Kind, Method, Owned(Ex));
159 if (CastArg.isInvalid())
160 return ExprError();
161
162 Ex = CastArg.takeAs<Expr>();
163 }
164 }
165
Sebastian Redlf53597f2009-03-15 17:47:39 +0000166 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000167 Kind, Ex, DestType, OpLoc));
168 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000169 }
170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000172}
173
Sebastian Redldb647282009-01-27 23:18:31 +0000174/// CastsAwayConstness - Check if the pointer conversion from SrcType to
175/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
176/// the cast checkers. Both arguments must denote pointer (possibly to member)
177/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000178static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000179CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000180 // Casting away constness is defined in C++ 5.2.11p8 with reference to
181 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
182 // the rules are non-trivial. So first we construct Tcv *...cv* as described
183 // in C++ 5.2.11p8.
184 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
185 "Source type is not pointer or pointer to member.");
186 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
187 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000188
189 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
John McCall0953e762009-09-24 19:53:00 +0000190 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000191
192 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000193 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000194 cv1.push_back(UnwrappedSrcType.getQualifiers());
195 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000196 }
197 assert(cv1.size() > 0 && "Must have at least one pointer level.");
198
199 // Construct void pointers with those qualifiers (in reverse order of
200 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000201 QualType SrcConstruct = Self.Context.VoidTy;
202 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000203 ASTContext &Context = Self.Context;
204 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
205 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000206 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000207 SrcConstruct
208 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
209 DestConstruct
210 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000211 }
212
213 // Test if they're compatible.
214 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000215 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216}
217
Sebastian Redl26d85b12008-11-05 21:50:06 +0000218/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
219/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
220/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000221static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000222CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
223 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000224 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000226 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000227
228 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
229 // or "pointer to cv void".
230
231 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000232 const PointerType *DestPointer = DestType->getAs<PointerType>();
233 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000234 if (DestPointer) {
235 DestPointee = DestPointer->getPointeeType();
236 } else if (DestReference) {
237 DestPointee = DestReference->getPointeeType();
238 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000239 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000240 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000241 return;
242 }
243
Ted Kremenek6217b802009-07-29 21:53:49 +0000244 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000245 if (DestPointee->isVoidType()) {
246 assert(DestPointer && "Reference to void is not possible");
247 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000248 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000249 PDiag(diag::err_bad_dynamic_cast_incomplete)
250 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000251 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000253 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000254 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000255 return;
256 }
257
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000258 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
259 // complete class type, [...]. If T is an lvalue reference type, v shall be
260 // an lvalue of a complete class type, [...]. If T is an rvalue reference
261 // type, v shall be an expression having a complete effective class type,
262 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263
Sebastian Redl37d6de32008-11-08 13:00:26 +0000264 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000265 QualType SrcPointee;
266 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000267 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268 SrcPointee = SrcPointer->getPointeeType();
269 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000270 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000271 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000272 return;
273 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000274 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000275 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000276 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000277 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000278 }
279 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000280 } else {
281 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000282 }
283
Ted Kremenek6217b802009-07-29 21:53:49 +0000284 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000285 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000286 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000287 PDiag(diag::err_bad_dynamic_cast_incomplete)
288 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000289 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000291 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000292 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000293 return;
294 }
295
296 assert((DestPointer || DestReference) &&
297 "Bad destination non-ptr/ref slipped through.");
298 assert((DestRecord || DestPointee->isVoidType()) &&
299 "Bad destination pointee slipped through.");
300 assert(SrcRecord && "Bad source pointee slipped through.");
301
302 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
303 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000304 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000305 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306 return;
307 }
308
309 // C++ 5.2.7p3: If the type of v is the same as the required result type,
310 // [except for cv].
311 if (DestRecord == SrcRecord) {
312 return;
313 }
314
315 // C++ 5.2.7p5
316 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000317 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
318 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000319 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000320 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 // Diagnostic already emitted on error.
322 return;
323 }
324
325 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000326 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000327 assert(SrcDecl && "Definition missing");
328 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000329 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000330 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000331 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000332
333 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000334 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000335}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000336
337/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
338/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
339/// like this:
340/// const char *str = "literal";
341/// legacy_function(const_cast\<char*\>(str));
342void
343CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000345 if (!DestType->isLValueReferenceType())
346 Self.DefaultFunctionArrayConversion(SrcExpr);
347
348 unsigned msg = diag::err_bad_cxx_cast_generic;
349 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
350 && msg != 0)
351 Self.Diag(OpRange.getBegin(), msg) << CT_Const
352 << SrcExpr->getType() << DestType << OpRange;
353}
354
355/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
356/// valid.
357/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
358/// like this:
359/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
360void
361CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000362 const SourceRange &OpRange, const SourceRange &DestRange,
363 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000364 if (!DestType->isLValueReferenceType())
365 Self.DefaultFunctionArrayConversion(SrcExpr);
366
367 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000368 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
369 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000370 != TC_Success && msg != 0)
371 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
372 << SrcExpr->getType() << DestType << OpRange;
373}
374
375
376/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
377/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
378/// implicit conversions explicit and getting rid of data loss warnings.
379void
380CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000381 const SourceRange &OpRange, CastExpr::CastKind &Kind,
382 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000383 // This test is outside everything else because it's the only case where
384 // a non-lvalue-reference target type does not lead to decay.
385 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
386 if (DestType->isVoidType()) {
387 return;
388 }
389
390 if (!DestType->isLValueReferenceType())
391 Self.DefaultFunctionArrayConversion(SrcExpr);
392
393 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000394 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false,OpRange, msg,
395 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000396 != TC_Success && msg != 0)
397 Self.Diag(OpRange.getBegin(), msg) << CT_Static
398 << SrcExpr->getType() << DestType << OpRange;
399}
400
401/// TryStaticCast - Check if a static cast can be performed, and do so if
402/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
403/// and casting away constness.
404static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
405 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000406 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000407 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000408 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000409 // The order the tests is not entirely arbitrary. There is one conversion
410 // that can be handled in two different ways. Given:
411 // struct A {};
412 // struct B : public A {
413 // B(); B(const A&);
414 // };
415 // const A &a = B();
416 // the cast static_cast<const B&>(a) could be seen as either a static
417 // reference downcast, or an explicit invocation of the user-defined
418 // conversion using B's conversion constructor.
419 // DR 427 specifies that the downcast is to be applied here.
420
421 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
422 // Done outside this function.
423
424 TryCastResult tcr;
425
426 // C++ 5.2.9p5, reference downcast.
427 // See the function for details.
428 // DR 427 specifies that this is to be applied before paragraph 2.
429 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
430 if (tcr != TC_NotApplicable)
431 return tcr;
432
433 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
434 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
435 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
436 if (tcr != TC_NotApplicable)
437 return tcr;
438
439 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
440 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000441 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000442 Kind, ConversionDecl);
443 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000444 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000445
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000446 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
447 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
448 // conversions, subject to further restrictions.
449 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
450 // of qualification conversions impossible.
451 // In the CStyle case, the earlier attempt to const_cast should have taken
452 // care of reverse qualification conversions.
453
454 QualType OrigSrcType = SrcExpr->getType();
455
456 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
457
458 // Reverse integral promotion/conversion. All such conversions are themselves
459 // again integral promotions or conversions and are thus already handled by
460 // p2 (TryDirectInitialization above).
461 // (Note: any data loss warnings should be suppressed.)
462 // The exception is the reverse of enum->integer, i.e. integer->enum (and
463 // enum->enum). See also C++ 5.2.9p7.
464 // The same goes for reverse floating point promotion/conversion and
465 // floating-integral conversions. Again, only floating->enum is relevant.
466 if (DestType->isEnumeralType()) {
467 if (SrcType->isComplexType() || SrcType->isVectorType()) {
468 // Fall through - these cannot be converted.
469 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
470 return TC_Success;
471 }
472
473 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
474 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
475 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
476 if (tcr != TC_NotApplicable)
477 return tcr;
478
479 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
480 // conversion. C++ 5.2.9p9 has additional information.
481 // DR54's access restrictions apply here also.
482 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
483 OpRange, msg);
484 if (tcr != TC_NotApplicable)
485 return tcr;
486
487 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
488 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
489 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000490 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000491 QualType SrcPointee = SrcPointer->getPointeeType();
492 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000493 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000494 QualType DestPointee = DestPointer->getPointeeType();
495 if (DestPointee->isIncompleteOrObjectType()) {
496 // This is definitely the intended conversion, but it might fail due
497 // to a const violation.
498 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
499 msg = diag::err_bad_cxx_cast_const_away;
500 return TC_Failed;
501 }
502 return TC_Success;
503 }
504 }
505 }
506 }
507
508 // We tried everything. Everything! Nothing works! :-(
509 return TC_NotApplicable;
510}
511
512/// Tests whether a conversion according to N2844 is valid.
513TryCastResult
514TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000515 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000516 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
517 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000518 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000519 if (!R)
520 return TC_NotApplicable;
521
522 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
523 return TC_NotApplicable;
524
525 // Because we try the reference downcast before this function, from now on
526 // this is the only cast possibility, so we issue an error if we fail now.
527 // FIXME: Should allow casting away constness if CStyle.
528 bool DerivedToBase;
529 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
530 DerivedToBase) <
531 Sema::Ref_Compatible_With_Added_Qualification) {
532 msg = diag::err_bad_lvalue_to_rvalue_cast;
533 return TC_Failed;
534 }
535
536 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
537 // than nothing.
538 return TC_Success;
539}
540
541/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
542TryCastResult
543TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
544 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000545 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000546 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
547 // cast to type "reference to cv2 D", where D is a class derived from B,
548 // if a valid standard conversion from "pointer to D" to "pointer to B"
549 // exists, cv2 >= cv1, and B is not a virtual base class of D.
550 // In addition, DR54 clarifies that the base must be accessible in the
551 // current context. Although the wording of DR54 only applies to the pointer
552 // variant of this rule, the intent is clearly for it to apply to the this
553 // conversion as well.
554
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000556 if (!DestReference) {
557 return TC_NotApplicable;
558 }
559 bool RValueRef = DestReference->isRValueReferenceType();
560 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
561 // We know the left side is an lvalue reference, so we can suggest a reason.
562 msg = diag::err_bad_cxx_cast_rvalue;
563 return TC_NotApplicable;
564 }
565
566 QualType DestPointee = DestReference->getPointeeType();
567
568 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
569 OpRange, SrcExpr->getType(), DestType, msg);
570}
571
572/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
573TryCastResult
574TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000575 bool CStyle, const SourceRange &OpRange,
576 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000577 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
578 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
579 // is a class derived from B, if a valid standard conversion from "pointer
580 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
581 // class of D.
582 // In addition, DR54 clarifies that the base must be accessible in the
583 // current context.
584
Ted Kremenek6217b802009-07-29 21:53:49 +0000585 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000586 if (!DestPointer) {
587 return TC_NotApplicable;
588 }
589
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000591 if (!SrcPointer) {
592 msg = diag::err_bad_static_cast_pointer_nonpointer;
593 return TC_NotApplicable;
594 }
595
596 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
597 DestPointer->getPointeeType(), CStyle,
598 OpRange, SrcType, DestType, msg);
599}
600
601/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
602/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
603/// DestType, both of which must be canonical, is possible and allowed.
604TryCastResult
605TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
606 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump1eb44332009-09-09 15:08:12 +0000607 QualType OrigDestType, unsigned &msg) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000608 // We can only work with complete types. But don't complain if it doesn't work
609 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
610 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
611 return TC_NotApplicable;
612
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000613 // Downcast can only happen in class hierarchies, so we need classes.
614 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
615 return TC_NotApplicable;
616 }
617
Douglas Gregora8f32e02009-10-06 17:59:45 +0000618 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
619 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000620 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
621 return TC_NotApplicable;
622 }
623
624 // Target type does derive from source type. Now we're serious. If an error
625 // appears now, it's not ignored.
626 // This may not be entirely in line with the standard. Take for example:
627 // struct A {};
628 // struct B : virtual A {
629 // B(A&);
630 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000631 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000632 // void f()
633 // {
634 // (void)static_cast<const B&>(*((A*)0));
635 // }
636 // As far as the standard is concerned, p5 does not apply (A is virtual), so
637 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
638 // However, both GCC and Comeau reject this example, and accepting it would
639 // mean more complex code if we're to preserve the nice error message.
640 // FIXME: Being 100% compliant here would be nice to have.
641
642 // Must preserve cv, as always, unless we're in C-style mode.
643 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
644 msg = diag::err_bad_cxx_cast_const_away;
645 return TC_Failed;
646 }
647
648 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
649 // This code is analoguous to that in CheckDerivedToBaseConversion, except
650 // that it builds the paths in reverse order.
651 // To sum up: record all paths to the base and build a nice string from
652 // them. Use it to spice up the error message.
653 if (!Paths.isRecordingPaths()) {
654 Paths.clear();
655 Paths.setRecordingPaths(true);
656 Self.IsDerivedFrom(DestType, SrcType, Paths);
657 }
658 std::string PathDisplayStr;
659 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000660 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000661 PI != PE; ++PI) {
662 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
663 // We haven't displayed a path to this particular base
664 // class subobject yet.
665 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000666 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
667 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000668 EI != EE; ++EI)
669 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
670 PathDisplayStr += DestType.getAsString();
671 }
672 }
673
674 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
675 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
676 << PathDisplayStr << OpRange;
677 msg = 0;
678 return TC_Failed;
679 }
680
681 if (Paths.getDetectedVirtual() != 0) {
682 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
683 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
684 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
685 msg = 0;
686 return TC_Failed;
687 }
688
689 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
690 diag::err_downcast_from_inaccessible_base, Paths,
691 OpRange.getBegin(), DeclarationName())) {
692 msg = 0;
693 return TC_Failed;
694 }
695
696 return TC_Success;
697}
698
699/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
700/// C++ 5.2.9p9 is valid:
701///
702/// An rvalue of type "pointer to member of D of type cv1 T" can be
703/// converted to an rvalue of type "pointer to member of B of type cv2 T",
704/// where B is a base class of D [...].
705///
706TryCastResult
707TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
708 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000709 unsigned &msg) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000710 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000711 if (!DestMemPtr)
712 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000713 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000714 if (!SrcMemPtr) {
715 msg = diag::err_bad_static_cast_member_pointer_nonmp;
716 return TC_NotApplicable;
717 }
718
719 // T == T, modulo cv
720 if (Self.Context.getCanonicalType(
721 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
722 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
723 getUnqualifiedType()))
724 return TC_NotApplicable;
725
726 // B base of D
727 QualType SrcClass(SrcMemPtr->getClass(), 0);
728 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000730 /*DetectVirtual=*/true);
731 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
732 return TC_NotApplicable;
733 }
734
735 // B is a base of D. But is it an allowed base? If not, it's a hard error.
736 if (Paths.isAmbiguous(DestClass)) {
737 Paths.clear();
738 Paths.setRecordingPaths(true);
739 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
740 assert(StillOkay);
741 StillOkay = StillOkay;
742 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
743 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
744 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
745 msg = 0;
746 return TC_Failed;
747 }
748
749 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
750 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
751 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
752 msg = 0;
753 return TC_Failed;
754 }
755
756 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
757 diag::err_downcast_from_inaccessible_base, Paths,
758 OpRange.getBegin(), DeclarationName())) {
759 msg = 0;
760 return TC_Failed;
761 }
762
763 return TC_Success;
764}
765
766/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
767/// is valid:
768///
769/// An expression e can be explicitly converted to a type T using a
770/// @c static_cast if the declaration "T t(e);" is well-formed [...].
771TryCastResult
772TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000773 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000774 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000775 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000776 if (DestType->isRecordType()) {
777 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
778 diag::err_bad_dynamic_cast_incomplete)) {
779 msg = 0;
780 return TC_Failed;
781 }
782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000784 if (DestType->isReferenceType()) {
785 // At this point of CheckStaticCast, if the destination is a reference,
786 // this has to work. There is no other way that works.
787 // On the other hand, if we're checking a C-style cast, we've still got
788 // the reinterpret_cast way. In that case, we pass an ICS so we don't
789 // get error messages.
790 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +0000791 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000792 OpRange.getBegin(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000793 /*SuppressUserConversions=*/false,
794 /*AllowExplicit=*/false,
795 /*ForceRValue=*/false,
796 CStyle ? &ICS : 0);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000797 if (!failed)
798 return TC_Success;
799 if (CStyle)
800 return TC_NotApplicable;
801 // If we didn't pass the ICS, we already got an error message.
802 msg = 0;
803 return TC_Failed;
804 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000805
806 // FIXME: To get a proper error from invalid conversions here, we need to
807 // reimplement more of this.
808 // FIXME: This does not actually perform the conversion, and thus does not
809 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000810 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000811 Self.TryImplicitConversion(SrcExpr, DestType,
812 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000813 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000814 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000815 /*InOverloadResolution=*/false,
816 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Anders Carlsson3c31a392009-09-26 00:12:34 +0000818 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
819 return TC_NotApplicable;
820
Anders Carlsson0aebc812009-09-09 21:33:21 +0000821 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) {
Anders Carlsson3c31a392009-09-26 00:12:34 +0000822 ConversionDecl = cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction);
823 if (isa<CXXConstructorDecl>(ConversionDecl))
824 Kind = CastExpr::CK_ConstructorConversion;
825 else if (isa<CXXConversionDecl>(ConversionDecl))
826 Kind = CastExpr::CK_UserDefinedConversion;
827 } else if (ICS.ConversionKind ==
828 ImplicitConversionSequence::StandardConversion) {
829 // FIXME: Set the cast kind depending on which types of conversions we have.
Anders Carlsson0aebc812009-09-09 21:33:21 +0000830 }
Anders Carlsson3c31a392009-09-26 00:12:34 +0000831
832 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000833}
834
835/// TryConstCast - See if a const_cast from source to destination is allowed,
836/// and perform it if it is.
837static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
838 bool CStyle, unsigned &msg) {
839 DestType = Self.Context.getCanonicalType(DestType);
840 QualType SrcType = SrcExpr->getType();
841 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000842 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000843 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
844 // Cannot const_cast non-lvalue to lvalue reference type. But if this
845 // is C-style, static_cast might find a way, so we simply suggest a
846 // message and tell the parent to keep searching.
847 msg = diag::err_bad_cxx_cast_rvalue;
848 return TC_NotApplicable;
849 }
850
851 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
852 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
853 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
854 SrcType = Self.Context.getPointerType(SrcType);
855 }
856
857 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
858 // the rules for const_cast are the same as those used for pointers.
859
860 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
861 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
862 // was a reference type, we converted it to a pointer above.
863 // The status of rvalue references isn't entirely clear, but it looks like
864 // conversion to them is simply invalid.
865 // C++ 5.2.11p3: For two pointer types [...]
866 if (!CStyle)
867 msg = diag::err_bad_const_cast_dest;
868 return TC_NotApplicable;
869 }
870 if (DestType->isFunctionPointerType() ||
871 DestType->isMemberFunctionPointerType()) {
872 // Cannot cast direct function pointers.
873 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
874 // T is the ultimate pointee of source and target type.
875 if (!CStyle)
876 msg = diag::err_bad_const_cast_dest;
877 return TC_NotApplicable;
878 }
879 SrcType = Self.Context.getCanonicalType(SrcType);
880
881 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
882 // completely equal.
883 // FIXME: const_cast should probably not be able to convert between pointers
884 // to different address spaces.
885 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
886 // in multi-level pointers may change, but the level count must be the same,
887 // as must be the final pointee type.
888 while (SrcType != DestType &&
889 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
890 SrcType = SrcType.getUnqualifiedType();
891 DestType = DestType.getUnqualifiedType();
892 }
893
894 // Since we're dealing in canonical types, the remainder must be the same.
895 if (SrcType != DestType)
896 return TC_NotApplicable;
897
898 return TC_Success;
899}
900
901static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
902 QualType DestType, bool CStyle,
903 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000904 unsigned &msg,
905 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000906 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
907
908 DestType = Self.Context.getCanonicalType(DestType);
909 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000910 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000911 bool LValue = DestTypeTmp->isLValueReferenceType();
912 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
913 // Cannot cast non-lvalue to reference type. See the similar comment in
914 // const_cast.
915 msg = diag::err_bad_cxx_cast_rvalue;
916 return TC_NotApplicable;
917 }
918
919 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
920 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
921 // built-in & and * operators.
922 // This code does this transformation for the checked types.
923 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
924 SrcType = Self.Context.getPointerType(SrcType);
925 }
926
927 // Canonicalize source for comparison.
928 SrcType = Self.Context.getCanonicalType(SrcType);
929
Ted Kremenek6217b802009-07-29 21:53:49 +0000930 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
931 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000932 if (DestMemPtr && SrcMemPtr) {
933 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
934 // can be explicitly converted to an rvalue of type "pointer to member
935 // of Y of type T2" if T1 and T2 are both function types or both object
936 // types.
937 if (DestMemPtr->getPointeeType()->isFunctionType() !=
938 SrcMemPtr->getPointeeType()->isFunctionType())
939 return TC_NotApplicable;
940
941 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
942 // constness.
943 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
944 // we accept it.
945 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
946 msg = diag::err_bad_cxx_cast_const_away;
947 return TC_Failed;
948 }
949
950 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000951 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000952 return TC_Success;
953 }
954
955 // See below for the enumeral issue.
956 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
957 !DestType->isEnumeralType()) {
958 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
959 // type large enough to hold it. A value of std::nullptr_t can be
960 // converted to an integral type; the conversion has the same meaning
961 // and validity as a conversion of (void*)0 to the integral type.
962 if (Self.Context.getTypeSize(SrcType) >
963 Self.Context.getTypeSize(DestType)) {
964 msg = diag::err_bad_reinterpret_cast_small_int;
965 return TC_Failed;
966 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000967 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000968 return TC_Success;
969 }
970
Anders Carlsson0de51bc2009-09-16 19:19:43 +0000971 bool destIsVector = DestType->isVectorType();
972 bool srcIsVector = SrcType->isVectorType();
973 if (srcIsVector || destIsVector) {
974 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
975 bool destIsScalar =
976 DestType->isIntegralType() && !DestType->isEnumeralType();
977
978 // Check if this is a cast between a vector and something else.
979 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
980 !(srcIsVector && destIsVector))
981 return TC_NotApplicable;
982
983 // If both types have the same size, we can successfully cast.
984 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
985 return TC_Success;
986
987 if (destIsScalar)
988 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
989 else if (srcIsScalar)
990 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
991 else
992 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
993
994 return TC_Failed;
995 }
996
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000997 bool destIsPtr = DestType->isPointerType();
998 bool srcIsPtr = SrcType->isPointerType();
999 if (!destIsPtr && !srcIsPtr) {
1000 // Except for std::nullptr_t->integer and lvalue->reference, which are
1001 // handled above, at least one of the two arguments must be a pointer.
1002 return TC_NotApplicable;
1003 }
1004
1005 if (SrcType == DestType) {
1006 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1007 // restrictions, a cast to the same type is allowed. The intent is not
1008 // entirely clear here, since all other paragraphs explicitly forbid casts
1009 // to the same type. However, the behavior of compilers is pretty consistent
1010 // on this point: allow same-type conversion if the involved types are
1011 // pointers, disallow otherwise.
1012 return TC_Success;
1013 }
1014
1015 // Note: Clang treats enumeration types as integral types. If this is ever
1016 // changed for C++, the additional check here will be redundant.
1017 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1018 assert(srcIsPtr && "One type must be a pointer");
1019 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1020 // type large enough to hold it.
1021 if (Self.Context.getTypeSize(SrcType) >
1022 Self.Context.getTypeSize(DestType)) {
1023 msg = diag::err_bad_reinterpret_cast_small_int;
1024 return TC_Failed;
1025 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001026 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001027 return TC_Success;
1028 }
1029
1030 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1031 assert(destIsPtr && "One type must be a pointer");
1032 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1033 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001034 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001035 return TC_Success;
1036 }
1037
1038 if (!destIsPtr || !srcIsPtr) {
1039 // With the valid non-pointer conversions out of the way, we can be even
1040 // more stringent.
1041 return TC_NotApplicable;
1042 }
1043
1044 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1045 // The C-style cast operator can.
1046 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1047 msg = diag::err_bad_cxx_cast_const_away;
1048 return TC_Failed;
1049 }
1050
1051 // Not casting away constness, so the only remaining check is for compatible
1052 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001053 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001054
1055 if (SrcType->isFunctionPointerType()) {
1056 if (DestType->isFunctionPointerType()) {
1057 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1058 // a pointer to a function of a different type.
1059 return TC_Success;
1060 }
1061
1062 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1063 // an object type or vice versa is conditionally-supported.
1064 // Compilers support it in C++03 too, though, because it's necessary for
1065 // casting the return value of dlsym() and GetProcAddress().
1066 // FIXME: Conditionally-supported behavior should be configurable in the
1067 // TargetInfo or similar.
1068 if (!Self.getLangOptions().CPlusPlus0x)
1069 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1070 return TC_Success;
1071 }
1072
1073 if (DestType->isFunctionPointerType()) {
1074 // See above.
1075 if (!Self.getLangOptions().CPlusPlus0x)
1076 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1077 return TC_Success;
1078 }
1079
1080 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1081 // a pointer to an object of different type.
1082 // Void pointers are not specified, but supported by every compiler out there.
1083 // So we finish by allowing everything that remains - it's got to be two
1084 // object pointers.
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001085 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001086 return TC_Success;
1087}
1088
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001089bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001090 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001091 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001092 // This test is outside everything else because it's the only case where
1093 // a non-lvalue-reference target type does not lead to decay.
1094 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001095 if (CastTy->isVoidType()) {
1096 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001097 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001098 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001099
1100 // If the type is dependent, we won't do any other semantic analysis now.
1101 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1102 return false;
1103
1104 if (!CastTy->isLValueReferenceType())
1105 DefaultFunctionArrayConversion(CastExpr);
1106
1107 // C++ [expr.cast]p5: The conversions performed by
1108 // - a const_cast,
1109 // - a static_cast,
1110 // - a static_cast followed by a const_cast,
1111 // - a reinterpret_cast, or
1112 // - a reinterpret_cast followed by a const_cast,
1113 // can be performed using the cast notation of explicit type conversion.
1114 // [...] If a conversion can be interpreted in more than one of the ways
1115 // listed above, the interpretation that appears first in the list is used,
1116 // even if a cast resulting from that interpretation is ill-formed.
1117 // In plain language, this means trying a const_cast ...
1118 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001119 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1120 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001121 if (tcr == TC_Success)
1122 Kind = CastExpr::CK_NoOp;
1123
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001124 if (tcr == TC_NotApplicable) {
1125 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001126 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1127 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001128 if (tcr == TC_NotApplicable) {
1129 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001130 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1131 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001132 }
1133 }
1134
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001135 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001136 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001137 << CastExpr->getType() << CastTy << R;
1138
1139 return tcr != TC_Success;
1140}