blob: 393c84a5d8a57cabe240952767010c5090c13218 [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,
Douglas Gregord6e44a32010-04-16 22:09:46 +000049 CastExpr::CastKind &Kind);
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,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000073 unsigned &msg,
74 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000075static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
76 QualType DestType, bool CStyle,
77 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000078 unsigned &msg,
79 CastExpr::CastKind &Kind);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000080static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
81 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000082 const SourceRange &OpRange,
83 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000084 QualType OrigDestType, unsigned &msg,
85 CastExpr::CastKind &Kind);
Douglas Gregor4ce46c22010-03-07 23:24:59 +000086static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
87 QualType SrcType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000088 QualType DestType,bool CStyle,
89 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +000090 unsigned &msg,
91 CastExpr::CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000092static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000093 QualType DestType, bool CStyle,
94 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000095 unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +000096 CastExpr::CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000097static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000098 QualType DestType, bool CStyle,
99 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000100 unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000101 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000102static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
103 bool CStyle, unsigned &msg);
104static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
105 QualType DestType, bool CStyle,
106 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000107 unsigned &msg,
108 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000109
Sebastian Redl26d85b12008-11-05 21:50:06 +0000110/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000111Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000112Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
113 SourceLocation LAngleBracketLoc, TypeTy *Ty,
114 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000115 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000116 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000117
John McCall9d125032010-01-15 18:39:57 +0000118 TypeSourceInfo *DestTInfo;
119 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
120 if (!DestTInfo)
121 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000122
123 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
124 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
125 SourceRange(LParenLoc, RParenLoc));
126}
127
128Action::OwningExprResult
129Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
130 TypeSourceInfo *DestTInfo, ExprArg E,
131 SourceRange AngleBrackets, SourceRange Parens) {
132 Expr *Ex = E.takeAs<Expr>();
133 QualType DestType = DestTInfo->getType();
134
135 SourceRange OpRange(OpLoc, Parens.getEnd());
136 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000137
Douglas Gregor9103bb22008-12-17 22:52:20 +0000138 // If the type is dependent, we won't do the semantic analysis now.
139 // FIXME: should we check this in a more fine-grained manner?
140 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
141
Sebastian Redl26d85b12008-11-05 21:50:06 +0000142 switch (Kind) {
143 default: assert(0 && "Unknown C++ cast!");
144
145 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000146 if (!TypeDependent)
147 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000148 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000149 Ex, DestTInfo, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000150
Anders Carlsson714179b2009-08-02 19:07:59 +0000151 case tok::kw_dynamic_cast: {
152 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000153 // FIXME: Initialize base path!
154 CXXBaseSpecifierArray BasePath;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000155 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000156 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000158 Kind, Ex, BasePath, DestTInfo,
159 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;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000163 // FIXME: Initialize base path!
164 CXXBaseSpecifierArray BasePath;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000165 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000166 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000167 return Owned(new (Context) CXXReinterpretCastExpr(
168 DestType.getNonReferenceType(),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000169 Kind, Ex, BasePath, DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000170 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000171 case tok::kw_static_cast: {
172 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000173 // FIXME: Initialize base path!
174 CXXBaseSpecifierArray BasePath;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000175 if (!TypeDependent)
176 CheckStaticCast(*this, Ex, DestType, OpRange, Kind);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000177
Sebastian Redlf53597f2009-03-15 17:47:39 +0000178 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000179 Kind, Ex, BasePath,
180 DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000181 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000182 }
183
Sebastian Redlf53597f2009-03-15 17:47:39 +0000184 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000185}
186
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000187/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
188/// this removes one level of indirection from both types, provided that they're
189/// the same kind of pointer (plain or to-member). Unlike the Sema function,
190/// this one doesn't care if the two pointers-to-member don't point into the
191/// same class. This is because CastsAwayConstness doesn't care.
192bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
193 const PointerType *T1PtrType = T1->getAs<PointerType>(),
194 *T2PtrType = T2->getAs<PointerType>();
195 if (T1PtrType && T2PtrType) {
196 T1 = T1PtrType->getPointeeType();
197 T2 = T2PtrType->getPointeeType();
198 return true;
199 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000200 const ObjCObjectPointerType *T1ObjCPtrType =
201 T1->getAs<ObjCObjectPointerType>(),
202 *T2ObjCPtrType =
203 T2->getAs<ObjCObjectPointerType>();
204 if (T1ObjCPtrType) {
205 if (T2ObjCPtrType) {
206 T1 = T1ObjCPtrType->getPointeeType();
207 T2 = T2ObjCPtrType->getPointeeType();
208 return true;
209 }
210 else if (T2PtrType) {
211 T1 = T1ObjCPtrType->getPointeeType();
212 T2 = T2PtrType->getPointeeType();
213 return true;
214 }
215 }
216 else if (T2ObjCPtrType) {
217 if (T1PtrType) {
218 T2 = T2ObjCPtrType->getPointeeType();
219 T1 = T1PtrType->getPointeeType();
220 return true;
221 }
222 }
223
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000224 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
225 *T2MPType = T2->getAs<MemberPointerType>();
226 if (T1MPType && T2MPType) {
227 T1 = T1MPType->getPointeeType();
228 T2 = T2MPType->getPointeeType();
229 return true;
230 }
231 return false;
232}
233
Sebastian Redldb647282009-01-27 23:18:31 +0000234/// CastsAwayConstness - Check if the pointer conversion from SrcType to
235/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
236/// the cast checkers. Both arguments must denote pointer (possibly to member)
237/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000238static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000239CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000240 // Casting away constness is defined in C++ 5.2.11p8 with reference to
241 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
242 // the rules are non-trivial. So first we construct Tcv *...cv* as described
243 // in C++ 5.2.11p8.
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000244 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000245 "Source type is not pointer or pointer to member.");
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000246 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000247 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000248
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000249 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
250 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000251 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252
253 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000254 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000255 cv1.push_back(UnwrappedSrcType.getQualifiers());
256 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000257 }
258 assert(cv1.size() > 0 && "Must have at least one pointer level.");
259
260 // Construct void pointers with those qualifiers (in reverse order of
261 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000262 QualType SrcConstruct = Self.Context.VoidTy;
263 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000264 ASTContext &Context = Self.Context;
265 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
266 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000267 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000268 SrcConstruct
269 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
270 DestConstruct
271 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000272 }
273
274 // Test if they're compatible.
275 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000276 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000277}
278
Sebastian Redl26d85b12008-11-05 21:50:06 +0000279/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
280/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
281/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000282static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000283CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
284 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000285 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000286 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000287 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000288
289 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
290 // or "pointer to cv void".
291
292 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000293 const PointerType *DestPointer = DestType->getAs<PointerType>();
294 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000295 if (DestPointer) {
296 DestPointee = DestPointer->getPointeeType();
297 } else if (DestReference) {
298 DestPointee = DestReference->getPointeeType();
299 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000300 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000301 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302 return;
303 }
304
Ted Kremenek6217b802009-07-29 21:53:49 +0000305 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306 if (DestPointee->isVoidType()) {
307 assert(DestPointer && "Reference to void is not possible");
308 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000309 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000310 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000311 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000312 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000314 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000315 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000316 return;
317 }
318
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000319 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
320 // complete class type, [...]. If T is an lvalue reference type, v shall be
321 // an lvalue of a complete class type, [...]. If T is an rvalue reference
322 // type, v shall be an expression having a complete effective class type,
323 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000324
Sebastian Redl37d6de32008-11-08 13:00:26 +0000325 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000326 QualType SrcPointee;
327 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000328 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000329 SrcPointee = SrcPointer->getPointeeType();
330 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000331 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000332 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000333 return;
334 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000335 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000336 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000337 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000338 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000339 }
340 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000341 } else {
342 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000343 }
344
Ted Kremenek6217b802009-07-29 21:53:49 +0000345 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000346 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000347 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000348 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000349 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000350 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000351 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000352 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000353 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000354 return;
355 }
356
357 assert((DestPointer || DestReference) &&
358 "Bad destination non-ptr/ref slipped through.");
359 assert((DestRecord || DestPointee->isVoidType()) &&
360 "Bad destination pointee slipped through.");
361 assert(SrcRecord && "Bad source pointee slipped through.");
362
363 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
364 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000365 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000366 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000367 return;
368 }
369
370 // C++ 5.2.7p3: If the type of v is the same as the required result type,
371 // [except for cv].
372 if (DestRecord == SrcRecord) {
373 return;
374 }
375
376 // C++ 5.2.7p5
377 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000378 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
379 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000380 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000381 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000382 // Diagnostic already emitted on error.
383 return;
384 }
385
386 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000387 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000388 assert(SrcDecl && "Definition missing");
389 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000390 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000391 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000392 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000393
394 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000395 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000396}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000397
398/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
399/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
400/// like this:
401/// const char *str = "literal";
402/// legacy_function(const_cast\<char*\>(str));
403void
404CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000405 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000406 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000407 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000408
409 unsigned msg = diag::err_bad_cxx_cast_generic;
410 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
411 && msg != 0)
412 Self.Diag(OpRange.getBegin(), msg) << CT_Const
413 << SrcExpr->getType() << DestType << OpRange;
414}
415
416/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
417/// valid.
418/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
419/// like this:
420/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
421void
422CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000423 const SourceRange &OpRange, const SourceRange &DestRange,
424 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000425 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000426 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000427
428 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000429 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
430 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000431 != TC_Success && msg != 0)
432 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
433 << SrcExpr->getType() << DestType << OpRange;
434}
435
436
437/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
438/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
439/// implicit conversions explicit and getting rid of data loss warnings.
440void
441CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000442 const SourceRange &OpRange, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000443 // This test is outside everything else because it's the only case where
444 // a non-lvalue-reference target type does not lead to decay.
445 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000446 if (DestType->isVoidType()) {
447 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000448 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000449 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000450
Douglas Gregorb653c522009-11-06 01:14:41 +0000451 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000452 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000453
454 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000455 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000456 Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000457 != TC_Success && msg != 0)
458 Self.Diag(OpRange.getBegin(), msg) << CT_Static
459 << SrcExpr->getType() << DestType << OpRange;
460}
461
462/// TryStaticCast - Check if a static cast can be performed, and do so if
463/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
464/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000465static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000466 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000467 const SourceRange &OpRange, unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000468 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000469 // The order the tests is not entirely arbitrary. There is one conversion
470 // that can be handled in two different ways. Given:
471 // struct A {};
472 // struct B : public A {
473 // B(); B(const A&);
474 // };
475 // const A &a = B();
476 // the cast static_cast<const B&>(a) could be seen as either a static
477 // reference downcast, or an explicit invocation of the user-defined
478 // conversion using B's conversion constructor.
479 // DR 427 specifies that the downcast is to be applied here.
480
481 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
482 // Done outside this function.
483
484 TryCastResult tcr;
485
486 // C++ 5.2.9p5, reference downcast.
487 // See the function for details.
488 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000489 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000490 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000491 if (tcr != TC_NotApplicable)
492 return tcr;
493
494 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
495 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
496 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000497 if (tcr != TC_NotApplicable) {
498 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000499 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000500 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000501
502 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
503 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000504 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000505 Kind);
Anders Carlsson3c31a392009-09-26 00:12:34 +0000506 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000507 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000508
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000509 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
510 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
511 // conversions, subject to further restrictions.
512 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
513 // of qualification conversions impossible.
514 // In the CStyle case, the earlier attempt to const_cast should have taken
515 // care of reverse qualification conversions.
516
517 QualType OrigSrcType = SrcExpr->getType();
518
519 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
520
521 // Reverse integral promotion/conversion. All such conversions are themselves
522 // again integral promotions or conversions and are thus already handled by
523 // p2 (TryDirectInitialization above).
524 // (Note: any data loss warnings should be suppressed.)
525 // The exception is the reverse of enum->integer, i.e. integer->enum (and
526 // enum->enum). See also C++ 5.2.9p7.
527 // The same goes for reverse floating point promotion/conversion and
528 // floating-integral conversions. Again, only floating->enum is relevant.
529 if (DestType->isEnumeralType()) {
530 if (SrcType->isComplexType() || SrcType->isVectorType()) {
531 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000532 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
533 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000534 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000535 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000536 }
537
538 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
539 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000540 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
541 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000542 if (tcr != TC_NotApplicable)
543 return tcr;
544
545 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
546 // conversion. C++ 5.2.9p9 has additional information.
547 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000548 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000549 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000550 if (tcr != TC_NotApplicable)
551 return tcr;
552
553 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
554 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
555 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000556 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000557 QualType SrcPointee = SrcPointer->getPointeeType();
558 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000560 QualType DestPointee = DestPointer->getPointeeType();
561 if (DestPointee->isIncompleteOrObjectType()) {
562 // This is definitely the intended conversion, but it might fail due
563 // to a const violation.
564 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
565 msg = diag::err_bad_cxx_cast_const_away;
566 return TC_Failed;
567 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000568 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000569 return TC_Success;
570 }
571 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000572 else if (CStyle && DestType->isObjCObjectPointerType()) {
573 // allow c-style cast of objective-c pointers as they are pervasive.
574 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
575 return TC_Success;
576 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000577 else if (CStyle && DestType->isBlockPointerType()) {
578 // allow c-style cast of void * to block pointers.
579 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
580 return TC_Success;
581 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000582 }
583 }
584
585 // We tried everything. Everything! Nothing works! :-(
586 return TC_NotApplicable;
587}
588
589/// Tests whether a conversion according to N2844 is valid.
590TryCastResult
591TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000592 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000593 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
594 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000595 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000596 if (!R)
597 return TC_NotApplicable;
598
599 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
600 return TC_NotApplicable;
601
602 // Because we try the reference downcast before this function, from now on
603 // this is the only cast possibility, so we issue an error if we fail now.
604 // FIXME: Should allow casting away constness if CStyle.
605 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000606 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
607 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000608 DerivedToBase) <
609 Sema::Ref_Compatible_With_Added_Qualification) {
610 msg = diag::err_bad_lvalue_to_rvalue_cast;
611 return TC_Failed;
612 }
613
Douglas Gregorf0e0b172010-03-25 00:20:38 +0000614 // FIXME: We should probably have an AST node for lvalue-to-rvalue
615 // conversions.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000616 return TC_Success;
617}
618
619/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
620TryCastResult
621TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
622 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000623 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000624 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
625 // cast to type "reference to cv2 D", where D is a class derived from B,
626 // if a valid standard conversion from "pointer to D" to "pointer to B"
627 // exists, cv2 >= cv1, and B is not a virtual base class of D.
628 // In addition, DR54 clarifies that the base must be accessible in the
629 // current context. Although the wording of DR54 only applies to the pointer
630 // variant of this rule, the intent is clearly for it to apply to the this
631 // conversion as well.
632
Ted Kremenek6217b802009-07-29 21:53:49 +0000633 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000634 if (!DestReference) {
635 return TC_NotApplicable;
636 }
637 bool RValueRef = DestReference->isRValueReferenceType();
638 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
639 // We know the left side is an lvalue reference, so we can suggest a reason.
640 msg = diag::err_bad_cxx_cast_rvalue;
641 return TC_NotApplicable;
642 }
643
644 QualType DestPointee = DestReference->getPointeeType();
645
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000646 return TryStaticDowncast(Self,
647 Self.Context.getCanonicalType(SrcExpr->getType()),
648 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000649 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000650}
651
652/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
653TryCastResult
654TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000655 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000656 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000657 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
658 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
659 // is a class derived from B, if a valid standard conversion from "pointer
660 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
661 // class of D.
662 // In addition, DR54 clarifies that the base must be accessible in the
663 // current context.
664
Ted Kremenek6217b802009-07-29 21:53:49 +0000665 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000666 if (!DestPointer) {
667 return TC_NotApplicable;
668 }
669
Ted Kremenek6217b802009-07-29 21:53:49 +0000670 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000671 if (!SrcPointer) {
672 msg = diag::err_bad_static_cast_pointer_nonpointer;
673 return TC_NotApplicable;
674 }
675
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000676 return TryStaticDowncast(Self,
677 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
678 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
679 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000680}
681
682/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
683/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000684/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000685TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000686TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000687 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000688 QualType OrigDestType, unsigned &msg,
689 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000690 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000691 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
692 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000693 return TC_NotApplicable;
694
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000695 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000696 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000697 return TC_NotApplicable;
698 }
699
Douglas Gregora8f32e02009-10-06 17:59:45 +0000700 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
701 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000702 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
703 return TC_NotApplicable;
704 }
705
706 // Target type does derive from source type. Now we're serious. If an error
707 // appears now, it's not ignored.
708 // This may not be entirely in line with the standard. Take for example:
709 // struct A {};
710 // struct B : virtual A {
711 // B(A&);
712 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000713 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000714 // void f()
715 // {
716 // (void)static_cast<const B&>(*((A*)0));
717 // }
718 // As far as the standard is concerned, p5 does not apply (A is virtual), so
719 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
720 // However, both GCC and Comeau reject this example, and accepting it would
721 // mean more complex code if we're to preserve the nice error message.
722 // FIXME: Being 100% compliant here would be nice to have.
723
724 // Must preserve cv, as always, unless we're in C-style mode.
725 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
726 msg = diag::err_bad_cxx_cast_const_away;
727 return TC_Failed;
728 }
729
730 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
731 // This code is analoguous to that in CheckDerivedToBaseConversion, except
732 // that it builds the paths in reverse order.
733 // To sum up: record all paths to the base and build a nice string from
734 // them. Use it to spice up the error message.
735 if (!Paths.isRecordingPaths()) {
736 Paths.clear();
737 Paths.setRecordingPaths(true);
738 Self.IsDerivedFrom(DestType, SrcType, Paths);
739 }
740 std::string PathDisplayStr;
741 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000742 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000743 PI != PE; ++PI) {
744 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
745 // We haven't displayed a path to this particular base
746 // class subobject yet.
747 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000748 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
749 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000750 EI != EE; ++EI)
751 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000752 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000753 }
754 }
755
756 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000757 << QualType(SrcType).getUnqualifiedType()
758 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000759 << PathDisplayStr << OpRange;
760 msg = 0;
761 return TC_Failed;
762 }
763
764 if (Paths.getDetectedVirtual() != 0) {
765 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
766 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
767 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
768 msg = 0;
769 return TC_Failed;
770 }
771
John McCall6b2accb2010-02-10 09:31:12 +0000772 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000773 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000774 Paths.front(),
775 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000776 msg = 0;
777 return TC_Failed;
778 }
779
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000780 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000781 return TC_Success;
782}
783
784/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
785/// C++ 5.2.9p9 is valid:
786///
787/// An rvalue of type "pointer to member of D of type cv1 T" can be
788/// converted to an rvalue of type "pointer to member of B of type cv2 T",
789/// where B is a base class of D [...].
790///
791TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000792TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
793 QualType DestType, bool CStyle,
794 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000795 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000796 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000797 if (!DestMemPtr)
798 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000799
800 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +0000801 DeclAccessPair FoundOverload;
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000802 if (SrcExpr->getType() == Self.Context.OverloadTy) {
803 if (FunctionDecl *Fn
804 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
805 FoundOverload)) {
806 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
807 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
808 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
809 WasOverloadedFunction = true;
810 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000811 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000812
Ted Kremenek6217b802009-07-29 21:53:49 +0000813 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000814 if (!SrcMemPtr) {
815 msg = diag::err_bad_static_cast_member_pointer_nonmp;
816 return TC_NotApplicable;
817 }
818
819 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000820 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
821 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000822 return TC_NotApplicable;
823
824 // B base of D
825 QualType SrcClass(SrcMemPtr->getClass(), 0);
826 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000828 /*DetectVirtual=*/true);
829 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
830 return TC_NotApplicable;
831 }
832
833 // B is a base of D. But is it an allowed base? If not, it's a hard error.
834 if (Paths.isAmbiguous(DestClass)) {
835 Paths.clear();
836 Paths.setRecordingPaths(true);
837 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
838 assert(StillOkay);
839 StillOkay = StillOkay;
840 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
841 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
842 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
843 msg = 0;
844 return TC_Failed;
845 }
846
847 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
848 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
849 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
850 msg = 0;
851 return TC_Failed;
852 }
853
John McCall6b2accb2010-02-10 09:31:12 +0000854 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000855 DestType, SrcType,
John McCall58e6f342010-03-16 05:22:47 +0000856 Paths.front(),
857 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000858 msg = 0;
859 return TC_Failed;
860 }
861
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000862 if (WasOverloadedFunction) {
863 // Resolve the address of the overloaded function again, this time
864 // allowing complaints if something goes wrong.
865 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
866 DestType,
John McCall6bb80172010-03-30 21:47:33 +0000867 true,
868 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000869 if (!Fn) {
870 msg = 0;
871 return TC_Failed;
872 }
873
John McCall6bb80172010-03-30 21:47:33 +0000874 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000875 if (!SrcExpr) {
876 msg = 0;
877 return TC_Failed;
878 }
879 }
880
Anders Carlsson1a31a182009-10-30 00:46:35 +0000881 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000882 return TC_Success;
883}
884
885/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
886/// is valid:
887///
888/// An expression e can be explicitly converted to a type T using a
889/// @c static_cast if the declaration "T t(e);" is well-formed [...].
890TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000891TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000892 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000893 CastExpr::CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +0000894 if (DestType->isRecordType()) {
895 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
896 diag::err_bad_dynamic_cast_incomplete)) {
897 msg = 0;
898 return TC_Failed;
899 }
900 }
Douglas Gregord6e44a32010-04-16 22:09:46 +0000901
902 // At this point of CheckStaticCast, if the destination is a reference,
903 // this has to work. There is no other way that works.
904 // On the other hand, if we're checking a C-style cast, we've still got
905 // the reinterpret_cast way.
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000906 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
907 InitializationKind InitKind
Douglas Gregord6e44a32010-04-16 22:09:46 +0000908 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
909 CStyle);
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000910 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregord6e44a32010-04-16 22:09:46 +0000911 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
912 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +0000913 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000914
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000915 Sema::OwningExprResult Result
Douglas Gregord6e44a32010-04-16 22:09:46 +0000916 = InitSeq.Perform(Self, Entity, InitKind,
917 Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000918 if (Result.isInvalid()) {
919 msg = 0;
920 return TC_Failed;
921 }
922
Douglas Gregord6e44a32010-04-16 22:09:46 +0000923 if (InitSeq.isConstructorInitialization())
924 Kind = CastExpr::CK_ConstructorConversion;
925 else
926 Kind = CastExpr::CK_NoOp;
927
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000928 SrcExpr = Result.takeAs<Expr>();
929 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000930}
931
932/// TryConstCast - See if a const_cast from source to destination is allowed,
933/// and perform it if it is.
934static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
935 bool CStyle, unsigned &msg) {
936 DestType = Self.Context.getCanonicalType(DestType);
937 QualType SrcType = SrcExpr->getType();
938 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000939 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000940 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
941 // Cannot const_cast non-lvalue to lvalue reference type. But if this
942 // is C-style, static_cast might find a way, so we simply suggest a
943 // message and tell the parent to keep searching.
944 msg = diag::err_bad_cxx_cast_rvalue;
945 return TC_NotApplicable;
946 }
947
948 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
949 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
950 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
951 SrcType = Self.Context.getPointerType(SrcType);
952 }
953
954 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
955 // the rules for const_cast are the same as those used for pointers.
956
957 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
958 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
959 // was a reference type, we converted it to a pointer above.
960 // The status of rvalue references isn't entirely clear, but it looks like
961 // conversion to them is simply invalid.
962 // C++ 5.2.11p3: For two pointer types [...]
963 if (!CStyle)
964 msg = diag::err_bad_const_cast_dest;
965 return TC_NotApplicable;
966 }
967 if (DestType->isFunctionPointerType() ||
968 DestType->isMemberFunctionPointerType()) {
969 // Cannot cast direct function pointers.
970 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
971 // T is the ultimate pointee of source and target type.
972 if (!CStyle)
973 msg = diag::err_bad_const_cast_dest;
974 return TC_NotApplicable;
975 }
976 SrcType = Self.Context.getCanonicalType(SrcType);
977
978 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
979 // completely equal.
980 // FIXME: const_cast should probably not be able to convert between pointers
981 // to different address spaces.
982 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
983 // in multi-level pointers may change, but the level count must be the same,
984 // as must be the final pointee type.
985 while (SrcType != DestType &&
986 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +0000987 Qualifiers Quals;
988 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
989 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000990 }
991
992 // Since we're dealing in canonical types, the remainder must be the same.
993 if (SrcType != DestType)
994 return TC_NotApplicable;
995
996 return TC_Success;
997}
998
999static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1000 QualType DestType, bool CStyle,
1001 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001002 unsigned &msg,
1003 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001004 DestType = Self.Context.getCanonicalType(DestType);
1005 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001006 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001007 bool LValue = DestTypeTmp->isLValueReferenceType();
1008 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1009 // Cannot cast non-lvalue to reference type. See the similar comment in
1010 // const_cast.
1011 msg = diag::err_bad_cxx_cast_rvalue;
1012 return TC_NotApplicable;
1013 }
1014
1015 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1016 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1017 // built-in & and * operators.
1018 // This code does this transformation for the checked types.
1019 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1020 SrcType = Self.Context.getPointerType(SrcType);
1021 }
1022
1023 // Canonicalize source for comparison.
1024 SrcType = Self.Context.getCanonicalType(SrcType);
1025
Ted Kremenek6217b802009-07-29 21:53:49 +00001026 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1027 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001028 if (DestMemPtr && SrcMemPtr) {
1029 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1030 // can be explicitly converted to an rvalue of type "pointer to member
1031 // of Y of type T2" if T1 and T2 are both function types or both object
1032 // types.
1033 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1034 SrcMemPtr->getPointeeType()->isFunctionType())
1035 return TC_NotApplicable;
1036
1037 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1038 // constness.
1039 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1040 // we accept it.
1041 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1042 msg = diag::err_bad_cxx_cast_const_away;
1043 return TC_Failed;
1044 }
1045
1046 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001047 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048 return TC_Success;
1049 }
1050
1051 // See below for the enumeral issue.
1052 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1053 !DestType->isEnumeralType()) {
1054 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1055 // type large enough to hold it. A value of std::nullptr_t can be
1056 // converted to an integral type; the conversion has the same meaning
1057 // and validity as a conversion of (void*)0 to the integral type.
1058 if (Self.Context.getTypeSize(SrcType) >
1059 Self.Context.getTypeSize(DestType)) {
1060 msg = diag::err_bad_reinterpret_cast_small_int;
1061 return TC_Failed;
1062 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001063 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001064 return TC_Success;
1065 }
1066
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001067 bool destIsVector = DestType->isVectorType();
1068 bool srcIsVector = SrcType->isVectorType();
1069 if (srcIsVector || destIsVector) {
1070 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1071 bool destIsScalar =
1072 DestType->isIntegralType() && !DestType->isEnumeralType();
1073
1074 // Check if this is a cast between a vector and something else.
1075 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1076 !(srcIsVector && destIsVector))
1077 return TC_NotApplicable;
1078
1079 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001080 if (Self.Context.getTypeSize(SrcType)
1081 == Self.Context.getTypeSize(DestType)) {
1082 Kind = CastExpr::CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001083 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001084 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001085
1086 if (destIsScalar)
1087 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1088 else if (srcIsScalar)
1089 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1090 else
1091 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1092
1093 return TC_Failed;
1094 }
1095
Fariborz Jahanian72a86592010-02-03 20:32:31 +00001096 bool destIsPtr = DestType->isAnyPointerType();
1097 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001098 if (!destIsPtr && !srcIsPtr) {
1099 // Except for std::nullptr_t->integer and lvalue->reference, which are
1100 // handled above, at least one of the two arguments must be a pointer.
1101 return TC_NotApplicable;
1102 }
1103
1104 if (SrcType == DestType) {
1105 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1106 // restrictions, a cast to the same type is allowed. The intent is not
1107 // entirely clear here, since all other paragraphs explicitly forbid casts
1108 // to the same type. However, the behavior of compilers is pretty consistent
1109 // on this point: allow same-type conversion if the involved types are
1110 // pointers, disallow otherwise.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001111 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001112 return TC_Success;
1113 }
1114
1115 // Note: Clang treats enumeration types as integral types. If this is ever
1116 // changed for C++, the additional check here will be redundant.
1117 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1118 assert(srcIsPtr && "One type must be a pointer");
1119 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1120 // type large enough to hold it.
1121 if (Self.Context.getTypeSize(SrcType) >
1122 Self.Context.getTypeSize(DestType)) {
1123 msg = diag::err_bad_reinterpret_cast_small_int;
1124 return TC_Failed;
1125 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001126 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 return TC_Success;
1128 }
1129
1130 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1131 assert(destIsPtr && "One type must be a pointer");
1132 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1133 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001134 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001135 return TC_Success;
1136 }
1137
1138 if (!destIsPtr || !srcIsPtr) {
1139 // With the valid non-pointer conversions out of the way, we can be even
1140 // more stringent.
1141 return TC_NotApplicable;
1142 }
1143
1144 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1145 // The C-style cast operator can.
1146 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1147 msg = diag::err_bad_cxx_cast_const_away;
1148 return TC_Failed;
1149 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001150 if (CStyle && DestType->isObjCObjectPointerType()) {
1151 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1152 return TC_Success;
1153 }
1154
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001155 // Not casting away constness, so the only remaining check is for compatible
1156 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001157 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001158
1159 if (SrcType->isFunctionPointerType()) {
1160 if (DestType->isFunctionPointerType()) {
1161 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1162 // a pointer to a function of a different type.
1163 return TC_Success;
1164 }
1165
1166 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1167 // an object type or vice versa is conditionally-supported.
1168 // Compilers support it in C++03 too, though, because it's necessary for
1169 // casting the return value of dlsym() and GetProcAddress().
1170 // FIXME: Conditionally-supported behavior should be configurable in the
1171 // TargetInfo or similar.
1172 if (!Self.getLangOptions().CPlusPlus0x)
1173 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1174 return TC_Success;
1175 }
1176
1177 if (DestType->isFunctionPointerType()) {
1178 // See above.
1179 if (!Self.getLangOptions().CPlusPlus0x)
1180 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1181 return TC_Success;
1182 }
1183
1184 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1185 // a pointer to an object of different type.
1186 // Void pointers are not specified, but supported by every compiler out there.
1187 // So we finish by allowing everything that remains - it's got to be two
1188 // object pointers.
1189 return TC_Success;
1190}
1191
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001192bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Douglas Gregord6e44a32010-04-16 22:09:46 +00001193 CastExpr::CastKind &Kind, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001194 // This test is outside everything else because it's the only case where
1195 // a non-lvalue-reference target type does not lead to decay.
1196 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001197 if (CastTy->isVoidType()) {
1198 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001199 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001200 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001201
1202 // If the type is dependent, we won't do any other semantic analysis now.
1203 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1204 return false;
1205
Douglas Gregorb653c522009-11-06 01:14:41 +00001206 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001207 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001208
1209 // C++ [expr.cast]p5: The conversions performed by
1210 // - a const_cast,
1211 // - a static_cast,
1212 // - a static_cast followed by a const_cast,
1213 // - a reinterpret_cast, or
1214 // - a reinterpret_cast followed by a const_cast,
1215 // can be performed using the cast notation of explicit type conversion.
1216 // [...] If a conversion can be interpreted in more than one of the ways
1217 // listed above, the interpretation that appears first in the list is used,
1218 // even if a cast resulting from that interpretation is ill-formed.
1219 // In plain language, this means trying a const_cast ...
1220 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001221 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1222 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001223 if (tcr == TC_Success)
1224 Kind = CastExpr::CK_NoOp;
1225
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001226 if (tcr == TC_NotApplicable) {
1227 // ... or if that is not possible, a static_cast, ignoring const, ...
Douglas Gregord6e44a32010-04-16 22:09:46 +00001228 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001229 if (tcr == TC_NotApplicable) {
1230 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001231 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1232 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001233 }
1234 }
1235
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001236 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001237 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001238 << CastExpr->getType() << CastTy << R;
1239
1240 return tcr != TC_Success;
1241}