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