blob: 10da0945f433d3cd258e21c7f7e96b26e1539e6e [file] [log] [blame]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000018#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000019#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000020using namespace clang;
21
Sebastian Redl0e35d042009-07-25 15:41:38 +000022enum TryCastResult {
23 TC_NotApplicable, ///< The cast method is not applicable.
24 TC_Success, ///< The cast method is appropriate and successful.
25 TC_Failed ///< The cast method is appropriate, but failed. A
26 ///< diagnostic has been emitted.
27};
28
29enum CastType {
30 CT_Const, ///< const_cast
31 CT_Static, ///< static_cast
32 CT_Reinterpret, ///< reinterpret_cast
33 CT_Dynamic, ///< dynamic_cast
34 CT_CStyle, ///< (Type)expr
35 CT_Functional ///< Type(expr)
Sebastian Redlf831eeb2008-11-08 13:00:26 +000036};
37
38static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
39 const SourceRange &OpRange,
40 const SourceRange &DestRange);
41static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
42 const SourceRange &OpRange,
43 const SourceRange &DestRange);
44static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson9583fa72009-08-07 22:21:05 +000045 const SourceRange &OpRange,
46 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000047static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
48 const SourceRange &OpRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +000049 const SourceRange &DestRange,
50 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000051
52static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl0e35d042009-07-25 15:41:38 +000053
54// The Try functions attempt a specific way of casting. If they succeed, they
55// return TC_Success. If their way of casting is not appropriate for the given
56// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
57// to emit if no other way succeeds. If their way of casting is appropriate but
58// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
59// they emit a specialized diagnostic.
60// All diagnostics returned by these functions must expect the same three
61// arguments:
62// %0: Cast Type (a value from the CastType enumeration)
63// %1: Source Type
64// %2: Destination Type
65static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
66 QualType DestType, unsigned &msg);
67static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
68 QualType DestType, bool CStyle,
69 const SourceRange &OpRange,
70 unsigned &msg);
71static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
72 QualType DestType, bool CStyle,
73 const SourceRange &OpRange,
74 unsigned &msg);
75static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
76 QualType DestType, bool CStyle,
77 const SourceRange &OpRange,
78 QualType OrigSrcType,
79 QualType OrigDestType, unsigned &msg);
80static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
81 QualType DestType,bool CStyle,
82 const SourceRange &OpRange,
83 unsigned &msg);
84static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
85 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
87 unsigned &msg);
88static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
89 QualType DestType, bool CStyle,
90 const SourceRange &OpRange,
Anders Carlsson9583fa72009-08-07 22:21:05 +000091 CastExpr::CastKind &Kind, unsigned &msg);
Sebastian Redl0e35d042009-07-25 15:41:38 +000092static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
93 bool CStyle, unsigned &msg);
94static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
95 QualType DestType, bool CStyle,
96 const SourceRange &OpRange,
97 unsigned &msg);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000098
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000099/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000100Action::OwningExprResult
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000101Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
102 SourceLocation LAngleBracketLoc, TypeTy *Ty,
103 SourceLocation RAngleBracketLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000104 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000105 SourceLocation RParenLoc) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000106 Expr *Ex = E.takeAs<Expr>();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000107 // FIXME: Preserve type source info.
108 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000109 SourceRange OpRange(OpLoc, RParenLoc);
110 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
111
Douglas Gregore6be68a2008-12-17 22:52:20 +0000112 // If the type is dependent, we won't do the semantic analysis now.
113 // FIXME: should we check this in a more fine-grained manner?
114 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
115
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000116 switch (Kind) {
117 default: assert(0 && "Unknown C++ cast!");
118
119 case tok::kw_const_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000120 if (!TypeDependent)
121 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000122 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
123 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000124
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000125 case tok::kw_dynamic_cast: {
126 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000127 if (!TypeDependent)
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000128 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000129 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000130 Kind, Ex, DestType, OpLoc));
131 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000132 case tok::kw_reinterpret_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000133 if (!TypeDependent)
134 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000135 return Owned(new (Context) CXXReinterpretCastExpr(
136 DestType.getNonReferenceType(),
137 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000138
Anders Carlsson9583fa72009-08-07 22:21:05 +0000139 case tok::kw_static_cast: {
140 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000141 if (!TypeDependent)
Anders Carlsson9583fa72009-08-07 22:21:05 +0000142 CheckStaticCast(*this, Ex, DestType, OpRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000143 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +0000144 Kind, Ex, DestType, OpLoc));
145 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000146 }
147
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000148 return ExprError();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000149}
150
Sebastian Redl04b3f352009-01-27 23:18:31 +0000151/// CastsAwayConstness - Check if the pointer conversion from SrcType to
152/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
153/// the cast checkers. Both arguments must denote pointer (possibly to member)
154/// types.
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000155bool
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000156CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000157{
Sebastian Redl04b3f352009-01-27 23:18:31 +0000158 // Casting away constness is defined in C++ 5.2.11p8 with reference to
159 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
160 // the rules are non-trivial. So first we construct Tcv *...cv* as described
161 // in C++ 5.2.11p8.
162 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
163 "Source type is not pointer or pointer to member.");
164 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
165 "Destination type is not pointer or pointer to member.");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000166
167 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
168 llvm::SmallVector<unsigned, 8> cv1, cv2;
169
170 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000171 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000172 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
173 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
174 }
175 assert(cv1.size() > 0 && "Must have at least one pointer level.");
176
177 // Construct void pointers with those qualifiers (in reverse order of
178 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000179 QualType SrcConstruct = Self.Context.VoidTy;
180 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000181 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
182 i2 = cv2.rbegin();
183 i1 != cv1.rend(); ++i1, ++i2)
184 {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000185 SrcConstruct = Self.Context.getPointerType(
186 SrcConstruct.getQualifiedType(*i1));
187 DestConstruct = Self.Context.getPointerType(
188 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000189 }
190
191 // Test if they're compatible.
192 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000193 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000194}
195
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000196/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
197/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
198/// checked downcasts in class hierarchies.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000199static void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000200CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
201 const SourceRange &OpRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000202 const SourceRange &DestRange, CastExpr::CastKind &Kind)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000203{
204 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000205 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000206
207 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
208 // or "pointer to cv void".
209
210 QualType DestPointee;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000211 const PointerType *DestPointer = DestType->getAs<PointerType>();
212 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000213 if (DestPointer) {
214 DestPointee = DestPointer->getPointeeType();
215 } else if (DestReference) {
216 DestPointee = DestReference->getPointeeType();
217 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000218 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000219 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000220 return;
221 }
222
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000223 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000224 if (DestPointee->isVoidType()) {
225 assert(DestPointer && "Reference to void is not possible");
226 } else if (DestRecord) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000227 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000228 diag::err_bad_dynamic_cast_incomplete,
229 DestRange))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000230 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000231 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000232 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000233 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000234 return;
235 }
236
Sebastian Redlce6fff02009-03-16 23:22:08 +0000237 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
238 // complete class type, [...]. If T is an lvalue reference type, v shall be
239 // an lvalue of a complete class type, [...]. If T is an rvalue reference
240 // type, v shall be an expression having a complete effective class type,
241 // [...]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000242
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000243 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000244 QualType SrcPointee;
245 if (DestPointer) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000246 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000247 SrcPointee = SrcPointer->getPointeeType();
248 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000249 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000250 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000251 return;
252 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000253 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000254 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000255 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000256 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000257 }
258 SrcPointee = SrcType;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000259 } else {
260 SrcPointee = SrcType;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000261 }
262
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000263 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000264 if (SrcRecord) {
Douglas Gregorc84d8932009-03-09 16:13:40 +0000265 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000266 diag::err_bad_dynamic_cast_incomplete,
267 SrcExpr->getSourceRange()))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000268 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000269 } else {
Chris Lattner77d52da2008-11-20 06:06:08 +0000270 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000271 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000272 return;
273 }
274
275 assert((DestPointer || DestReference) &&
276 "Bad destination non-ptr/ref slipped through.");
277 assert((DestRecord || DestPointee->isVoidType()) &&
278 "Bad destination pointee slipped through.");
279 assert(SrcRecord && "Bad source pointee slipped through.");
280
281 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
282 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000283 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000284 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000285 return;
286 }
287
288 // C++ 5.2.7p3: If the type of v is the same as the required result type,
289 // [except for cv].
290 if (DestRecord == SrcRecord) {
291 return;
292 }
293
294 // C++ 5.2.7p5
295 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000296 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
297 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner4bfd2232008-11-24 06:25:27 +0000298 OpRange.getBegin(), OpRange);
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000299 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000300 // Diagnostic already emitted on error.
301 return;
302 }
303
304 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000305 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000306 assert(SrcDecl && "Definition missing");
307 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner77d52da2008-11-20 06:06:08 +0000308 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000309 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000310 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000311
312 // Done. Everything else is run-time checks.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000313 Kind = CastExpr::CK_Dynamic;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000314}
Sebastian Redl0e35d042009-07-25 15:41:38 +0000315
316/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
317/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
318/// like this:
319/// const char *str = "literal";
320/// legacy_function(const_cast\<char*\>(str));
321void
322CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
323 const SourceRange &OpRange, const SourceRange &DestRange)
324{
325 if (!DestType->isLValueReferenceType())
326 Self.DefaultFunctionArrayConversion(SrcExpr);
327
328 unsigned msg = diag::err_bad_cxx_cast_generic;
329 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
330 && msg != 0)
331 Self.Diag(OpRange.getBegin(), msg) << CT_Const
332 << SrcExpr->getType() << DestType << OpRange;
333}
334
335/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
336/// valid.
337/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
338/// like this:
339/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
340void
341CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
342 const SourceRange &OpRange, const SourceRange &DestRange)
343{
344 if (!DestType->isLValueReferenceType())
345 Self.DefaultFunctionArrayConversion(SrcExpr);
346
347 unsigned msg = diag::err_bad_cxx_cast_generic;
348 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
349 != TC_Success && msg != 0)
350 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
351 << SrcExpr->getType() << DestType << OpRange;
352}
353
354
355/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
356/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
357/// implicit conversions explicit and getting rid of data loss warnings.
358void
359CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson9583fa72009-08-07 22:21:05 +0000360 const SourceRange &OpRange, CastExpr::CastKind &Kind)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000361{
362 // This test is outside everything else because it's the only case where
363 // a non-lvalue-reference target type does not lead to decay.
364 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
365 if (DestType->isVoidType()) {
366 return;
367 }
368
369 if (!DestType->isLValueReferenceType())
370 Self.DefaultFunctionArrayConversion(SrcExpr);
371
372 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9583fa72009-08-07 22:21:05 +0000373 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
374 Kind, msg)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000375 != TC_Success && msg != 0)
376 Self.Diag(OpRange.getBegin(), msg) << CT_Static
377 << SrcExpr->getType() << DestType << OpRange;
378}
379
380/// TryStaticCast - Check if a static cast can be performed, and do so if
381/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
382/// and casting away constness.
383static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
384 QualType DestType, bool CStyle,
385 const SourceRange &OpRange,
Anders Carlsson9583fa72009-08-07 22:21:05 +0000386 CastExpr::CastKind &Kind, unsigned &msg)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000387{
388 // The order the tests is not entirely arbitrary. There is one conversion
389 // that can be handled in two different ways. Given:
390 // struct A {};
391 // struct B : public A {
392 // B(); B(const A&);
393 // };
394 // const A &a = B();
395 // the cast static_cast<const B&>(a) could be seen as either a static
396 // reference downcast, or an explicit invocation of the user-defined
397 // conversion using B's conversion constructor.
398 // DR 427 specifies that the downcast is to be applied here.
399
400 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
401 // Done outside this function.
402
403 TryCastResult tcr;
404
405 // C++ 5.2.9p5, reference downcast.
406 // See the function for details.
407 // DR 427 specifies that this is to be applied before paragraph 2.
408 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
409 if (tcr != TC_NotApplicable)
410 return tcr;
411
412 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
413 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
414 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
415 if (tcr != TC_NotApplicable)
416 return tcr;
417
418 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
419 // [...] if the declaration "T t(e);" is well-formed, [...].
420 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg);
421 if (tcr != TC_NotApplicable)
422 return tcr;
423
424 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
425 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
426 // conversions, subject to further restrictions.
427 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
428 // of qualification conversions impossible.
429 // In the CStyle case, the earlier attempt to const_cast should have taken
430 // care of reverse qualification conversions.
431
432 QualType OrigSrcType = SrcExpr->getType();
433
434 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
435
436 // Reverse integral promotion/conversion. All such conversions are themselves
437 // again integral promotions or conversions and are thus already handled by
438 // p2 (TryDirectInitialization above).
439 // (Note: any data loss warnings should be suppressed.)
440 // The exception is the reverse of enum->integer, i.e. integer->enum (and
441 // enum->enum). See also C++ 5.2.9p7.
442 // The same goes for reverse floating point promotion/conversion and
443 // floating-integral conversions. Again, only floating->enum is relevant.
444 if (DestType->isEnumeralType()) {
445 if (SrcType->isComplexType() || SrcType->isVectorType()) {
446 // Fall through - these cannot be converted.
447 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
448 return TC_Success;
449 }
450
451 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
452 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
453 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
454 if (tcr != TC_NotApplicable)
455 return tcr;
456
457 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
458 // conversion. C++ 5.2.9p9 has additional information.
459 // DR54's access restrictions apply here also.
460 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
461 OpRange, msg);
462 if (tcr != TC_NotApplicable)
463 return tcr;
464
465 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
466 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
467 // just the usual constness stuff.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000468 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000469 QualType SrcPointee = SrcPointer->getPointeeType();
470 if (SrcPointee->isVoidType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000471 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000472 QualType DestPointee = DestPointer->getPointeeType();
473 if (DestPointee->isIncompleteOrObjectType()) {
474 // This is definitely the intended conversion, but it might fail due
475 // to a const violation.
476 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
477 msg = diag::err_bad_cxx_cast_const_away;
478 return TC_Failed;
479 }
480 return TC_Success;
481 }
482 }
483 }
484 }
485
486 // We tried everything. Everything! Nothing works! :-(
487 return TC_NotApplicable;
488}
489
490/// Tests whether a conversion according to N2844 is valid.
491TryCastResult
492TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
493 unsigned &msg)
494{
495 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
496 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000497 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000498 if (!R)
499 return TC_NotApplicable;
500
501 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
502 return TC_NotApplicable;
503
504 // Because we try the reference downcast before this function, from now on
505 // this is the only cast possibility, so we issue an error if we fail now.
506 // FIXME: Should allow casting away constness if CStyle.
507 bool DerivedToBase;
508 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
509 DerivedToBase) <
510 Sema::Ref_Compatible_With_Added_Qualification) {
511 msg = diag::err_bad_lvalue_to_rvalue_cast;
512 return TC_Failed;
513 }
514
515 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
516 // than nothing.
517 return TC_Success;
518}
519
520/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
521TryCastResult
522TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
523 bool CStyle, const SourceRange &OpRange,
524 unsigned &msg)
525{
526 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
527 // cast to type "reference to cv2 D", where D is a class derived from B,
528 // if a valid standard conversion from "pointer to D" to "pointer to B"
529 // exists, cv2 >= cv1, and B is not a virtual base class of D.
530 // In addition, DR54 clarifies that the base must be accessible in the
531 // current context. Although the wording of DR54 only applies to the pointer
532 // variant of this rule, the intent is clearly for it to apply to the this
533 // conversion as well.
534
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000535 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000536 if (!DestReference) {
537 return TC_NotApplicable;
538 }
539 bool RValueRef = DestReference->isRValueReferenceType();
540 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
541 // We know the left side is an lvalue reference, so we can suggest a reason.
542 msg = diag::err_bad_cxx_cast_rvalue;
543 return TC_NotApplicable;
544 }
545
546 QualType DestPointee = DestReference->getPointeeType();
547
548 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
549 OpRange, SrcExpr->getType(), DestType, msg);
550}
551
552/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
553TryCastResult
554TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
555 bool CStyle, const SourceRange &OpRange, unsigned &msg)
556{
557 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
558 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
559 // is a class derived from B, if a valid standard conversion from "pointer
560 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
561 // class of D.
562 // In addition, DR54 clarifies that the base must be accessible in the
563 // current context.
564
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000565 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000566 if (!DestPointer) {
567 return TC_NotApplicable;
568 }
569
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000570 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000571 if (!SrcPointer) {
572 msg = diag::err_bad_static_cast_pointer_nonpointer;
573 return TC_NotApplicable;
574 }
575
576 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
577 DestPointer->getPointeeType(), CStyle,
578 OpRange, SrcType, DestType, msg);
579}
580
581/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
582/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
583/// DestType, both of which must be canonical, is possible and allowed.
584TryCastResult
585TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
586 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
587 QualType OrigDestType, unsigned &msg)
588{
589 // Downcast can only happen in class hierarchies, so we need classes.
590 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
591 return TC_NotApplicable;
592 }
593
594 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
595 /*DetectVirtual=*/true);
596 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
597 return TC_NotApplicable;
598 }
599
600 // Target type does derive from source type. Now we're serious. If an error
601 // appears now, it's not ignored.
602 // This may not be entirely in line with the standard. Take for example:
603 // struct A {};
604 // struct B : virtual A {
605 // B(A&);
606 // };
607 //
608 // void f()
609 // {
610 // (void)static_cast<const B&>(*((A*)0));
611 // }
612 // As far as the standard is concerned, p5 does not apply (A is virtual), so
613 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
614 // However, both GCC and Comeau reject this example, and accepting it would
615 // mean more complex code if we're to preserve the nice error message.
616 // FIXME: Being 100% compliant here would be nice to have.
617
618 // Must preserve cv, as always, unless we're in C-style mode.
619 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
620 msg = diag::err_bad_cxx_cast_const_away;
621 return TC_Failed;
622 }
623
624 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
625 // This code is analoguous to that in CheckDerivedToBaseConversion, except
626 // that it builds the paths in reverse order.
627 // To sum up: record all paths to the base and build a nice string from
628 // them. Use it to spice up the error message.
629 if (!Paths.isRecordingPaths()) {
630 Paths.clear();
631 Paths.setRecordingPaths(true);
632 Self.IsDerivedFrom(DestType, SrcType, Paths);
633 }
634 std::string PathDisplayStr;
635 std::set<unsigned> DisplayedPaths;
636 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
637 PI != PE; ++PI) {
638 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
639 // We haven't displayed a path to this particular base
640 // class subobject yet.
641 PathDisplayStr += "\n ";
642 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
643 EI != EE; ++EI)
644 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
645 PathDisplayStr += DestType.getAsString();
646 }
647 }
648
649 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
650 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
651 << PathDisplayStr << OpRange;
652 msg = 0;
653 return TC_Failed;
654 }
655
656 if (Paths.getDetectedVirtual() != 0) {
657 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
658 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
659 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
660 msg = 0;
661 return TC_Failed;
662 }
663
664 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
665 diag::err_downcast_from_inaccessible_base, Paths,
666 OpRange.getBegin(), DeclarationName())) {
667 msg = 0;
668 return TC_Failed;
669 }
670
671 return TC_Success;
672}
673
674/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
675/// C++ 5.2.9p9 is valid:
676///
677/// An rvalue of type "pointer to member of D of type cv1 T" can be
678/// converted to an rvalue of type "pointer to member of B of type cv2 T",
679/// where B is a base class of D [...].
680///
681TryCastResult
682TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
683 bool CStyle, const SourceRange &OpRange,
684 unsigned &msg)
685{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000686 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000687 if (!DestMemPtr)
688 return TC_NotApplicable;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000689 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000690 if (!SrcMemPtr) {
691 msg = diag::err_bad_static_cast_member_pointer_nonmp;
692 return TC_NotApplicable;
693 }
694
695 // T == T, modulo cv
696 if (Self.Context.getCanonicalType(
697 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
698 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
699 getUnqualifiedType()))
700 return TC_NotApplicable;
701
702 // B base of D
703 QualType SrcClass(SrcMemPtr->getClass(), 0);
704 QualType DestClass(DestMemPtr->getClass(), 0);
705 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
706 /*DetectVirtual=*/true);
707 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
708 return TC_NotApplicable;
709 }
710
711 // B is a base of D. But is it an allowed base? If not, it's a hard error.
712 if (Paths.isAmbiguous(DestClass)) {
713 Paths.clear();
714 Paths.setRecordingPaths(true);
715 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
716 assert(StillOkay);
717 StillOkay = StillOkay;
718 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
719 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
720 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
721 msg = 0;
722 return TC_Failed;
723 }
724
725 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
726 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
727 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
728 msg = 0;
729 return TC_Failed;
730 }
731
732 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
733 diag::err_downcast_from_inaccessible_base, Paths,
734 OpRange.getBegin(), DeclarationName())) {
735 msg = 0;
736 return TC_Failed;
737 }
738
739 return TC_Success;
740}
741
742/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
743/// is valid:
744///
745/// An expression e can be explicitly converted to a type T using a
746/// @c static_cast if the declaration "T t(e);" is well-formed [...].
747TryCastResult
748TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
749 bool CStyle, const SourceRange &OpRange, unsigned &msg)
750{
751 if (DestType->isReferenceType()) {
752 // At this point of CheckStaticCast, if the destination is a reference,
753 // this has to work. There is no other way that works.
754 // On the other hand, if we're checking a C-style cast, we've still got
755 // the reinterpret_cast way. In that case, we pass an ICS so we don't
756 // get error messages.
757 ImplicitConversionSequence ICS;
758 bool failed = Self.CheckReferenceInit(SrcExpr, DestType, CStyle ? &ICS : 0);
759 if (!failed)
760 return TC_Success;
761 if (CStyle)
762 return TC_NotApplicable;
763 // If we didn't pass the ICS, we already got an error message.
764 msg = 0;
765 return TC_Failed;
766 }
767 if (DestType->isRecordType()) {
768 // There are no further possibilities for the target type being a class,
769 // neither in static_cast nor in a C-style cast. So we can fail here.
770 // FIXME: We need to store this constructor in the AST.
771 if (Self.PerformInitializationByConstructor(DestType, &SrcExpr, 1,
772 OpRange.getBegin(), OpRange, DeclarationName(), Sema::IK_Direct))
773 return TC_Success;
774 // The function already emitted an error.
775 msg = 0;
776 return TC_Failed;
777 }
778
779 // FIXME: To get a proper error from invalid conversions here, we need to
780 // reimplement more of this.
781 // FIXME: This does not actually perform the conversion, and thus does not
782 // check for ambiguity or access.
783 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
784 SrcExpr, DestType);
785 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
786 TC_NotApplicable : TC_Success;
787}
788
789/// TryConstCast - See if a const_cast from source to destination is allowed,
790/// and perform it if it is.
791static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
792 bool CStyle, unsigned &msg) {
793 DestType = Self.Context.getCanonicalType(DestType);
794 QualType SrcType = SrcExpr->getType();
795 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000796 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000797 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
798 // Cannot const_cast non-lvalue to lvalue reference type. But if this
799 // is C-style, static_cast might find a way, so we simply suggest a
800 // message and tell the parent to keep searching.
801 msg = diag::err_bad_cxx_cast_rvalue;
802 return TC_NotApplicable;
803 }
804
805 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
806 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
807 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
808 SrcType = Self.Context.getPointerType(SrcType);
809 }
810
811 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
812 // the rules for const_cast are the same as those used for pointers.
813
814 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
815 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
816 // was a reference type, we converted it to a pointer above.
817 // The status of rvalue references isn't entirely clear, but it looks like
818 // conversion to them is simply invalid.
819 // C++ 5.2.11p3: For two pointer types [...]
820 if (!CStyle)
821 msg = diag::err_bad_const_cast_dest;
822 return TC_NotApplicable;
823 }
824 if (DestType->isFunctionPointerType() ||
825 DestType->isMemberFunctionPointerType()) {
826 // Cannot cast direct function pointers.
827 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
828 // T is the ultimate pointee of source and target type.
829 if (!CStyle)
830 msg = diag::err_bad_const_cast_dest;
831 return TC_NotApplicable;
832 }
833 SrcType = Self.Context.getCanonicalType(SrcType);
834
835 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
836 // completely equal.
837 // FIXME: const_cast should probably not be able to convert between pointers
838 // to different address spaces.
839 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
840 // in multi-level pointers may change, but the level count must be the same,
841 // as must be the final pointee type.
842 while (SrcType != DestType &&
843 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
844 SrcType = SrcType.getUnqualifiedType();
845 DestType = DestType.getUnqualifiedType();
846 }
847
848 // Since we're dealing in canonical types, the remainder must be the same.
849 if (SrcType != DestType)
850 return TC_NotApplicable;
851
852 return TC_Success;
853}
854
855static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
856 QualType DestType, bool CStyle,
857 const SourceRange &OpRange,
858 unsigned &msg) {
859 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
860
861 DestType = Self.Context.getCanonicalType(DestType);
862 QualType SrcType = SrcExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000863 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000864 bool LValue = DestTypeTmp->isLValueReferenceType();
865 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
866 // Cannot cast non-lvalue to reference type. See the similar comment in
867 // const_cast.
868 msg = diag::err_bad_cxx_cast_rvalue;
869 return TC_NotApplicable;
870 }
871
872 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
873 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
874 // built-in & and * operators.
875 // This code does this transformation for the checked types.
876 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
877 SrcType = Self.Context.getPointerType(SrcType);
878 }
879
880 // Canonicalize source for comparison.
881 SrcType = Self.Context.getCanonicalType(SrcType);
882
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000883 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
884 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000885 if (DestMemPtr && SrcMemPtr) {
886 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
887 // can be explicitly converted to an rvalue of type "pointer to member
888 // of Y of type T2" if T1 and T2 are both function types or both object
889 // types.
890 if (DestMemPtr->getPointeeType()->isFunctionType() !=
891 SrcMemPtr->getPointeeType()->isFunctionType())
892 return TC_NotApplicable;
893
894 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
895 // constness.
896 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
897 // we accept it.
898 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
899 msg = diag::err_bad_cxx_cast_const_away;
900 return TC_Failed;
901 }
902
903 // A valid member pointer cast.
904 return TC_Success;
905 }
906
907 // See below for the enumeral issue.
908 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
909 !DestType->isEnumeralType()) {
910 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
911 // type large enough to hold it. A value of std::nullptr_t can be
912 // converted to an integral type; the conversion has the same meaning
913 // and validity as a conversion of (void*)0 to the integral type.
914 if (Self.Context.getTypeSize(SrcType) >
915 Self.Context.getTypeSize(DestType)) {
916 msg = diag::err_bad_reinterpret_cast_small_int;
917 return TC_Failed;
918 }
919 return TC_Success;
920 }
921
922 bool destIsPtr = DestType->isPointerType();
923 bool srcIsPtr = SrcType->isPointerType();
924 if (!destIsPtr && !srcIsPtr) {
925 // Except for std::nullptr_t->integer and lvalue->reference, which are
926 // handled above, at least one of the two arguments must be a pointer.
927 return TC_NotApplicable;
928 }
929
930 if (SrcType == DestType) {
931 // C++ 5.2.10p2 has a note that mentions that, subject to all other
932 // restrictions, a cast to the same type is allowed. The intent is not
933 // entirely clear here, since all other paragraphs explicitly forbid casts
934 // to the same type. However, the behavior of compilers is pretty consistent
935 // on this point: allow same-type conversion if the involved types are
936 // pointers, disallow otherwise.
937 return TC_Success;
938 }
939
940 // Note: Clang treats enumeration types as integral types. If this is ever
941 // changed for C++, the additional check here will be redundant.
942 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
943 assert(srcIsPtr && "One type must be a pointer");
944 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
945 // type large enough to hold it.
946 if (Self.Context.getTypeSize(SrcType) >
947 Self.Context.getTypeSize(DestType)) {
948 msg = diag::err_bad_reinterpret_cast_small_int;
949 return TC_Failed;
950 }
951 return TC_Success;
952 }
953
954 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
955 assert(destIsPtr && "One type must be a pointer");
956 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
957 // converted to a pointer.
958 return TC_Success;
959 }
960
961 if (!destIsPtr || !srcIsPtr) {
962 // With the valid non-pointer conversions out of the way, we can be even
963 // more stringent.
964 return TC_NotApplicable;
965 }
966
967 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
968 // The C-style cast operator can.
969 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
970 msg = diag::err_bad_cxx_cast_const_away;
971 return TC_Failed;
972 }
973
974 // Not casting away constness, so the only remaining check is for compatible
975 // pointer categories.
976
977 if (SrcType->isFunctionPointerType()) {
978 if (DestType->isFunctionPointerType()) {
979 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
980 // a pointer to a function of a different type.
981 return TC_Success;
982 }
983
984 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
985 // an object type or vice versa is conditionally-supported.
986 // Compilers support it in C++03 too, though, because it's necessary for
987 // casting the return value of dlsym() and GetProcAddress().
988 // FIXME: Conditionally-supported behavior should be configurable in the
989 // TargetInfo or similar.
990 if (!Self.getLangOptions().CPlusPlus0x)
991 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
992 return TC_Success;
993 }
994
995 if (DestType->isFunctionPointerType()) {
996 // See above.
997 if (!Self.getLangOptions().CPlusPlus0x)
998 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
999 return TC_Success;
1000 }
1001
1002 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1003 // a pointer to an object of different type.
1004 // Void pointers are not specified, but supported by every compiler out there.
1005 // So we finish by allowing everything that remains - it's got to be two
1006 // object pointers.
1007 return TC_Success;
1008}
1009
Sebastian Redlc358b622009-07-29 13:50:23 +00001010bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Anders Carlsson9583fa72009-08-07 22:21:05 +00001011 CastExpr::CastKind &Kind, bool FunctionalStyle)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001012{
1013 // This test is outside everything else because it's the only case where
1014 // a non-lvalue-reference target type does not lead to decay.
1015 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1016 if (CastTy->isVoidType())
1017 return false;
1018
1019 // If the type is dependent, we won't do any other semantic analysis now.
1020 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1021 return false;
1022
1023 if (!CastTy->isLValueReferenceType())
1024 DefaultFunctionArrayConversion(CastExpr);
1025
1026 // C++ [expr.cast]p5: The conversions performed by
1027 // - a const_cast,
1028 // - a static_cast,
1029 // - a static_cast followed by a const_cast,
1030 // - a reinterpret_cast, or
1031 // - a reinterpret_cast followed by a const_cast,
1032 // can be performed using the cast notation of explicit type conversion.
1033 // [...] If a conversion can be interpreted in more than one of the ways
1034 // listed above, the interpretation that appears first in the list is used,
1035 // even if a cast resulting from that interpretation is ill-formed.
1036 // In plain language, this means trying a const_cast ...
1037 unsigned msg = diag::err_bad_cxx_cast_generic;
1038 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,msg);
1039 if (tcr == TC_NotApplicable) {
1040 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson9583fa72009-08-07 22:21:05 +00001041 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, Kind, msg);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001042 if (tcr == TC_NotApplicable) {
1043 // ... and finally a reinterpret_cast, ignoring const.
1044 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
1045 }
1046 }
1047
Sebastian Redl0e35d042009-07-25 15:41:38 +00001048 if (tcr != TC_Success && msg != 0)
Sebastian Redlc358b622009-07-29 13:50:23 +00001049 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001050 << CastExpr->getType() << CastTy << R;
1051
1052 return tcr != TC_Success;
1053}