blob: a6e5570752bd5290306d6d9884e402454d16f77c [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;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000153 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000154 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000155 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000156 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson714179b2009-08-02 19:07:59 +0000157 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000158 case tok::kw_reinterpret_cast: {
159 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000160 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000161 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000162 return Owned(new (Context) CXXReinterpretCastExpr(
163 DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000164 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000165 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000166 case tok::kw_static_cast: {
167 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000168 if (!TypeDependent)
169 CheckStaticCast(*this, Ex, DestType, OpRange, Kind);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000172 Kind, Ex, DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000173 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000174 }
175
Sebastian Redlf53597f2009-03-15 17:47:39 +0000176 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000177}
178
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000179/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
180/// this removes one level of indirection from both types, provided that they're
181/// the same kind of pointer (plain or to-member). Unlike the Sema function,
182/// this one doesn't care if the two pointers-to-member don't point into the
183/// same class. This is because CastsAwayConstness doesn't care.
184bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
185 const PointerType *T1PtrType = T1->getAs<PointerType>(),
186 *T2PtrType = T2->getAs<PointerType>();
187 if (T1PtrType && T2PtrType) {
188 T1 = T1PtrType->getPointeeType();
189 T2 = T2PtrType->getPointeeType();
190 return true;
191 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000192 const ObjCObjectPointerType *T1ObjCPtrType =
193 T1->getAs<ObjCObjectPointerType>(),
194 *T2ObjCPtrType =
195 T2->getAs<ObjCObjectPointerType>();
196 if (T1ObjCPtrType) {
197 if (T2ObjCPtrType) {
198 T1 = T1ObjCPtrType->getPointeeType();
199 T2 = T2ObjCPtrType->getPointeeType();
200 return true;
201 }
202 else if (T2PtrType) {
203 T1 = T1ObjCPtrType->getPointeeType();
204 T2 = T2PtrType->getPointeeType();
205 return true;
206 }
207 }
208 else if (T2ObjCPtrType) {
209 if (T1PtrType) {
210 T2 = T2ObjCPtrType->getPointeeType();
211 T1 = T1PtrType->getPointeeType();
212 return true;
213 }
214 }
215
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000216 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
217 *T2MPType = T2->getAs<MemberPointerType>();
218 if (T1MPType && T2MPType) {
219 T1 = T1MPType->getPointeeType();
220 T2 = T2MPType->getPointeeType();
221 return true;
222 }
223 return false;
224}
225
Sebastian Redldb647282009-01-27 23:18:31 +0000226/// CastsAwayConstness - Check if the pointer conversion from SrcType to
227/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
228/// the cast checkers. Both arguments must denote pointer (possibly to member)
229/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000230static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000231CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000232 // Casting away constness is defined in C++ 5.2.11p8 with reference to
233 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
234 // the rules are non-trivial. So first we construct Tcv *...cv* as described
235 // in C++ 5.2.11p8.
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000236 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000237 "Source type is not pointer or pointer to member.");
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000238 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000239 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000240
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000241 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
242 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000243 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000244
245 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000246 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000247 cv1.push_back(UnwrappedSrcType.getQualifiers());
248 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000249 }
250 assert(cv1.size() > 0 && "Must have at least one pointer level.");
251
252 // Construct void pointers with those qualifiers (in reverse order of
253 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000254 QualType SrcConstruct = Self.Context.VoidTy;
255 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000256 ASTContext &Context = Self.Context;
257 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
258 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000259 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000260 SrcConstruct
261 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
262 DestConstruct
263 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000264 }
265
266 // Test if they're compatible.
267 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000268 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000269}
270
Sebastian Redl26d85b12008-11-05 21:50:06 +0000271/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
272/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
273/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000274static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000275CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
276 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000277 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000278 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000279 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280
281 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
282 // or "pointer to cv void".
283
284 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000285 const PointerType *DestPointer = DestType->getAs<PointerType>();
286 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000287 if (DestPointer) {
288 DestPointee = DestPointer->getPointeeType();
289 } else if (DestReference) {
290 DestPointee = DestReference->getPointeeType();
291 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000292 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000293 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000294 return;
295 }
296
Ted Kremenek6217b802009-07-29 21:53:49 +0000297 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000298 if (DestPointee->isVoidType()) {
299 assert(DestPointer && "Reference to void is not possible");
300 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000301 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000302 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000303 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000304 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000305 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000306 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000307 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000308 return;
309 }
310
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000311 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
312 // complete class type, [...]. If T is an lvalue reference type, v shall be
313 // an lvalue of a complete class type, [...]. If T is an rvalue reference
314 // type, v shall be an expression having a complete effective class type,
315 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000316
Sebastian Redl37d6de32008-11-08 13:00:26 +0000317 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000318 QualType SrcPointee;
319 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000320 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 SrcPointee = SrcPointer->getPointeeType();
322 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000323 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000324 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000325 return;
326 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000327 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000328 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000329 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000330 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000331 }
332 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000333 } else {
334 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000335 }
336
Ted Kremenek6217b802009-07-29 21:53:49 +0000337 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000338 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000339 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000340 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000341 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000342 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000343 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000344 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000345 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000346 return;
347 }
348
349 assert((DestPointer || DestReference) &&
350 "Bad destination non-ptr/ref slipped through.");
351 assert((DestRecord || DestPointee->isVoidType()) &&
352 "Bad destination pointee slipped through.");
353 assert(SrcRecord && "Bad source pointee slipped through.");
354
355 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
356 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000357 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000358 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000359 return;
360 }
361
362 // C++ 5.2.7p3: If the type of v is the same as the required result type,
363 // [except for cv].
364 if (DestRecord == SrcRecord) {
365 return;
366 }
367
368 // C++ 5.2.7p5
369 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000370 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
371 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000372 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000373 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000374 // Diagnostic already emitted on error.
375 return;
376 }
377
378 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000379 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000380 assert(SrcDecl && "Definition missing");
381 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000382 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000383 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000384 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000385
386 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000387 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000388}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000389
390/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
391/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
392/// like this:
393/// const char *str = "literal";
394/// legacy_function(const_cast\<char*\>(str));
395void
396CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000397 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000398 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000399 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000400
401 unsigned msg = diag::err_bad_cxx_cast_generic;
402 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
403 && msg != 0)
404 Self.Diag(OpRange.getBegin(), msg) << CT_Const
405 << SrcExpr->getType() << DestType << OpRange;
406}
407
408/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
409/// valid.
410/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
411/// like this:
412/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
413void
414CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000415 const SourceRange &OpRange, const SourceRange &DestRange,
416 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000417 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000418 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000419
420 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000421 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
422 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000423 != TC_Success && msg != 0)
424 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
425 << SrcExpr->getType() << DestType << OpRange;
426}
427
428
429/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
430/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
431/// implicit conversions explicit and getting rid of data loss warnings.
432void
433CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000434 const SourceRange &OpRange, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000435 // This test is outside everything else because it's the only case where
436 // a non-lvalue-reference target type does not lead to decay.
437 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000438 if (DestType->isVoidType()) {
439 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000440 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000441 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000442
Douglas Gregorb653c522009-11-06 01:14:41 +0000443 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000444 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000445
446 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000447 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000448 Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000449 != TC_Success && msg != 0)
450 Self.Diag(OpRange.getBegin(), msg) << CT_Static
451 << SrcExpr->getType() << DestType << OpRange;
452}
453
454/// TryStaticCast - Check if a static cast can be performed, and do so if
455/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
456/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000457static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000458 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000459 const SourceRange &OpRange, unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000460 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000461 // The order the tests is not entirely arbitrary. There is one conversion
462 // that can be handled in two different ways. Given:
463 // struct A {};
464 // struct B : public A {
465 // B(); B(const A&);
466 // };
467 // const A &a = B();
468 // the cast static_cast<const B&>(a) could be seen as either a static
469 // reference downcast, or an explicit invocation of the user-defined
470 // conversion using B's conversion constructor.
471 // DR 427 specifies that the downcast is to be applied here.
472
473 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
474 // Done outside this function.
475
476 TryCastResult tcr;
477
478 // C++ 5.2.9p5, reference downcast.
479 // See the function for details.
480 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000481 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000482 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000483 if (tcr != TC_NotApplicable)
484 return tcr;
485
486 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
487 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
488 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000489 if (tcr != TC_NotApplicable) {
490 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000491 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000492 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000493
494 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
495 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000496 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000497 Kind);
Anders Carlsson3c31a392009-09-26 00:12:34 +0000498 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000499 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000500
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000501 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
502 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
503 // conversions, subject to further restrictions.
504 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
505 // of qualification conversions impossible.
506 // In the CStyle case, the earlier attempt to const_cast should have taken
507 // care of reverse qualification conversions.
508
509 QualType OrigSrcType = SrcExpr->getType();
510
511 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
512
513 // Reverse integral promotion/conversion. All such conversions are themselves
514 // again integral promotions or conversions and are thus already handled by
515 // p2 (TryDirectInitialization above).
516 // (Note: any data loss warnings should be suppressed.)
517 // The exception is the reverse of enum->integer, i.e. integer->enum (and
518 // enum->enum). See also C++ 5.2.9p7.
519 // The same goes for reverse floating point promotion/conversion and
520 // floating-integral conversions. Again, only floating->enum is relevant.
521 if (DestType->isEnumeralType()) {
522 if (SrcType->isComplexType() || SrcType->isVectorType()) {
523 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000524 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
525 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000526 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000527 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000528 }
529
530 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
531 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000532 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
533 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000534 if (tcr != TC_NotApplicable)
535 return tcr;
536
537 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
538 // conversion. C++ 5.2.9p9 has additional information.
539 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000540 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000541 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000542 if (tcr != TC_NotApplicable)
543 return tcr;
544
545 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
546 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
547 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000548 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000549 QualType SrcPointee = SrcPointer->getPointeeType();
550 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000551 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000552 QualType DestPointee = DestPointer->getPointeeType();
553 if (DestPointee->isIncompleteOrObjectType()) {
554 // This is definitely the intended conversion, but it might fail due
555 // to a const violation.
556 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
557 msg = diag::err_bad_cxx_cast_const_away;
558 return TC_Failed;
559 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000560 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000561 return TC_Success;
562 }
563 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000564 else if (CStyle && DestType->isObjCObjectPointerType()) {
565 // allow c-style cast of objective-c pointers as they are pervasive.
566 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
567 return TC_Success;
568 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000569 else if (CStyle && DestType->isBlockPointerType()) {
570 // allow c-style cast of void * to block pointers.
571 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
572 return TC_Success;
573 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000574 }
575 }
576
577 // We tried everything. Everything! Nothing works! :-(
578 return TC_NotApplicable;
579}
580
581/// Tests whether a conversion according to N2844 is valid.
582TryCastResult
583TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000584 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000585 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
586 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000587 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000588 if (!R)
589 return TC_NotApplicable;
590
591 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
592 return TC_NotApplicable;
593
594 // Because we try the reference downcast before this function, from now on
595 // this is the only cast possibility, so we issue an error if we fail now.
596 // FIXME: Should allow casting away constness if CStyle.
597 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000598 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
599 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000600 DerivedToBase) <
601 Sema::Ref_Compatible_With_Added_Qualification) {
602 msg = diag::err_bad_lvalue_to_rvalue_cast;
603 return TC_Failed;
604 }
605
Douglas Gregorf0e0b172010-03-25 00:20:38 +0000606 // FIXME: We should probably have an AST node for lvalue-to-rvalue
607 // conversions.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000608 return TC_Success;
609}
610
611/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
612TryCastResult
613TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
614 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000615 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000616 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
617 // cast to type "reference to cv2 D", where D is a class derived from B,
618 // if a valid standard conversion from "pointer to D" to "pointer to B"
619 // exists, cv2 >= cv1, and B is not a virtual base class of D.
620 // In addition, DR54 clarifies that the base must be accessible in the
621 // current context. Although the wording of DR54 only applies to the pointer
622 // variant of this rule, the intent is clearly for it to apply to the this
623 // conversion as well.
624
Ted Kremenek6217b802009-07-29 21:53:49 +0000625 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000626 if (!DestReference) {
627 return TC_NotApplicable;
628 }
629 bool RValueRef = DestReference->isRValueReferenceType();
630 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
631 // We know the left side is an lvalue reference, so we can suggest a reason.
632 msg = diag::err_bad_cxx_cast_rvalue;
633 return TC_NotApplicable;
634 }
635
636 QualType DestPointee = DestReference->getPointeeType();
637
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000638 return TryStaticDowncast(Self,
639 Self.Context.getCanonicalType(SrcExpr->getType()),
640 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000641 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000642}
643
644/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
645TryCastResult
646TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000647 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000648 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000649 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
650 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
651 // is a class derived from B, if a valid standard conversion from "pointer
652 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
653 // class of D.
654 // In addition, DR54 clarifies that the base must be accessible in the
655 // current context.
656
Ted Kremenek6217b802009-07-29 21:53:49 +0000657 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000658 if (!DestPointer) {
659 return TC_NotApplicable;
660 }
661
Ted Kremenek6217b802009-07-29 21:53:49 +0000662 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000663 if (!SrcPointer) {
664 msg = diag::err_bad_static_cast_pointer_nonpointer;
665 return TC_NotApplicable;
666 }
667
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000668 return TryStaticDowncast(Self,
669 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
670 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
671 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000672}
673
674/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
675/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000676/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000677TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000678TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000680 QualType OrigDestType, unsigned &msg,
681 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000682 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000683 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
684 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000685 return TC_NotApplicable;
686
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000687 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000688 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000689 return TC_NotApplicable;
690 }
691
Douglas Gregora8f32e02009-10-06 17:59:45 +0000692 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
693 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000694 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
695 return TC_NotApplicable;
696 }
697
698 // Target type does derive from source type. Now we're serious. If an error
699 // appears now, it's not ignored.
700 // This may not be entirely in line with the standard. Take for example:
701 // struct A {};
702 // struct B : virtual A {
703 // B(A&);
704 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000705 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000706 // void f()
707 // {
708 // (void)static_cast<const B&>(*((A*)0));
709 // }
710 // As far as the standard is concerned, p5 does not apply (A is virtual), so
711 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
712 // However, both GCC and Comeau reject this example, and accepting it would
713 // mean more complex code if we're to preserve the nice error message.
714 // FIXME: Being 100% compliant here would be nice to have.
715
716 // Must preserve cv, as always, unless we're in C-style mode.
717 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
718 msg = diag::err_bad_cxx_cast_const_away;
719 return TC_Failed;
720 }
721
722 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
723 // This code is analoguous to that in CheckDerivedToBaseConversion, except
724 // that it builds the paths in reverse order.
725 // To sum up: record all paths to the base and build a nice string from
726 // them. Use it to spice up the error message.
727 if (!Paths.isRecordingPaths()) {
728 Paths.clear();
729 Paths.setRecordingPaths(true);
730 Self.IsDerivedFrom(DestType, SrcType, Paths);
731 }
732 std::string PathDisplayStr;
733 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000734 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000735 PI != PE; ++PI) {
736 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
737 // We haven't displayed a path to this particular base
738 // class subobject yet.
739 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000740 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
741 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000742 EI != EE; ++EI)
743 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000744 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000745 }
746 }
747
748 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000749 << QualType(SrcType).getUnqualifiedType()
750 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000751 << PathDisplayStr << OpRange;
752 msg = 0;
753 return TC_Failed;
754 }
755
756 if (Paths.getDetectedVirtual() != 0) {
757 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
758 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
759 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
760 msg = 0;
761 return TC_Failed;
762 }
763
John McCall6b2accb2010-02-10 09:31:12 +0000764 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000765 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000766 Paths.front(),
767 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000768 msg = 0;
769 return TC_Failed;
770 }
771
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000772 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000773 return TC_Success;
774}
775
776/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
777/// C++ 5.2.9p9 is valid:
778///
779/// An rvalue of type "pointer to member of D of type cv1 T" can be
780/// converted to an rvalue of type "pointer to member of B of type cv2 T",
781/// where B is a base class of D [...].
782///
783TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000784TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
785 QualType DestType, bool CStyle,
786 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000787 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000788 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000789 if (!DestMemPtr)
790 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000791
792 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +0000793 DeclAccessPair FoundOverload;
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000794 if (SrcExpr->getType() == Self.Context.OverloadTy) {
795 if (FunctionDecl *Fn
796 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
797 FoundOverload)) {
798 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
799 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
800 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
801 WasOverloadedFunction = true;
802 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000803 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000804
Ted Kremenek6217b802009-07-29 21:53:49 +0000805 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000806 if (!SrcMemPtr) {
807 msg = diag::err_bad_static_cast_member_pointer_nonmp;
808 return TC_NotApplicable;
809 }
810
811 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000812 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
813 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000814 return TC_NotApplicable;
815
816 // B base of D
817 QualType SrcClass(SrcMemPtr->getClass(), 0);
818 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000820 /*DetectVirtual=*/true);
821 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
822 return TC_NotApplicable;
823 }
824
825 // B is a base of D. But is it an allowed base? If not, it's a hard error.
826 if (Paths.isAmbiguous(DestClass)) {
827 Paths.clear();
828 Paths.setRecordingPaths(true);
829 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
830 assert(StillOkay);
831 StillOkay = StillOkay;
832 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
833 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
834 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
835 msg = 0;
836 return TC_Failed;
837 }
838
839 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
840 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
841 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
842 msg = 0;
843 return TC_Failed;
844 }
845
John McCall6b2accb2010-02-10 09:31:12 +0000846 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000847 DestType, SrcType,
John McCall58e6f342010-03-16 05:22:47 +0000848 Paths.front(),
849 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000850 msg = 0;
851 return TC_Failed;
852 }
853
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000854 if (WasOverloadedFunction) {
855 // Resolve the address of the overloaded function again, this time
856 // allowing complaints if something goes wrong.
857 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
858 DestType,
John McCall6bb80172010-03-30 21:47:33 +0000859 true,
860 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000861 if (!Fn) {
862 msg = 0;
863 return TC_Failed;
864 }
865
John McCall6bb80172010-03-30 21:47:33 +0000866 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000867 if (!SrcExpr) {
868 msg = 0;
869 return TC_Failed;
870 }
871 }
872
Anders Carlsson1a31a182009-10-30 00:46:35 +0000873 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000874 return TC_Success;
875}
876
877/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
878/// is valid:
879///
880/// An expression e can be explicitly converted to a type T using a
881/// @c static_cast if the declaration "T t(e);" is well-formed [...].
882TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000883TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000884 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000885 CastExpr::CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +0000886 if (DestType->isRecordType()) {
887 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
888 diag::err_bad_dynamic_cast_incomplete)) {
889 msg = 0;
890 return TC_Failed;
891 }
892 }
Douglas Gregord6e44a32010-04-16 22:09:46 +0000893
894 // At this point of CheckStaticCast, if the destination is a reference,
895 // this has to work. There is no other way that works.
896 // On the other hand, if we're checking a C-style cast, we've still got
897 // the reinterpret_cast way.
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000898 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
899 InitializationKind InitKind
Douglas Gregord6e44a32010-04-16 22:09:46 +0000900 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
901 CStyle);
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000902 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregord6e44a32010-04-16 22:09:46 +0000903 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
904 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +0000905 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000906
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000907 Sema::OwningExprResult Result
Douglas Gregord6e44a32010-04-16 22:09:46 +0000908 = InitSeq.Perform(Self, Entity, InitKind,
909 Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000910 if (Result.isInvalid()) {
911 msg = 0;
912 return TC_Failed;
913 }
914
Douglas Gregord6e44a32010-04-16 22:09:46 +0000915 if (InitSeq.isConstructorInitialization())
916 Kind = CastExpr::CK_ConstructorConversion;
917 else
918 Kind = CastExpr::CK_NoOp;
919
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000920 SrcExpr = Result.takeAs<Expr>();
921 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000922}
923
924/// TryConstCast - See if a const_cast from source to destination is allowed,
925/// and perform it if it is.
926static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
927 bool CStyle, unsigned &msg) {
928 DestType = Self.Context.getCanonicalType(DestType);
929 QualType SrcType = SrcExpr->getType();
930 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000931 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000932 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
933 // Cannot const_cast non-lvalue to lvalue reference type. But if this
934 // is C-style, static_cast might find a way, so we simply suggest a
935 // message and tell the parent to keep searching.
936 msg = diag::err_bad_cxx_cast_rvalue;
937 return TC_NotApplicable;
938 }
939
940 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
941 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
942 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
943 SrcType = Self.Context.getPointerType(SrcType);
944 }
945
946 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
947 // the rules for const_cast are the same as those used for pointers.
948
949 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
950 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
951 // was a reference type, we converted it to a pointer above.
952 // The status of rvalue references isn't entirely clear, but it looks like
953 // conversion to them is simply invalid.
954 // C++ 5.2.11p3: For two pointer types [...]
955 if (!CStyle)
956 msg = diag::err_bad_const_cast_dest;
957 return TC_NotApplicable;
958 }
959 if (DestType->isFunctionPointerType() ||
960 DestType->isMemberFunctionPointerType()) {
961 // Cannot cast direct function pointers.
962 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
963 // T is the ultimate pointee of source and target type.
964 if (!CStyle)
965 msg = diag::err_bad_const_cast_dest;
966 return TC_NotApplicable;
967 }
968 SrcType = Self.Context.getCanonicalType(SrcType);
969
970 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
971 // completely equal.
972 // FIXME: const_cast should probably not be able to convert between pointers
973 // to different address spaces.
974 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
975 // in multi-level pointers may change, but the level count must be the same,
976 // as must be the final pointee type.
977 while (SrcType != DestType &&
978 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +0000979 Qualifiers Quals;
980 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
981 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000982 }
983
984 // Since we're dealing in canonical types, the remainder must be the same.
985 if (SrcType != DestType)
986 return TC_NotApplicable;
987
988 return TC_Success;
989}
990
991static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
992 QualType DestType, bool CStyle,
993 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000994 unsigned &msg,
995 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000996 DestType = Self.Context.getCanonicalType(DestType);
997 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000998 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000999 bool LValue = DestTypeTmp->isLValueReferenceType();
1000 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1001 // Cannot cast non-lvalue to reference type. See the similar comment in
1002 // const_cast.
1003 msg = diag::err_bad_cxx_cast_rvalue;
1004 return TC_NotApplicable;
1005 }
1006
1007 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1008 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1009 // built-in & and * operators.
1010 // This code does this transformation for the checked types.
1011 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1012 SrcType = Self.Context.getPointerType(SrcType);
1013 }
1014
1015 // Canonicalize source for comparison.
1016 SrcType = Self.Context.getCanonicalType(SrcType);
1017
Ted Kremenek6217b802009-07-29 21:53:49 +00001018 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1019 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001020 if (DestMemPtr && SrcMemPtr) {
1021 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1022 // can be explicitly converted to an rvalue of type "pointer to member
1023 // of Y of type T2" if T1 and T2 are both function types or both object
1024 // types.
1025 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1026 SrcMemPtr->getPointeeType()->isFunctionType())
1027 return TC_NotApplicable;
1028
1029 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1030 // constness.
1031 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1032 // we accept it.
1033 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1034 msg = diag::err_bad_cxx_cast_const_away;
1035 return TC_Failed;
1036 }
1037
1038 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001039 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001040 return TC_Success;
1041 }
1042
1043 // See below for the enumeral issue.
1044 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1045 !DestType->isEnumeralType()) {
1046 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1047 // type large enough to hold it. A value of std::nullptr_t can be
1048 // converted to an integral type; the conversion has the same meaning
1049 // and validity as a conversion of (void*)0 to the integral type.
1050 if (Self.Context.getTypeSize(SrcType) >
1051 Self.Context.getTypeSize(DestType)) {
1052 msg = diag::err_bad_reinterpret_cast_small_int;
1053 return TC_Failed;
1054 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001055 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001056 return TC_Success;
1057 }
1058
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001059 bool destIsVector = DestType->isVectorType();
1060 bool srcIsVector = SrcType->isVectorType();
1061 if (srcIsVector || destIsVector) {
1062 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1063 bool destIsScalar =
1064 DestType->isIntegralType() && !DestType->isEnumeralType();
1065
1066 // Check if this is a cast between a vector and something else.
1067 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1068 !(srcIsVector && destIsVector))
1069 return TC_NotApplicable;
1070
1071 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001072 if (Self.Context.getTypeSize(SrcType)
1073 == Self.Context.getTypeSize(DestType)) {
1074 Kind = CastExpr::CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001075 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001076 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001077
1078 if (destIsScalar)
1079 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1080 else if (srcIsScalar)
1081 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1082 else
1083 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1084
1085 return TC_Failed;
1086 }
1087
Fariborz Jahanian72a86592010-02-03 20:32:31 +00001088 bool destIsPtr = DestType->isAnyPointerType();
1089 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001090 if (!destIsPtr && !srcIsPtr) {
1091 // Except for std::nullptr_t->integer and lvalue->reference, which are
1092 // handled above, at least one of the two arguments must be a pointer.
1093 return TC_NotApplicable;
1094 }
1095
1096 if (SrcType == DestType) {
1097 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1098 // restrictions, a cast to the same type is allowed. The intent is not
1099 // entirely clear here, since all other paragraphs explicitly forbid casts
1100 // to the same type. However, the behavior of compilers is pretty consistent
1101 // on this point: allow same-type conversion if the involved types are
1102 // pointers, disallow otherwise.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001103 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001104 return TC_Success;
1105 }
1106
1107 // Note: Clang treats enumeration types as integral types. If this is ever
1108 // changed for C++, the additional check here will be redundant.
1109 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1110 assert(srcIsPtr && "One type must be a pointer");
1111 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1112 // type large enough to hold it.
1113 if (Self.Context.getTypeSize(SrcType) >
1114 Self.Context.getTypeSize(DestType)) {
1115 msg = diag::err_bad_reinterpret_cast_small_int;
1116 return TC_Failed;
1117 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001118 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001119 return TC_Success;
1120 }
1121
1122 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1123 assert(destIsPtr && "One type must be a pointer");
1124 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1125 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001126 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 return TC_Success;
1128 }
1129
1130 if (!destIsPtr || !srcIsPtr) {
1131 // With the valid non-pointer conversions out of the way, we can be even
1132 // more stringent.
1133 return TC_NotApplicable;
1134 }
1135
1136 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1137 // The C-style cast operator can.
1138 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1139 msg = diag::err_bad_cxx_cast_const_away;
1140 return TC_Failed;
1141 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001142 if (CStyle && DestType->isObjCObjectPointerType()) {
1143 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1144 return TC_Success;
1145 }
1146
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001147 // Not casting away constness, so the only remaining check is for compatible
1148 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001149 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001150
1151 if (SrcType->isFunctionPointerType()) {
1152 if (DestType->isFunctionPointerType()) {
1153 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1154 // a pointer to a function of a different type.
1155 return TC_Success;
1156 }
1157
1158 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1159 // an object type or vice versa is conditionally-supported.
1160 // Compilers support it in C++03 too, though, because it's necessary for
1161 // casting the return value of dlsym() and GetProcAddress().
1162 // FIXME: Conditionally-supported behavior should be configurable in the
1163 // TargetInfo or similar.
1164 if (!Self.getLangOptions().CPlusPlus0x)
1165 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1166 return TC_Success;
1167 }
1168
1169 if (DestType->isFunctionPointerType()) {
1170 // See above.
1171 if (!Self.getLangOptions().CPlusPlus0x)
1172 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1173 return TC_Success;
1174 }
1175
1176 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1177 // a pointer to an object of different type.
1178 // Void pointers are not specified, but supported by every compiler out there.
1179 // So we finish by allowing everything that remains - it's got to be two
1180 // object pointers.
1181 return TC_Success;
1182}
1183
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001184bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Douglas Gregord6e44a32010-04-16 22:09:46 +00001185 CastExpr::CastKind &Kind, bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001186 // This test is outside everything else because it's the only case where
1187 // a non-lvalue-reference target type does not lead to decay.
1188 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001189 if (CastTy->isVoidType()) {
1190 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001191 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001192 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001193
1194 // If the type is dependent, we won't do any other semantic analysis now.
1195 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1196 return false;
1197
Douglas Gregorb653c522009-11-06 01:14:41 +00001198 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001199 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001200
1201 // C++ [expr.cast]p5: The conversions performed by
1202 // - a const_cast,
1203 // - a static_cast,
1204 // - a static_cast followed by a const_cast,
1205 // - a reinterpret_cast, or
1206 // - a reinterpret_cast followed by a const_cast,
1207 // can be performed using the cast notation of explicit type conversion.
1208 // [...] If a conversion can be interpreted in more than one of the ways
1209 // listed above, the interpretation that appears first in the list is used,
1210 // even if a cast resulting from that interpretation is ill-formed.
1211 // In plain language, this means trying a const_cast ...
1212 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001213 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1214 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001215 if (tcr == TC_Success)
1216 Kind = CastExpr::CK_NoOp;
1217
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001218 if (tcr == TC_NotApplicable) {
1219 // ... or if that is not possible, a static_cast, ignoring const, ...
Douglas Gregord6e44a32010-04-16 22:09:46 +00001220 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001221 if (tcr == TC_NotApplicable) {
1222 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001223 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1224 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001225 }
1226 }
1227
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001228 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001229 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001230 << CastExpr->getType() << CastTy << R;
1231
1232 return tcr != TC_Success;
1233}