blob: 014cec2b650c4439595114d2f41c4df7d49188d8 [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"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000022using namespace clang;
23
Sebastian Redl9cc11e72009-07-25 15:41:38 +000024enum TryCastResult {
25 TC_NotApplicable, ///< The cast method is not applicable.
26 TC_Success, ///< The cast method is appropriate and successful.
27 TC_Failed ///< The cast method is appropriate, but failed. A
28 ///< diagnostic has been emitted.
29};
30
31enum CastType {
32 CT_Const, ///< const_cast
33 CT_Static, ///< static_cast
34 CT_Reinterpret, ///< reinterpret_cast
35 CT_Dynamic, ///< dynamic_cast
36 CT_CStyle, ///< (Type)expr
37 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000038};
39
40static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
41 const SourceRange &OpRange,
42 const SourceRange &DestRange);
43static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
44 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000045 const SourceRange &DestRange,
46 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000047static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000048 const SourceRange &OpRange,
Anders Carlsson0aebc812009-09-09 21:33:21 +000049 CastExpr::CastKind &Kind,
50 CXXMethodDecl *&ConversionDecl);
Sebastian Redl37d6de32008-11-08 13:00:26 +000051static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
52 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000053 const SourceRange &DestRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000054 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000055
56static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000057
58// The Try functions attempt a specific way of casting. If they succeed, they
59// return TC_Success. If their way of casting is not appropriate for the given
60// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
61// to emit if no other way succeeds. If their way of casting is appropriate but
62// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
63// they emit a specialized diagnostic.
64// All diagnostics returned by these functions must expect the same three
65// arguments:
66// %0: Cast Type (a value from the CastType enumeration)
67// %1: Source Type
68// %2: Destination Type
69static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
70 QualType DestType, unsigned &msg);
71static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
72 QualType DestType, bool CStyle,
73 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000074 unsigned &msg,
75 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000076static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
77 QualType DestType, bool CStyle,
78 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000079 unsigned &msg,
80 CastExpr::CastKind &Kind);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000081static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
82 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000083 const SourceRange &OpRange,
84 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000085 QualType OrigDestType, unsigned &msg,
86 CastExpr::CastKind &Kind);
Douglas Gregor4ce46c22010-03-07 23:24:59 +000087static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
88 QualType SrcType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000089 QualType DestType,bool CStyle,
90 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +000091 unsigned &msg,
92 CastExpr::CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000093static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000094 QualType DestType, bool CStyle,
95 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +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 Redla82e4ae2009-11-14 21:15:49 +000099static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000102 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000103 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000104 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000105static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
106 bool CStyle, unsigned &msg);
107static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
108 QualType DestType, bool CStyle,
109 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000110 unsigned &msg,
111 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000112
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000114Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000115Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
116 SourceLocation LAngleBracketLoc, TypeTy *Ty,
117 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000118 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000119 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000120
John McCall9d125032010-01-15 18:39:57 +0000121 TypeSourceInfo *DestTInfo;
122 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
123 if (!DestTInfo)
124 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000125
126 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
127 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
128 SourceRange(LParenLoc, RParenLoc));
129}
130
131Action::OwningExprResult
132Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
133 TypeSourceInfo *DestTInfo, ExprArg E,
134 SourceRange AngleBrackets, SourceRange Parens) {
135 Expr *Ex = E.takeAs<Expr>();
136 QualType DestType = DestTInfo->getType();
137
138 SourceRange OpRange(OpLoc, Parens.getEnd());
139 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000140
Douglas Gregor9103bb22008-12-17 22:52:20 +0000141 // If the type is dependent, we won't do the semantic analysis now.
142 // FIXME: should we check this in a more fine-grained manner?
143 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
144
Sebastian Redl26d85b12008-11-05 21:50:06 +0000145 switch (Kind) {
146 default: assert(0 && "Unknown C++ cast!");
147
148 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000149 if (!TypeDependent)
150 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000152 Ex, DestTInfo, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000153
Anders Carlsson714179b2009-08-02 19:07:59 +0000154 case tok::kw_dynamic_cast: {
155 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000156 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000157 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000158 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000159 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson714179b2009-08-02 19:07:59 +0000160 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000161 case tok::kw_reinterpret_cast: {
162 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000163 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000164 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 return Owned(new (Context) CXXReinterpretCastExpr(
166 DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000167 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000168 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000169 case tok::kw_static_cast: {
170 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000171 if (!TypeDependent) {
172 CXXMethodDecl *Method = 0;
173
174 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
175
176 if (Method) {
177 OwningExprResult CastArg
178 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
179 Kind, Method, Owned(Ex));
180 if (CastArg.isInvalid())
181 return ExprError();
182
183 Ex = CastArg.takeAs<Expr>();
184 }
185 }
186
Sebastian Redlf53597f2009-03-15 17:47:39 +0000187 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000188 Kind, Ex, DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000189 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000190 }
191
Sebastian Redlf53597f2009-03-15 17:47:39 +0000192 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000193}
194
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000195/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
196/// this removes one level of indirection from both types, provided that they're
197/// the same kind of pointer (plain or to-member). Unlike the Sema function,
198/// this one doesn't care if the two pointers-to-member don't point into the
199/// same class. This is because CastsAwayConstness doesn't care.
200bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
201 const PointerType *T1PtrType = T1->getAs<PointerType>(),
202 *T2PtrType = T2->getAs<PointerType>();
203 if (T1PtrType && T2PtrType) {
204 T1 = T1PtrType->getPointeeType();
205 T2 = T2PtrType->getPointeeType();
206 return true;
207 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000208 const ObjCObjectPointerType *T1ObjCPtrType =
209 T1->getAs<ObjCObjectPointerType>(),
210 *T2ObjCPtrType =
211 T2->getAs<ObjCObjectPointerType>();
212 if (T1ObjCPtrType) {
213 if (T2ObjCPtrType) {
214 T1 = T1ObjCPtrType->getPointeeType();
215 T2 = T2ObjCPtrType->getPointeeType();
216 return true;
217 }
218 else if (T2PtrType) {
219 T1 = T1ObjCPtrType->getPointeeType();
220 T2 = T2PtrType->getPointeeType();
221 return true;
222 }
223 }
224 else if (T2ObjCPtrType) {
225 if (T1PtrType) {
226 T2 = T2ObjCPtrType->getPointeeType();
227 T1 = T1PtrType->getPointeeType();
228 return true;
229 }
230 }
231
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000232 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
233 *T2MPType = T2->getAs<MemberPointerType>();
234 if (T1MPType && T2MPType) {
235 T1 = T1MPType->getPointeeType();
236 T2 = T2MPType->getPointeeType();
237 return true;
238 }
239 return false;
240}
241
Sebastian Redldb647282009-01-27 23:18:31 +0000242/// CastsAwayConstness - Check if the pointer conversion from SrcType to
243/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
244/// the cast checkers. Both arguments must denote pointer (possibly to member)
245/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000246static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000247CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000248 // Casting away constness is defined in C++ 5.2.11p8 with reference to
249 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
250 // the rules are non-trivial. So first we construct Tcv *...cv* as described
251 // in C++ 5.2.11p8.
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000252 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000253 "Source type is not pointer or pointer to member.");
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000254 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000255 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000256
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000257 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
258 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000259 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000260
261 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000262 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000263 cv1.push_back(UnwrappedSrcType.getQualifiers());
264 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000265 }
266 assert(cv1.size() > 0 && "Must have at least one pointer level.");
267
268 // Construct void pointers with those qualifiers (in reverse order of
269 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000270 QualType SrcConstruct = Self.Context.VoidTy;
271 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000272 ASTContext &Context = Self.Context;
273 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
274 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000275 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000276 SrcConstruct
277 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
278 DestConstruct
279 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280 }
281
282 // Test if they're compatible.
283 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000284 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000285}
286
Sebastian Redl26d85b12008-11-05 21:50:06 +0000287/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
288/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
289/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000290static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000291CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
292 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000293 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000294 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000295 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000296
297 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
298 // or "pointer to cv void".
299
300 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000301 const PointerType *DestPointer = DestType->getAs<PointerType>();
302 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000303 if (DestPointer) {
304 DestPointee = DestPointer->getPointeeType();
305 } else if (DestReference) {
306 DestPointee = DestReference->getPointeeType();
307 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000308 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000309 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000310 return;
311 }
312
Ted Kremenek6217b802009-07-29 21:53:49 +0000313 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000314 if (DestPointee->isVoidType()) {
315 assert(DestPointer && "Reference to void is not possible");
316 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000317 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000318 PDiag(diag::err_bad_dynamic_cast_incomplete)
319 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000320 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000322 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000323 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000324 return;
325 }
326
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000327 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
328 // complete class type, [...]. If T is an lvalue reference type, v shall be
329 // an lvalue of a complete class type, [...]. If T is an rvalue reference
330 // type, v shall be an expression having a complete effective class type,
331 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000332
Sebastian Redl37d6de32008-11-08 13:00:26 +0000333 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000334 QualType SrcPointee;
335 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000336 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000337 SrcPointee = SrcPointer->getPointeeType();
338 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000339 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000340 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000341 return;
342 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000343 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000344 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000345 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000346 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000347 }
348 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000349 } else {
350 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000351 }
352
Ted Kremenek6217b802009-07-29 21:53:49 +0000353 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000354 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000355 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000356 PDiag(diag::err_bad_dynamic_cast_incomplete)
357 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000358 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000359 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000360 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000361 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000362 return;
363 }
364
365 assert((DestPointer || DestReference) &&
366 "Bad destination non-ptr/ref slipped through.");
367 assert((DestRecord || DestPointee->isVoidType()) &&
368 "Bad destination pointee slipped through.");
369 assert(SrcRecord && "Bad source pointee slipped through.");
370
371 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
372 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000373 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000374 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000375 return;
376 }
377
378 // C++ 5.2.7p3: If the type of v is the same as the required result type,
379 // [except for cv].
380 if (DestRecord == SrcRecord) {
381 return;
382 }
383
384 // C++ 5.2.7p5
385 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000386 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
387 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000388 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000389 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000390 // Diagnostic already emitted on error.
391 return;
392 }
393
394 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000395 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000396 assert(SrcDecl && "Definition missing");
397 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000398 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000399 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000400 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000401
402 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000403 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000404}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000405
406/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
407/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
408/// like this:
409/// const char *str = "literal";
410/// legacy_function(const_cast\<char*\>(str));
411void
412CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000413 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000414 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000415 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000416
417 unsigned msg = diag::err_bad_cxx_cast_generic;
418 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
419 && msg != 0)
420 Self.Diag(OpRange.getBegin(), msg) << CT_Const
421 << SrcExpr->getType() << DestType << OpRange;
422}
423
424/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
425/// valid.
426/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
427/// like this:
428/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
429void
430CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000431 const SourceRange &OpRange, const SourceRange &DestRange,
432 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000433 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000434 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000435
436 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000437 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
438 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000439 != TC_Success && msg != 0)
440 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
441 << SrcExpr->getType() << DestType << OpRange;
442}
443
444
445/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
446/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
447/// implicit conversions explicit and getting rid of data loss warnings.
448void
449CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000450 const SourceRange &OpRange, CastExpr::CastKind &Kind,
451 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000452 // This test is outside everything else because it's the only case where
453 // a non-lvalue-reference target type does not lead to decay.
454 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000455 if (DestType->isVoidType()) {
456 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000457 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000458 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000459
Douglas Gregorb653c522009-11-06 01:14:41 +0000460 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000461 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000462
463 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000464 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000465 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000466 != TC_Success && msg != 0)
467 Self.Diag(OpRange.getBegin(), msg) << CT_Static
468 << SrcExpr->getType() << DestType << OpRange;
469}
470
471/// TryStaticCast - Check if a static cast can be performed, and do so if
472/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
473/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000474static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000475 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000476 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000477 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000478 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000479 // The order the tests is not entirely arbitrary. There is one conversion
480 // that can be handled in two different ways. Given:
481 // struct A {};
482 // struct B : public A {
483 // B(); B(const A&);
484 // };
485 // const A &a = B();
486 // the cast static_cast<const B&>(a) could be seen as either a static
487 // reference downcast, or an explicit invocation of the user-defined
488 // conversion using B's conversion constructor.
489 // DR 427 specifies that the downcast is to be applied here.
490
491 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
492 // Done outside this function.
493
494 TryCastResult tcr;
495
496 // C++ 5.2.9p5, reference downcast.
497 // See the function for details.
498 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000499 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000500 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000501 if (tcr != TC_NotApplicable)
502 return tcr;
503
504 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
505 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
506 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000507 if (tcr != TC_NotApplicable) {
508 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000509 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000510 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000511
512 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
513 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000514 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000515 Kind, ConversionDecl);
516 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000517 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000518
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000519 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
520 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
521 // conversions, subject to further restrictions.
522 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
523 // of qualification conversions impossible.
524 // In the CStyle case, the earlier attempt to const_cast should have taken
525 // care of reverse qualification conversions.
526
527 QualType OrigSrcType = SrcExpr->getType();
528
529 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
530
531 // Reverse integral promotion/conversion. All such conversions are themselves
532 // again integral promotions or conversions and are thus already handled by
533 // p2 (TryDirectInitialization above).
534 // (Note: any data loss warnings should be suppressed.)
535 // The exception is the reverse of enum->integer, i.e. integer->enum (and
536 // enum->enum). See also C++ 5.2.9p7.
537 // The same goes for reverse floating point promotion/conversion and
538 // floating-integral conversions. Again, only floating->enum is relevant.
539 if (DestType->isEnumeralType()) {
540 if (SrcType->isComplexType() || SrcType->isVectorType()) {
541 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000542 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
543 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000544 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000545 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000546 }
547
548 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
549 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000550 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
551 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000552 if (tcr != TC_NotApplicable)
553 return tcr;
554
555 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
556 // conversion. C++ 5.2.9p9 has additional information.
557 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000558 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000559 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000560 if (tcr != TC_NotApplicable)
561 return tcr;
562
563 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
564 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
565 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000566 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000567 QualType SrcPointee = SrcPointer->getPointeeType();
568 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000569 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000570 QualType DestPointee = DestPointer->getPointeeType();
571 if (DestPointee->isIncompleteOrObjectType()) {
572 // This is definitely the intended conversion, but it might fail due
573 // to a const violation.
574 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
575 msg = diag::err_bad_cxx_cast_const_away;
576 return TC_Failed;
577 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000578 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000579 return TC_Success;
580 }
581 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000582 else if (CStyle && DestType->isObjCObjectPointerType()) {
583 // allow c-style cast of objective-c pointers as they are pervasive.
584 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
585 return TC_Success;
586 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000587 else if (CStyle && DestType->isBlockPointerType()) {
588 // allow c-style cast of void * to block pointers.
589 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
590 return TC_Success;
591 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000592 }
593 }
594
595 // We tried everything. Everything! Nothing works! :-(
596 return TC_NotApplicable;
597}
598
599/// Tests whether a conversion according to N2844 is valid.
600TryCastResult
601TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000602 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000603 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
604 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000605 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000606 if (!R)
607 return TC_NotApplicable;
608
609 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
610 return TC_NotApplicable;
611
612 // Because we try the reference downcast before this function, from now on
613 // this is the only cast possibility, so we issue an error if we fail now.
614 // FIXME: Should allow casting away constness if CStyle.
615 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000616 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
617 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000618 DerivedToBase) <
619 Sema::Ref_Compatible_With_Added_Qualification) {
620 msg = diag::err_bad_lvalue_to_rvalue_cast;
621 return TC_Failed;
622 }
623
624 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
625 // than nothing.
626 return TC_Success;
627}
628
629/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
630TryCastResult
631TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
632 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000633 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000634 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
635 // cast to type "reference to cv2 D", where D is a class derived from B,
636 // if a valid standard conversion from "pointer to D" to "pointer to B"
637 // exists, cv2 >= cv1, and B is not a virtual base class of D.
638 // In addition, DR54 clarifies that the base must be accessible in the
639 // current context. Although the wording of DR54 only applies to the pointer
640 // variant of this rule, the intent is clearly for it to apply to the this
641 // conversion as well.
642
Ted Kremenek6217b802009-07-29 21:53:49 +0000643 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000644 if (!DestReference) {
645 return TC_NotApplicable;
646 }
647 bool RValueRef = DestReference->isRValueReferenceType();
648 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
649 // We know the left side is an lvalue reference, so we can suggest a reason.
650 msg = diag::err_bad_cxx_cast_rvalue;
651 return TC_NotApplicable;
652 }
653
654 QualType DestPointee = DestReference->getPointeeType();
655
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000656 return TryStaticDowncast(Self,
657 Self.Context.getCanonicalType(SrcExpr->getType()),
658 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000659 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000660}
661
662/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
663TryCastResult
664TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000665 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000666 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000667 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
668 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
669 // is a class derived from B, if a valid standard conversion from "pointer
670 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
671 // class of D.
672 // In addition, DR54 clarifies that the base must be accessible in the
673 // current context.
674
Ted Kremenek6217b802009-07-29 21:53:49 +0000675 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000676 if (!DestPointer) {
677 return TC_NotApplicable;
678 }
679
Ted Kremenek6217b802009-07-29 21:53:49 +0000680 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000681 if (!SrcPointer) {
682 msg = diag::err_bad_static_cast_pointer_nonpointer;
683 return TC_NotApplicable;
684 }
685
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000686 return TryStaticDowncast(Self,
687 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
688 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
689 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000690}
691
692/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
693/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000694/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000695TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000696TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000697 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000698 QualType OrigDestType, unsigned &msg,
699 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000700 // We can only work with complete types. But don't complain if it doesn't work
701 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
702 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
703 return TC_NotApplicable;
704
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000705 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000706 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000707 return TC_NotApplicable;
708 }
709
Douglas Gregora8f32e02009-10-06 17:59:45 +0000710 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
711 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000712 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
713 return TC_NotApplicable;
714 }
715
716 // Target type does derive from source type. Now we're serious. If an error
717 // appears now, it's not ignored.
718 // This may not be entirely in line with the standard. Take for example:
719 // struct A {};
720 // struct B : virtual A {
721 // B(A&);
722 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000723 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000724 // void f()
725 // {
726 // (void)static_cast<const B&>(*((A*)0));
727 // }
728 // As far as the standard is concerned, p5 does not apply (A is virtual), so
729 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
730 // However, both GCC and Comeau reject this example, and accepting it would
731 // mean more complex code if we're to preserve the nice error message.
732 // FIXME: Being 100% compliant here would be nice to have.
733
734 // Must preserve cv, as always, unless we're in C-style mode.
735 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
736 msg = diag::err_bad_cxx_cast_const_away;
737 return TC_Failed;
738 }
739
740 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
741 // This code is analoguous to that in CheckDerivedToBaseConversion, except
742 // that it builds the paths in reverse order.
743 // To sum up: record all paths to the base and build a nice string from
744 // them. Use it to spice up the error message.
745 if (!Paths.isRecordingPaths()) {
746 Paths.clear();
747 Paths.setRecordingPaths(true);
748 Self.IsDerivedFrom(DestType, SrcType, Paths);
749 }
750 std::string PathDisplayStr;
751 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000752 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000753 PI != PE; ++PI) {
754 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
755 // We haven't displayed a path to this particular base
756 // class subobject yet.
757 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000758 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
759 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000760 EI != EE; ++EI)
761 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000762 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000763 }
764 }
765
766 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000767 << QualType(SrcType).getUnqualifiedType()
768 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000769 << PathDisplayStr << OpRange;
770 msg = 0;
771 return TC_Failed;
772 }
773
774 if (Paths.getDetectedVirtual() != 0) {
775 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
776 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
777 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
778 msg = 0;
779 return TC_Failed;
780 }
781
John McCall6b2accb2010-02-10 09:31:12 +0000782 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000783 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000784 Paths.front(),
785 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000786 msg = 0;
787 return TC_Failed;
788 }
789
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000790 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000791 return TC_Success;
792}
793
794/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
795/// C++ 5.2.9p9 is valid:
796///
797/// An rvalue of type "pointer to member of D of type cv1 T" can be
798/// converted to an rvalue of type "pointer to member of B of type cv2 T",
799/// where B is a base class of D [...].
800///
801TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000802TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
803 QualType DestType, bool CStyle,
804 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000805 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000806 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000807 if (!DestMemPtr)
808 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000809
810 bool WasOverloadedFunction = false;
811 if (FunctionDecl *Fn
812 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false)) {
813 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
814 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
815 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
816 WasOverloadedFunction = true;
817 }
818
Ted Kremenek6217b802009-07-29 21:53:49 +0000819 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000820 if (!SrcMemPtr) {
821 msg = diag::err_bad_static_cast_member_pointer_nonmp;
822 return TC_NotApplicable;
823 }
824
825 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000826 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
827 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000828 return TC_NotApplicable;
829
830 // B base of D
831 QualType SrcClass(SrcMemPtr->getClass(), 0);
832 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000833 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000834 /*DetectVirtual=*/true);
835 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
836 return TC_NotApplicable;
837 }
838
839 // B is a base of D. But is it an allowed base? If not, it's a hard error.
840 if (Paths.isAmbiguous(DestClass)) {
841 Paths.clear();
842 Paths.setRecordingPaths(true);
843 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
844 assert(StillOkay);
845 StillOkay = StillOkay;
846 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
847 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
848 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
849 msg = 0;
850 return TC_Failed;
851 }
852
853 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
854 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
855 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
856 msg = 0;
857 return TC_Failed;
858 }
859
John McCall6b2accb2010-02-10 09:31:12 +0000860 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000861 DestType, SrcType,
John McCall58e6f342010-03-16 05:22:47 +0000862 Paths.front(),
863 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000864 msg = 0;
865 return TC_Failed;
866 }
867
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000868 if (WasOverloadedFunction) {
869 // Resolve the address of the overloaded function again, this time
870 // allowing complaints if something goes wrong.
871 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
872 DestType,
873 true);
874 if (!Fn) {
875 msg = 0;
876 return TC_Failed;
877 }
878
879 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, Fn);
880 if (!SrcExpr) {
881 msg = 0;
882 return TC_Failed;
883 }
884 }
885
Anders Carlsson1a31a182009-10-30 00:46:35 +0000886 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000887 return TC_Success;
888}
889
890/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
891/// is valid:
892///
893/// An expression e can be explicitly converted to a type T using a
894/// @c static_cast if the declaration "T t(e);" is well-formed [...].
895TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000896TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000897 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000898 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000900 if (DestType->isRecordType()) {
901 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
902 diag::err_bad_dynamic_cast_incomplete)) {
903 msg = 0;
904 return TC_Failed;
905 }
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000908 if (DestType->isReferenceType()) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000909 // All reference bindings insert implicit casts above that do the actual
910 // casting.
911 Kind = CastExpr::CK_NoOp;
912
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000913 // At this point of CheckStaticCast, if the destination is a reference,
914 // this has to work. There is no other way that works.
915 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000916 // the reinterpret_cast way. So in C-style mode, we first try the call
917 // with an ICS to suppress errors.
918 if (CStyle) {
919 ImplicitConversionSequence ICS;
920 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
921 /*SuppressUserConversions=*/false,
922 /*AllowExplicit=*/false, /*ForceRValue=*/false,
923 &ICS))
924 return TC_NotApplicable;
925 }
926 // Now we're committed either way.
927 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
928 /*SuppressUserConversions=*/false,
929 /*AllowExplicit=*/false,
930 /*ForceRValue=*/false, 0,
931 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000932 return TC_Success;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000933
934 // We already got an error message.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000935 msg = 0;
936 return TC_Failed;
937 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000938
Douglas Gregor19aeac62009-11-14 03:27:21 +0000939 if (DestType->isRecordType()) {
940 if (CXXConstructorDecl *Constructor
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000941 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregor19aeac62009-11-14 03:27:21 +0000942 OpRange.getBegin(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000943 InitializationKind::CreateDirect(OpRange.getBegin(),
944 OpRange.getBegin(),
945 OpRange.getEnd()))) {
Douglas Gregor19aeac62009-11-14 03:27:21 +0000946 ConversionDecl = Constructor;
947 Kind = CastExpr::CK_ConstructorConversion;
948 return TC_Success;
949 }
950
951 return TC_NotApplicable;
952 }
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000953
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000954 // FIXME: To get a proper error from invalid conversions here, we need to
955 // reimplement more of this.
956 // FIXME: This does not actually perform the conversion, and thus does not
957 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000958 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000959 Self.TryImplicitConversion(SrcExpr, DestType,
960 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000961 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000962 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000963 /*InOverloadResolution=*/false,
964 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000965
John McCall1d318332010-01-12 00:44:57 +0000966 if (ICS.isBad())
Anders Carlsson3c31a392009-09-26 00:12:34 +0000967 return TC_NotApplicable;
968
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000969 // The conversion is possible, so commit to it.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000970 Kind = CastExpr::CK_NoOp;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000971 msg = 0;
Douglas Gregor68647482009-12-16 03:45:30 +0000972 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, Sema::AA_Casting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000973 /*IgnoreBaseAccess*/CStyle) ?
974 TC_Failed : TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000975}
976
977/// TryConstCast - See if a const_cast from source to destination is allowed,
978/// and perform it if it is.
979static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
980 bool CStyle, unsigned &msg) {
981 DestType = Self.Context.getCanonicalType(DestType);
982 QualType SrcType = SrcExpr->getType();
983 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000984 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000985 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
986 // Cannot const_cast non-lvalue to lvalue reference type. But if this
987 // is C-style, static_cast might find a way, so we simply suggest a
988 // message and tell the parent to keep searching.
989 msg = diag::err_bad_cxx_cast_rvalue;
990 return TC_NotApplicable;
991 }
992
993 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
994 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
995 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
996 SrcType = Self.Context.getPointerType(SrcType);
997 }
998
999 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1000 // the rules for const_cast are the same as those used for pointers.
1001
1002 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
1003 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1004 // was a reference type, we converted it to a pointer above.
1005 // The status of rvalue references isn't entirely clear, but it looks like
1006 // conversion to them is simply invalid.
1007 // C++ 5.2.11p3: For two pointer types [...]
1008 if (!CStyle)
1009 msg = diag::err_bad_const_cast_dest;
1010 return TC_NotApplicable;
1011 }
1012 if (DestType->isFunctionPointerType() ||
1013 DestType->isMemberFunctionPointerType()) {
1014 // Cannot cast direct function pointers.
1015 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1016 // T is the ultimate pointee of source and target type.
1017 if (!CStyle)
1018 msg = diag::err_bad_const_cast_dest;
1019 return TC_NotApplicable;
1020 }
1021 SrcType = Self.Context.getCanonicalType(SrcType);
1022
1023 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1024 // completely equal.
1025 // FIXME: const_cast should probably not be able to convert between pointers
1026 // to different address spaces.
1027 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1028 // in multi-level pointers may change, but the level count must be the same,
1029 // as must be the final pointee type.
1030 while (SrcType != DestType &&
1031 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +00001032 Qualifiers Quals;
1033 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1034 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001035 }
1036
1037 // Since we're dealing in canonical types, the remainder must be the same.
1038 if (SrcType != DestType)
1039 return TC_NotApplicable;
1040
1041 return TC_Success;
1042}
1043
1044static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1045 QualType DestType, bool CStyle,
1046 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001047 unsigned &msg,
1048 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001049 DestType = Self.Context.getCanonicalType(DestType);
1050 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001052 bool LValue = DestTypeTmp->isLValueReferenceType();
1053 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1054 // Cannot cast non-lvalue to reference type. See the similar comment in
1055 // const_cast.
1056 msg = diag::err_bad_cxx_cast_rvalue;
1057 return TC_NotApplicable;
1058 }
1059
1060 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1061 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1062 // built-in & and * operators.
1063 // This code does this transformation for the checked types.
1064 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1065 SrcType = Self.Context.getPointerType(SrcType);
1066 }
1067
1068 // Canonicalize source for comparison.
1069 SrcType = Self.Context.getCanonicalType(SrcType);
1070
Ted Kremenek6217b802009-07-29 21:53:49 +00001071 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1072 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001073 if (DestMemPtr && SrcMemPtr) {
1074 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1075 // can be explicitly converted to an rvalue of type "pointer to member
1076 // of Y of type T2" if T1 and T2 are both function types or both object
1077 // types.
1078 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1079 SrcMemPtr->getPointeeType()->isFunctionType())
1080 return TC_NotApplicable;
1081
1082 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1083 // constness.
1084 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1085 // we accept it.
1086 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1087 msg = diag::err_bad_cxx_cast_const_away;
1088 return TC_Failed;
1089 }
1090
1091 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001092 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001093 return TC_Success;
1094 }
1095
1096 // See below for the enumeral issue.
1097 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1098 !DestType->isEnumeralType()) {
1099 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1100 // type large enough to hold it. A value of std::nullptr_t can be
1101 // converted to an integral type; the conversion has the same meaning
1102 // and validity as a conversion of (void*)0 to the integral type.
1103 if (Self.Context.getTypeSize(SrcType) >
1104 Self.Context.getTypeSize(DestType)) {
1105 msg = diag::err_bad_reinterpret_cast_small_int;
1106 return TC_Failed;
1107 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001108 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001109 return TC_Success;
1110 }
1111
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001112 bool destIsVector = DestType->isVectorType();
1113 bool srcIsVector = SrcType->isVectorType();
1114 if (srcIsVector || destIsVector) {
1115 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1116 bool destIsScalar =
1117 DestType->isIntegralType() && !DestType->isEnumeralType();
1118
1119 // Check if this is a cast between a vector and something else.
1120 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1121 !(srcIsVector && destIsVector))
1122 return TC_NotApplicable;
1123
1124 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001125 if (Self.Context.getTypeSize(SrcType)
1126 == Self.Context.getTypeSize(DestType)) {
1127 Kind = CastExpr::CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001128 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001129 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001130
1131 if (destIsScalar)
1132 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1133 else if (srcIsScalar)
1134 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1135 else
1136 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1137
1138 return TC_Failed;
1139 }
1140
Fariborz Jahanian72a86592010-02-03 20:32:31 +00001141 bool destIsPtr = DestType->isAnyPointerType();
1142 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001143 if (!destIsPtr && !srcIsPtr) {
1144 // Except for std::nullptr_t->integer and lvalue->reference, which are
1145 // handled above, at least one of the two arguments must be a pointer.
1146 return TC_NotApplicable;
1147 }
1148
1149 if (SrcType == DestType) {
1150 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1151 // restrictions, a cast to the same type is allowed. The intent is not
1152 // entirely clear here, since all other paragraphs explicitly forbid casts
1153 // to the same type. However, the behavior of compilers is pretty consistent
1154 // on this point: allow same-type conversion if the involved types are
1155 // pointers, disallow otherwise.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001156 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001157 return TC_Success;
1158 }
1159
1160 // Note: Clang treats enumeration types as integral types. If this is ever
1161 // changed for C++, the additional check here will be redundant.
1162 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1163 assert(srcIsPtr && "One type must be a pointer");
1164 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1165 // type large enough to hold it.
1166 if (Self.Context.getTypeSize(SrcType) >
1167 Self.Context.getTypeSize(DestType)) {
1168 msg = diag::err_bad_reinterpret_cast_small_int;
1169 return TC_Failed;
1170 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001171 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001172 return TC_Success;
1173 }
1174
1175 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1176 assert(destIsPtr && "One type must be a pointer");
1177 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1178 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001179 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001180 return TC_Success;
1181 }
1182
1183 if (!destIsPtr || !srcIsPtr) {
1184 // With the valid non-pointer conversions out of the way, we can be even
1185 // more stringent.
1186 return TC_NotApplicable;
1187 }
1188
1189 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1190 // The C-style cast operator can.
1191 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1192 msg = diag::err_bad_cxx_cast_const_away;
1193 return TC_Failed;
1194 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001195 if (CStyle && DestType->isObjCObjectPointerType()) {
1196 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1197 return TC_Success;
1198 }
1199
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001200 // Not casting away constness, so the only remaining check is for compatible
1201 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001202 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001203
1204 if (SrcType->isFunctionPointerType()) {
1205 if (DestType->isFunctionPointerType()) {
1206 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1207 // a pointer to a function of a different type.
1208 return TC_Success;
1209 }
1210
1211 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1212 // an object type or vice versa is conditionally-supported.
1213 // Compilers support it in C++03 too, though, because it's necessary for
1214 // casting the return value of dlsym() and GetProcAddress().
1215 // FIXME: Conditionally-supported behavior should be configurable in the
1216 // TargetInfo or similar.
1217 if (!Self.getLangOptions().CPlusPlus0x)
1218 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1219 return TC_Success;
1220 }
1221
1222 if (DestType->isFunctionPointerType()) {
1223 // See above.
1224 if (!Self.getLangOptions().CPlusPlus0x)
1225 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1226 return TC_Success;
1227 }
1228
1229 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1230 // a pointer to an object of different type.
1231 // Void pointers are not specified, but supported by every compiler out there.
1232 // So we finish by allowing everything that remains - it's got to be two
1233 // object pointers.
1234 return TC_Success;
1235}
1236
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001237bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001238 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001239 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001240 // This test is outside everything else because it's the only case where
1241 // a non-lvalue-reference target type does not lead to decay.
1242 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001243 if (CastTy->isVoidType()) {
1244 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001245 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001246 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001247
1248 // If the type is dependent, we won't do any other semantic analysis now.
1249 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1250 return false;
1251
Douglas Gregorb653c522009-11-06 01:14:41 +00001252 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001253 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001254
1255 // C++ [expr.cast]p5: The conversions performed by
1256 // - a const_cast,
1257 // - a static_cast,
1258 // - a static_cast followed by a const_cast,
1259 // - a reinterpret_cast, or
1260 // - a reinterpret_cast followed by a const_cast,
1261 // can be performed using the cast notation of explicit type conversion.
1262 // [...] If a conversion can be interpreted in more than one of the ways
1263 // listed above, the interpretation that appears first in the list is used,
1264 // even if a cast resulting from that interpretation is ill-formed.
1265 // In plain language, this means trying a const_cast ...
1266 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001267 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1268 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001269 if (tcr == TC_Success)
1270 Kind = CastExpr::CK_NoOp;
1271
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001272 if (tcr == TC_NotApplicable) {
1273 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001274 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1275 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001276 if (tcr == TC_NotApplicable) {
1277 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001278 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1279 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001280 }
1281 }
1282
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001283 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001284 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001285 << CastExpr->getType() << CastTy << R;
1286
1287 return tcr != TC_Success;
1288}