blob: 5c5c702fd50536cffaf651920009a67ab4a3f630 [file] [log] [blame]
Sebastian Redl3c5aa4d2008-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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000022using namespace clang;
23
Douglas Gregore81f58e2010-11-08 03:40:48 +000024
Douglas Gregore81f58e2010-11-08 03:40:48 +000025
Sebastian Redl9f831db2009-07-25 15:41:38 +000026enum TryCastResult {
27 TC_NotApplicable, ///< The cast method is not applicable.
28 TC_Success, ///< The cast method is appropriate and successful.
29 TC_Failed ///< The cast method is appropriate, but failed. A
30 ///< diagnostic has been emitted.
31};
32
33enum CastType {
34 CT_Const, ///< const_cast
35 CT_Static, ///< static_cast
36 CT_Reinterpret, ///< reinterpret_cast
37 CT_Dynamic, ///< dynamic_cast
38 CT_CStyle, ///< (Type)expr
39 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000040};
41
John McCallb50451a2011-10-05 07:41:44 +000042namespace {
43 struct CastOperation {
44 CastOperation(Sema &S, QualType destType, ExprResult src)
45 : Self(S), SrcExpr(src), DestType(destType),
46 ResultType(destType.getNonLValueExprType(S.Context)),
47 ValueKind(Expr::getValueKindForType(destType)),
48 Kind(CK_Dependent), IsARCUnbridgedCast(false) {}
Douglas Gregore81f58e2010-11-08 03:40:48 +000049
John McCallb50451a2011-10-05 07:41:44 +000050 Sema &Self;
51 ExprResult SrcExpr;
52 QualType DestType;
53 QualType ResultType;
54 ExprValueKind ValueKind;
55 CastKind Kind;
56 bool IsARCUnbridgedCast;
57 CXXCastPath BasePath;
Douglas Gregore81f58e2010-11-08 03:40:48 +000058
John McCallb50451a2011-10-05 07:41:44 +000059 SourceRange OpRange;
60 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000061
John McCallb50451a2011-10-05 07:41:44 +000062 void CheckConstCast();
63 void CheckReinterpretCast();
64 void CheckStaticCast();
65 void CheckDynamicCast();
66 void CheckCStyleCast(bool FunctionalCast);
67
68 void checkCastAlign() {
69 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
70 }
71
72 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
73 Expr *src = SrcExpr.get();
74 Self.CheckObjCARCConversion(OpRange, DestType, src, CCK);
75 SrcExpr = src;
76 }
77 };
78}
Sebastian Redl842ef522008-11-08 13:00:26 +000079
John McCall31168b02011-06-15 23:02:42 +000080static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
81 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-07-25 15:41:38 +000082
83// The Try functions attempt a specific way of casting. If they succeed, they
84// return TC_Success. If their way of casting is not appropriate for the given
85// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
86// to emit if no other way succeeds. If their way of casting is appropriate but
87// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
88// they emit a specialized diagnostic.
89// All diagnostics returned by these functions must expect the same three
90// arguments:
91// %0: Cast Type (a value from the CastType enumeration)
92// %1: Source Type
93// %2: Destination Type
94static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +000095 QualType DestType, bool CStyle,
96 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +000097 CXXCastPath &BasePath,
98 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +000099static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
102 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000103 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000104 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000105static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
106 QualType DestType, bool CStyle,
107 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000108 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000109 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000110 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000111static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
112 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000113 const SourceRange &OpRange,
114 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000115 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000116 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000117 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000118static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000119 QualType SrcType,
120 QualType DestType,bool CStyle,
121 const SourceRange &OpRange,
122 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000123 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000124 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000125
John Wiegley01296292011-04-08 18:41:53 +0000126static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000127 QualType DestType,
128 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000129 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000130 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000131 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +0000132static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000133 QualType DestType,
134 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000135 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000136 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000137 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000138 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000139static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
140 bool CStyle, unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000141static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000142 QualType DestType, bool CStyle,
143 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000144 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000145 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000146
Douglas Gregorb491ed32011-02-19 21:32:49 +0000147
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000148/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000149ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000150Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000151 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000152 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000153 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000154 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000155
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000156 assert(!D.isInvalidType());
157
158 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
159 if (D.isInvalidType())
160 return ExprError();
161
162 if (getLangOptions().CPlusPlus) {
163 // Check that there are no default arguments (C++ only).
164 CheckExtraCXXDefaultArguments(D);
165 }
166
167 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
John McCalld377e042010-01-15 19:13:16 +0000168 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
169 SourceRange(LParenLoc, RParenLoc));
170}
171
John McCalldadc5752010-08-24 06:29:42 +0000172ExprResult
John McCalld377e042010-01-15 19:13:16 +0000173Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000174 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000175 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000176 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000177 QualType DestType = DestTInfo->getType();
178
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000179 // If the type is dependent, we won't do the semantic analysis now.
180 // FIXME: should we check this in a more fine-grained manner?
John Wiegley01296292011-04-08 18:41:53 +0000181 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000182
John McCallb50451a2011-10-05 07:41:44 +0000183 CastOperation Op(*this, DestType, E);
184 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
185 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000186
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000187 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000188 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000189
190 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000191 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000192 Op.CheckConstCast();
193 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000194 return ExprError();
195 }
John McCallb50451a2011-10-05 07:41:44 +0000196 return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
197 Op.SrcExpr.take(), DestTInfo, OpLoc,
Douglas Gregor4478f852011-01-12 22:41:29 +0000198 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000199
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000200 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000201 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000202 Op.CheckDynamicCast();
203 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000204 return ExprError();
205 }
John McCallb50451a2011-10-05 07:41:44 +0000206 return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType,
207 Op.ValueKind, Op.Kind,
208 Op.SrcExpr.take(), &Op.BasePath,
209 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000210 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000211 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000212 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000213 Op.CheckReinterpretCast();
214 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000215 return ExprError();
216 }
John McCallb50451a2011-10-05 07:41:44 +0000217 return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
218 Op.ValueKind, Op.Kind,
219 Op.SrcExpr.take(), 0,
220 DestTInfo, OpLoc,
221 Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000222 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000223 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000224 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000225 Op.CheckStaticCast();
226 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000227 return ExprError();
228 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000229
John McCallb50451a2011-10-05 07:41:44 +0000230 return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
231 Op.Kind, Op.SrcExpr.take(),
232 &Op.BasePath, DestTInfo, OpLoc,
233 Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000234 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000235 }
236
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000237 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000238}
239
John McCall909acf82011-02-14 18:34:10 +0000240/// Try to diagnose a failed overloaded cast. Returns true if
241/// diagnostics were emitted.
242static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
243 SourceRange range, Expr *src,
244 QualType destType) {
245 switch (CT) {
246 // These cast kinds don't consider user-defined conversions.
247 case CT_Const:
248 case CT_Reinterpret:
249 case CT_Dynamic:
250 return false;
251
252 // These do.
253 case CT_Static:
254 case CT_CStyle:
255 case CT_Functional:
256 break;
257 }
258
259 QualType srcType = src->getType();
260 if (!destType->isRecordType() && !srcType->isRecordType())
261 return false;
262
263 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
264 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000265 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
266 range)
267 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
268 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall909acf82011-02-14 18:34:10 +0000269 InitializationSequence sequence(S, entity, initKind, &src, 1);
270
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000271 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000272 switch (sequence.getFailureKind()) {
273 default: return false;
274
275 case InitializationSequence::FK_ConstructorOverloadFailed:
276 case InitializationSequence::FK_UserConversionOverloadFailed:
277 break;
278 }
279
280 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
281
282 unsigned msg = 0;
283 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
284
285 switch (sequence.getFailedOverloadResult()) {
286 case OR_Success: llvm_unreachable("successful failed overload");
287 return false;
288 case OR_No_Viable_Function:
289 if (candidates.empty())
290 msg = diag::err_ovl_no_conversion_in_cast;
291 else
292 msg = diag::err_ovl_no_viable_conversion_in_cast;
293 howManyCandidates = OCD_AllCandidates;
294 break;
295
296 case OR_Ambiguous:
297 msg = diag::err_ovl_ambiguous_conversion_in_cast;
298 howManyCandidates = OCD_ViableCandidates;
299 break;
300
301 case OR_Deleted:
302 msg = diag::err_ovl_deleted_conversion_in_cast;
303 howManyCandidates = OCD_ViableCandidates;
304 break;
305 }
306
307 S.Diag(range.getBegin(), msg)
308 << CT << srcType << destType
309 << range << src->getSourceRange();
310
311 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
312
313 return true;
314}
315
316/// Diagnose a failed cast.
317static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
318 SourceRange opRange, Expr *src, QualType destType) {
John McCall0009fcc2011-04-26 20:42:42 +0000319 if (src->getType() == S.Context.BoundMemberTy) {
320 (void) S.CheckPlaceholderExpr(src); // will always fail
321 return;
322 }
323
John McCall909acf82011-02-14 18:34:10 +0000324 if (msg == diag::err_bad_cxx_cast_generic &&
325 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
326 return;
327
328 S.Diag(opRange.getBegin(), msg) << castType
329 << src->getType() << destType << opRange << src->getSourceRange();
330}
331
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000332/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
333/// this removes one level of indirection from both types, provided that they're
334/// the same kind of pointer (plain or to-member). Unlike the Sema function,
335/// this one doesn't care if the two pointers-to-member don't point into the
336/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000337static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000338 const PointerType *T1PtrType = T1->getAs<PointerType>(),
339 *T2PtrType = T2->getAs<PointerType>();
340 if (T1PtrType && T2PtrType) {
341 T1 = T1PtrType->getPointeeType();
342 T2 = T2PtrType->getPointeeType();
343 return true;
344 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000345 const ObjCObjectPointerType *T1ObjCPtrType =
346 T1->getAs<ObjCObjectPointerType>(),
347 *T2ObjCPtrType =
348 T2->getAs<ObjCObjectPointerType>();
349 if (T1ObjCPtrType) {
350 if (T2ObjCPtrType) {
351 T1 = T1ObjCPtrType->getPointeeType();
352 T2 = T2ObjCPtrType->getPointeeType();
353 return true;
354 }
355 else if (T2PtrType) {
356 T1 = T1ObjCPtrType->getPointeeType();
357 T2 = T2PtrType->getPointeeType();
358 return true;
359 }
360 }
361 else if (T2ObjCPtrType) {
362 if (T1PtrType) {
363 T2 = T2ObjCPtrType->getPointeeType();
364 T1 = T1PtrType->getPointeeType();
365 return true;
366 }
367 }
368
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000369 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
370 *T2MPType = T2->getAs<MemberPointerType>();
371 if (T1MPType && T2MPType) {
372 T1 = T1MPType->getPointeeType();
373 T2 = T2MPType->getPointeeType();
374 return true;
375 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000376
377 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
378 *T2BPType = T2->getAs<BlockPointerType>();
379 if (T1BPType && T2BPType) {
380 T1 = T1BPType->getPointeeType();
381 T2 = T2BPType->getPointeeType();
382 return true;
383 }
384
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000385 return false;
386}
387
Sebastian Redla5a77a62009-01-27 23:18:31 +0000388/// CastsAwayConstness - Check if the pointer conversion from SrcType to
389/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
390/// the cast checkers. Both arguments must denote pointer (possibly to member)
391/// types.
John McCall31168b02011-06-15 23:02:42 +0000392///
393/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
394///
395/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000396static bool
John McCall31168b02011-06-15 23:02:42 +0000397CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
398 bool CheckCVR, bool CheckObjCLifetime) {
399 // If the only checking we care about is for Objective-C lifetime qualifiers,
400 // and we're not in ARC mode, there's nothing to check.
401 if (!CheckCVR && CheckObjCLifetime &&
402 !Self.Context.getLangOptions().ObjCAutoRefCount)
403 return false;
404
Sebastian Redla5a77a62009-01-27 23:18:31 +0000405 // Casting away constness is defined in C++ 5.2.11p8 with reference to
406 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
407 // the rules are non-trivial. So first we construct Tcv *...cv* as described
408 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000409 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
410 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000411 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000412 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
413 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000414 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000415
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000416 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
417 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000418 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000419
Douglas Gregorb472e932011-04-15 17:59:54 +0000420 // Find the qualifiers. We only care about cvr-qualifiers for the
421 // purpose of this check, because other qualifiers (address spaces,
422 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000423 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000424 // Determine the relevant qualifiers at this level.
425 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000426 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000427 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000428
429 Qualifiers RetainedSrcQuals, RetainedDestQuals;
430 if (CheckCVR) {
431 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
432 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
433 }
434
435 if (CheckObjCLifetime &&
436 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
437 return true;
438
439 cv1.push_back(RetainedSrcQuals);
440 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000441 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000442 if (cv1.empty())
443 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000444
445 // Construct void pointers with those qualifiers (in reverse order of
446 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000447 QualType SrcConstruct = Self.Context.VoidTy;
448 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000449 ASTContext &Context = Self.Context;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000450 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall8ccfcb52009-09-24 19:53:00 +0000451 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000452 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000453 SrcConstruct
454 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
455 DestConstruct
456 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000457 }
458
459 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000460 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000461 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000462 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
463 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000464}
465
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000466/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
467/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
468/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000469void CastOperation::CheckDynamicCast() {
470 QualType OrigSrcType = SrcExpr.get()->getType();
471 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000472
473 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
474 // or "pointer to cv void".
475
476 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000477 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000478 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000479 if (DestPointer) {
480 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000481 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000482 DestPointee = DestReference->getPointeeType();
483 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000484 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000485 << this->DestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000486 return;
487 }
488
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000489 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000490 if (DestPointee->isVoidType()) {
491 assert(DestPointer && "Reference to void is not possible");
492 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000493 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000494 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000495 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000496 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000497 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000498 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000499 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000500 return;
501 }
502
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000503 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
504 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000505 // an lvalue of a complete class type, [...]. If T is an rvalue reference
506 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000507 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000508 QualType SrcPointee;
509 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000510 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000511 SrcPointee = SrcPointer->getPointeeType();
512 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000513 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000514 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000515 return;
516 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000517 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000518 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000519 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000520 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000521 }
522 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000523 } else {
524 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000525 }
526
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000527 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000528 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000529 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000530 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley01296292011-04-08 18:41:53 +0000531 << SrcExpr.get()->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000532 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000533 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000534 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000535 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000536 return;
537 }
538
539 assert((DestPointer || DestReference) &&
540 "Bad destination non-ptr/ref slipped through.");
541 assert((DestRecord || DestPointee->isVoidType()) &&
542 "Bad destination pointee slipped through.");
543 assert(SrcRecord && "Bad source pointee slipped through.");
544
545 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
546 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000547 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000548 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000549 return;
550 }
551
552 // C++ 5.2.7p3: If the type of v is the same as the required result type,
553 // [except for cv].
554 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000555 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000556 return;
557 }
558
559 // C++ 5.2.7p5
560 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000561 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000562 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
563 OpRange.getBegin(), OpRange,
564 &BasePath))
565 return;
566
John McCalle3027922010-08-25 11:45:40 +0000567 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000568
569 // If we are casting to or through a virtual base class, we need a
570 // vtable.
571 if (Self.BasePathInvolvesVirtualBase(BasePath))
572 Self.MarkVTableUsed(OpRange.getBegin(),
573 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000574 return;
575 }
576
577 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000578 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000579 assert(SrcDecl && "Definition missing");
580 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000581 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000582 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000583 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000584 Self.MarkVTableUsed(OpRange.getBegin(),
585 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000586
587 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000588 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000589}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000590
591/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
592/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
593/// like this:
594/// const char *str = "literal";
595/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000596void CastOperation::CheckConstCast() {
597 if (ValueKind == VK_RValue) {
John Wiegley01296292011-04-08 18:41:53 +0000598 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
599 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
600 return;
601 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000602
603 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley01296292011-04-08 18:41:53 +0000604 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9f831db2009-07-25 15:41:38 +0000605 && msg != 0)
606 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000607 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000608}
609
610/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
611/// valid.
612/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
613/// like this:
614/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000615void CastOperation::CheckReinterpretCast() {
616 if (ValueKind == VK_RValue) {
John Wiegley01296292011-04-08 18:41:53 +0000617 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
618 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
619 return;
620 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000621
622 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000623 TryCastResult tcr =
624 TryReinterpretCast(Self, SrcExpr, DestType,
625 /*CStyle*/false, OpRange, msg, Kind);
626 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000627 {
John Wiegley01296292011-04-08 18:41:53 +0000628 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
629 return;
630 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000631 //FIXME: &f<int>; is overloaded and resolvable
632 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000633 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000634 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000635 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000636
John McCall909acf82011-02-14 18:34:10 +0000637 } else {
John Wiegley01296292011-04-08 18:41:53 +0000638 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000639 }
John McCall31168b02011-06-15 23:02:42 +0000640 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb50451a2011-10-05 07:41:44 +0000641 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCall31168b02011-06-15 23:02:42 +0000642 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000643}
644
645
646/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
647/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
648/// implicit conversions explicit and getting rid of data loss warnings.
John McCallb50451a2011-10-05 07:41:44 +0000649void CastOperation::CheckStaticCast() {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000650 // This test is outside everything else because it's the only case where
651 // a non-lvalue-reference target type does not lead to decay.
652 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000653 if (DestType->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +0000654 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
655 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
656 return;
657 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregorb491ed32011-02-19 21:32:49 +0000658 ExprResult SingleFunctionExpression =
John Wiegley01296292011-04-08 18:41:53 +0000659 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +0000660 false, // Decay Function to ptr
661 true, // Complain
662 OpRange, DestType, diag::err_bad_static_cast_overload);
663 if (SingleFunctionExpression.isUsable())
664 {
John Wiegley01296292011-04-08 18:41:53 +0000665 SrcExpr = SingleFunctionExpression;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000666 Kind = CK_ToVoid;
667 }
668 }
669 else
670 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000671 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000672 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000673
John McCallb50451a2011-10-05 07:41:44 +0000674 if (ValueKind == VK_RValue && !DestType->isRecordType()) {
John Wiegley01296292011-04-08 18:41:53 +0000675 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
676 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
677 return;
678 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000679
680 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000681 TryCastResult tcr
682 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
683 Kind, BasePath);
684 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000685 if (SrcExpr.isInvalid())
686 return;
687 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
688 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000689 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000690 << oe->getName() << DestType << OpRange
691 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000692 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000693 } else {
John Wiegley01296292011-04-08 18:41:53 +0000694 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000695 }
John McCall31168b02011-06-15 23:02:42 +0000696 } else if (tcr == TC_Success) {
697 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000698 checkCastAlign();
699 if (Self.getLangOptions().ObjCAutoRefCount)
700 checkObjCARCConversion(Sema::CCK_OtherCast);
701 } else if (Kind == CK_BitCast) {
702 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000703 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000704}
705
706/// TryStaticCast - Check if a static cast can be performed, and do so if
707/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
708/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000709static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000710 QualType DestType,
711 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000712 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000713 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000714 CXXCastPath &BasePath) {
John McCall31168b02011-06-15 23:02:42 +0000715 // Determine whether we have the semantics of a C-style cast.
716 bool CStyle
717 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
718
Sebastian Redl9f831db2009-07-25 15:41:38 +0000719 // The order the tests is not entirely arbitrary. There is one conversion
720 // that can be handled in two different ways. Given:
721 // struct A {};
722 // struct B : public A {
723 // B(); B(const A&);
724 // };
725 // const A &a = B();
726 // the cast static_cast<const B&>(a) could be seen as either a static
727 // reference downcast, or an explicit invocation of the user-defined
728 // conversion using B's conversion constructor.
729 // DR 427 specifies that the downcast is to be applied here.
730
731 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
732 // Done outside this function.
733
734 TryCastResult tcr;
735
736 // C++ 5.2.9p5, reference downcast.
737 // See the function for details.
738 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley01296292011-04-08 18:41:53 +0000739 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000740 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000741 if (tcr != TC_NotApplicable)
742 return tcr;
743
Douglas Gregor465184a2011-01-22 00:06:57 +0000744 // C++0x [expr.static.cast]p3:
745 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
746 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley01296292011-04-08 18:41:53 +0000747 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregorce950842011-01-26 21:04:06 +0000748 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000749 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000750 return tcr;
751
752 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
753 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000754 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000755 Kind);
John Wiegley01296292011-04-08 18:41:53 +0000756 if (SrcExpr.isInvalid())
757 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000758 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000759 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000760
Sebastian Redl9f831db2009-07-25 15:41:38 +0000761 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
762 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
763 // conversions, subject to further restrictions.
764 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
765 // of qualification conversions impossible.
766 // In the CStyle case, the earlier attempt to const_cast should have taken
767 // care of reverse qualification conversions.
768
John Wiegley01296292011-04-08 18:41:53 +0000769 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000770
Douglas Gregor0bf31402010-10-08 23:50:27 +0000771 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000772 // converted to an integral type. [...] A value of a scoped enumeration type
773 // can also be explicitly converted to a floating-point type [...].
774 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
775 if (Enum->getDecl()->isScoped()) {
776 if (DestType->isBooleanType()) {
777 Kind = CK_IntegralToBoolean;
778 return TC_Success;
779 } else if (DestType->isIntegralType(Self.Context)) {
780 Kind = CK_IntegralCast;
781 return TC_Success;
782 } else if (DestType->isRealFloatingType()) {
783 Kind = CK_IntegralToFloating;
784 return TC_Success;
785 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000786 }
787 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000788
Sebastian Redl9f831db2009-07-25 15:41:38 +0000789 // Reverse integral promotion/conversion. All such conversions are themselves
790 // again integral promotions or conversions and are thus already handled by
791 // p2 (TryDirectInitialization above).
792 // (Note: any data loss warnings should be suppressed.)
793 // The exception is the reverse of enum->integer, i.e. integer->enum (and
794 // enum->enum). See also C++ 5.2.9p7.
795 // The same goes for reverse floating point promotion/conversion and
796 // floating-integral conversions. Again, only floating->enum is relevant.
797 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +0000798 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +0000799 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000800 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +0000801 } else if (SrcType->isRealFloatingType()) {
802 Kind = CK_FloatingToIntegral;
803 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000804 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000805 }
806
807 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
808 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000809 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000810 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000811 if (tcr != TC_NotApplicable)
812 return tcr;
813
814 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
815 // conversion. C++ 5.2.9p9 has additional information.
816 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000817 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000818 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000819 if (tcr != TC_NotApplicable)
820 return tcr;
821
822 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
823 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
824 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000825 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000826 QualType SrcPointee = SrcPointer->getPointeeType();
827 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000828 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000829 QualType DestPointee = DestPointer->getPointeeType();
830 if (DestPointee->isIncompleteOrObjectType()) {
831 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +0000832 // to a qualifier violation. Note that we permit Objective-C lifetime
833 // and GC qualifier mismatches here.
834 if (!CStyle) {
835 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
836 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
837 DestPointeeQuals.removeObjCGCAttr();
838 DestPointeeQuals.removeObjCLifetime();
839 SrcPointeeQuals.removeObjCGCAttr();
840 SrcPointeeQuals.removeObjCLifetime();
841 if (DestPointeeQuals != SrcPointeeQuals &&
842 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
843 msg = diag::err_bad_cxx_cast_qualifiers_away;
844 return TC_Failed;
845 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000846 }
John McCalle3027922010-08-25 11:45:40 +0000847 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000848 return TC_Success;
849 }
850 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000851 else if (DestType->isObjCObjectPointerType()) {
852 // allow both c-style cast and static_cast of objective-c pointers as
853 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +0000854 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000855 return TC_Success;
856 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000857 else if (CStyle && DestType->isBlockPointerType()) {
858 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000859 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000860 return TC_Success;
861 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000862 }
863 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000864 // Allow arbitray objective-c pointer conversion with static casts.
865 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000866 DestType->isObjCObjectPointerType()) {
867 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000868 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000869 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000870
Sebastian Redl9f831db2009-07-25 15:41:38 +0000871 // We tried everything. Everything! Nothing works! :-(
872 return TC_NotApplicable;
873}
874
875/// Tests whether a conversion according to N2844 is valid.
876TryCastResult
877TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000878 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
879 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000880 // C++0x [expr.static.cast]p3:
881 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
882 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000883 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000884 if (!R)
885 return TC_NotApplicable;
886
Douglas Gregor465184a2011-01-22 00:06:57 +0000887 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000888 return TC_NotApplicable;
889
890 // Because we try the reference downcast before this function, from now on
891 // this is the only cast possibility, so we issue an error if we fail now.
892 // FIXME: Should allow casting away constness if CStyle.
893 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000894 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +0000895 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000896 QualType FromType = SrcExpr->getType();
897 QualType ToType = R->getPointeeType();
898 if (CStyle) {
899 FromType = FromType.getUnqualifiedType();
900 ToType = ToType.getUnqualifiedType();
901 }
902
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000903 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000904 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +0000905 DerivedToBase, ObjCConversion,
906 ObjCLifetimeConversion)
907 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000908 msg = diag::err_bad_lvalue_to_rvalue_cast;
909 return TC_Failed;
910 }
911
Douglas Gregorba278e22011-01-25 16:13:26 +0000912 if (DerivedToBase) {
913 Kind = CK_DerivedToBase;
914 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
915 /*DetectVirtual=*/true);
916 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
917 return TC_NotApplicable;
918
919 Self.BuildBasePathArray(Paths, BasePath);
920 } else
921 Kind = CK_NoOp;
922
Sebastian Redl9f831db2009-07-25 15:41:38 +0000923 return TC_Success;
924}
925
926/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
927TryCastResult
928TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
929 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000930 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000931 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000932 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
933 // cast to type "reference to cv2 D", where D is a class derived from B,
934 // if a valid standard conversion from "pointer to D" to "pointer to B"
935 // exists, cv2 >= cv1, and B is not a virtual base class of D.
936 // In addition, DR54 clarifies that the base must be accessible in the
937 // current context. Although the wording of DR54 only applies to the pointer
938 // variant of this rule, the intent is clearly for it to apply to the this
939 // conversion as well.
940
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000941 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000942 if (!DestReference) {
943 return TC_NotApplicable;
944 }
945 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000946 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000947 // We know the left side is an lvalue reference, so we can suggest a reason.
948 msg = diag::err_bad_cxx_cast_rvalue;
949 return TC_NotApplicable;
950 }
951
952 QualType DestPointee = DestReference->getPointeeType();
953
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000954 return TryStaticDowncast(Self,
955 Self.Context.getCanonicalType(SrcExpr->getType()),
956 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000957 OpRange, SrcExpr->getType(), DestType, msg, Kind,
958 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000959}
960
961/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
962TryCastResult
963TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000964 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000965 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000966 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000967 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
968 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
969 // is a class derived from B, if a valid standard conversion from "pointer
970 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
971 // class of D.
972 // In addition, DR54 clarifies that the base must be accessible in the
973 // current context.
974
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000975 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000976 if (!DestPointer) {
977 return TC_NotApplicable;
978 }
979
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000980 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000981 if (!SrcPointer) {
982 msg = diag::err_bad_static_cast_pointer_nonpointer;
983 return TC_NotApplicable;
984 }
985
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000986 return TryStaticDowncast(Self,
987 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
988 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000989 CStyle, OpRange, SrcType, DestType, msg, Kind,
990 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000991}
992
993/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
994/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000995/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000996TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000997TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000998 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000999 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001000 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001001 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +00001002 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1003 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001004 return TC_NotApplicable;
1005
Sebastian Redl9f831db2009-07-25 15:41:38 +00001006 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001007 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001008 return TC_NotApplicable;
1009 }
1010
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001011 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001012 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001013 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1014 return TC_NotApplicable;
1015 }
1016
1017 // Target type does derive from source type. Now we're serious. If an error
1018 // appears now, it's not ignored.
1019 // This may not be entirely in line with the standard. Take for example:
1020 // struct A {};
1021 // struct B : virtual A {
1022 // B(A&);
1023 // };
Mike Stump11289f42009-09-09 15:08:12 +00001024 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 // void f()
1026 // {
1027 // (void)static_cast<const B&>(*((A*)0));
1028 // }
1029 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1030 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1031 // However, both GCC and Comeau reject this example, and accepting it would
1032 // mean more complex code if we're to preserve the nice error message.
1033 // FIXME: Being 100% compliant here would be nice to have.
1034
1035 // Must preserve cv, as always, unless we're in C-style mode.
1036 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001037 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001038 return TC_Failed;
1039 }
1040
1041 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1042 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1043 // that it builds the paths in reverse order.
1044 // To sum up: record all paths to the base and build a nice string from
1045 // them. Use it to spice up the error message.
1046 if (!Paths.isRecordingPaths()) {
1047 Paths.clear();
1048 Paths.setRecordingPaths(true);
1049 Self.IsDerivedFrom(DestType, SrcType, Paths);
1050 }
1051 std::string PathDisplayStr;
1052 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001053 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001054 PI != PE; ++PI) {
1055 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1056 // We haven't displayed a path to this particular base
1057 // class subobject yet.
1058 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001059 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1060 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001061 EI != EE; ++EI)
1062 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001063 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001064 }
1065 }
1066
1067 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001068 << QualType(SrcType).getUnqualifiedType()
1069 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001070 << PathDisplayStr << OpRange;
1071 msg = 0;
1072 return TC_Failed;
1073 }
1074
1075 if (Paths.getDetectedVirtual() != 0) {
1076 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1077 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1078 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1079 msg = 0;
1080 return TC_Failed;
1081 }
1082
John McCallfe9cf0a2011-02-14 23:21:33 +00001083 if (!CStyle) {
1084 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1085 SrcType, DestType,
1086 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001087 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001088 case Sema::AR_accessible:
1089 case Sema::AR_delayed: // be optimistic
1090 case Sema::AR_dependent: // be optimistic
1091 break;
1092
1093 case Sema::AR_inaccessible:
1094 msg = 0;
1095 return TC_Failed;
1096 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001097 }
1098
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001099 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001100 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001101 return TC_Success;
1102}
1103
1104/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1105/// C++ 5.2.9p9 is valid:
1106///
1107/// An rvalue of type "pointer to member of D of type cv1 T" can be
1108/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1109/// where B is a base class of D [...].
1110///
1111TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001112TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001113 QualType DestType, bool CStyle,
1114 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001115 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001116 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001117 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001118 if (!DestMemPtr)
1119 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001120
1121 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001122 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001123 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001124 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001125 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001126 FoundOverload)) {
1127 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1128 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1129 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1130 WasOverloadedFunction = true;
1131 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001132 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001133
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001134 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001135 if (!SrcMemPtr) {
1136 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1137 return TC_NotApplicable;
1138 }
1139
1140 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001141 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1142 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001143 return TC_NotApplicable;
1144
1145 // B base of D
1146 QualType SrcClass(SrcMemPtr->getClass(), 0);
1147 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001148 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001149 /*DetectVirtual=*/true);
1150 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1151 return TC_NotApplicable;
1152 }
1153
1154 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +00001155 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001156 Paths.clear();
1157 Paths.setRecordingPaths(true);
1158 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1159 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001160 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001161 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1162 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1163 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1164 msg = 0;
1165 return TC_Failed;
1166 }
1167
1168 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1169 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1170 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1171 msg = 0;
1172 return TC_Failed;
1173 }
1174
John McCallfe9cf0a2011-02-14 23:21:33 +00001175 if (!CStyle) {
1176 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1177 DestClass, SrcClass,
1178 Paths.front(),
1179 diag::err_upcast_to_inaccessible_base)) {
1180 case Sema::AR_accessible:
1181 case Sema::AR_delayed:
1182 case Sema::AR_dependent:
1183 // Optimistically assume that the delayed and dependent cases
1184 // will work out.
1185 break;
1186
1187 case Sema::AR_inaccessible:
1188 msg = 0;
1189 return TC_Failed;
1190 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001191 }
1192
Douglas Gregorc934bc82010-03-07 23:24:59 +00001193 if (WasOverloadedFunction) {
1194 // Resolve the address of the overloaded function again, this time
1195 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001196 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001197 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001198 true,
1199 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001200 if (!Fn) {
1201 msg = 0;
1202 return TC_Failed;
1203 }
1204
John McCall16df1e52010-03-30 21:47:33 +00001205 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001206 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001207 msg = 0;
1208 return TC_Failed;
1209 }
1210 }
1211
Anders Carlssonb78feca2010-04-24 19:22:20 +00001212 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001213 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001214 return TC_Success;
1215}
1216
1217/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1218/// is valid:
1219///
1220/// An expression e can be explicitly converted to a type T using a
1221/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1222TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001223TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001224 Sema::CheckedConversionKind CCK,
1225 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001226 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001227 if (DestType->isRecordType()) {
1228 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1229 diag::err_bad_dynamic_cast_incomplete)) {
1230 msg = 0;
1231 return TC_Failed;
1232 }
1233 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001234
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001235 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1236 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001237 = (CCK == Sema::CCK_CStyleCast)
1238 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1239 : (CCK == Sema::CCK_FunctionalCast)
1240 ? InitializationKind::CreateFunctionalCast(OpRange)
1241 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001242 Expr *SrcExprRaw = SrcExpr.get();
1243 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001244
1245 // At this point of CheckStaticCast, if the destination is a reference,
1246 // or the expression is an overload expression this has to work.
1247 // There is no other way that works.
1248 // On the other hand, if we're checking a C-style cast, we've still got
1249 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001250 bool CStyle
1251 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001252 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001253 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001254
John McCalldadc5752010-08-24 06:29:42 +00001255 ExprResult Result
John Wiegley01296292011-04-08 18:41:53 +00001256 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001257 if (Result.isInvalid()) {
1258 msg = 0;
1259 return TC_Failed;
1260 }
1261
Douglas Gregorb33eed02010-04-16 22:09:46 +00001262 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001263 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001264 else
John McCalle3027922010-08-25 11:45:40 +00001265 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001266
John Wiegley01296292011-04-08 18:41:53 +00001267 SrcExpr = move(Result);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001268 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001269}
1270
1271/// TryConstCast - See if a const_cast from source to destination is allowed,
1272/// and perform it if it is.
1273static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1274 bool CStyle, unsigned &msg) {
1275 DestType = Self.Context.getCanonicalType(DestType);
1276 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001277 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1278 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001279 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1280 // is C-style, static_cast might find a way, so we simply suggest a
1281 // message and tell the parent to keep searching.
1282 msg = diag::err_bad_cxx_cast_rvalue;
1283 return TC_NotApplicable;
1284 }
1285
1286 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1287 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1288 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1289 SrcType = Self.Context.getPointerType(SrcType);
1290 }
1291
1292 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1293 // the rules for const_cast are the same as those used for pointers.
1294
John McCall0e704f72010-05-18 09:35:29 +00001295 if (!DestType->isPointerType() &&
1296 !DestType->isMemberPointerType() &&
1297 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001298 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1299 // was a reference type, we converted it to a pointer above.
1300 // The status of rvalue references isn't entirely clear, but it looks like
1301 // conversion to them is simply invalid.
1302 // C++ 5.2.11p3: For two pointer types [...]
1303 if (!CStyle)
1304 msg = diag::err_bad_const_cast_dest;
1305 return TC_NotApplicable;
1306 }
1307 if (DestType->isFunctionPointerType() ||
1308 DestType->isMemberFunctionPointerType()) {
1309 // Cannot cast direct function pointers.
1310 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1311 // T is the ultimate pointee of source and target type.
1312 if (!CStyle)
1313 msg = diag::err_bad_const_cast_dest;
1314 return TC_NotApplicable;
1315 }
1316 SrcType = Self.Context.getCanonicalType(SrcType);
1317
1318 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1319 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001320 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1321 // in multi-level pointers may change, but the level count must be the same,
1322 // as must be the final pointee type.
1323 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001324 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001325 Qualifiers SrcQuals, DestQuals;
1326 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1327 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1328
1329 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1330 // the other qualifiers (e.g., address spaces) are identical.
1331 SrcQuals.removeCVRQualifiers();
1332 DestQuals.removeCVRQualifiers();
1333 if (SrcQuals != DestQuals)
1334 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001335 }
1336
1337 // Since we're dealing in canonical types, the remainder must be the same.
1338 if (SrcType != DestType)
1339 return TC_NotApplicable;
1340
1341 return TC_Success;
1342}
1343
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001344// Checks for undefined behavior in reinterpret_cast.
1345// The cases that is checked for is:
1346// *reinterpret_cast<T*>(&a)
1347// reinterpret_cast<T&>(a)
1348// where accessing 'a' as type 'T' will result in undefined behavior.
1349void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1350 bool IsDereference,
1351 SourceRange Range) {
1352 unsigned DiagID = IsDereference ?
1353 diag::warn_pointer_indirection_from_incompatible_type :
1354 diag::warn_undefined_reinterpret_cast;
1355
1356 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00001357 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001358 return;
1359 }
1360
1361 QualType SrcTy, DestTy;
1362 if (IsDereference) {
1363 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1364 return;
1365 }
1366 SrcTy = SrcType->getPointeeType();
1367 DestTy = DestType->getPointeeType();
1368 } else {
1369 if (!DestType->getAs<ReferenceType>()) {
1370 return;
1371 }
1372 SrcTy = SrcType;
1373 DestTy = DestType->getPointeeType();
1374 }
1375
1376 // Cast is compatible if the types are the same.
1377 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1378 return;
1379 }
1380 // or one of the types is a char or void type
1381 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1382 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1383 return;
1384 }
1385 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001386 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001387 return;
1388 }
1389
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001390 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001391 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1392 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1393 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1394 return;
1395 }
1396 }
1397
1398 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1399}
Douglas Gregor1beec452011-03-12 01:48:56 +00001400
John Wiegley01296292011-04-08 18:41:53 +00001401static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001402 QualType DestType, bool CStyle,
1403 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001404 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001405 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001406 bool IsLValueCast = false;
1407
Sebastian Redl9f831db2009-07-25 15:41:38 +00001408 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001409 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001410
1411 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001412 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1413 if (SrcType == Self.Context.OverloadTy) {
1414 // ... unless foo<int> resolves to an lvalue unambiguously
1415 ExprResult SingleFunctionExpr =
John Wiegley01296292011-04-08 18:41:53 +00001416 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +00001417 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1418 );
1419 if (SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001420 SrcExpr = move(SingleFunctionExpr);
1421 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001422 }
1423 else
1424 return TC_NotApplicable;
1425 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001426
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001427 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001428 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00001429 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001430 // Cannot cast non-lvalue to lvalue reference type. See the similar
1431 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001432 msg = diag::err_bad_cxx_cast_rvalue;
1433 return TC_NotApplicable;
1434 }
1435
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001436 if (!CStyle) {
1437 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1438 /*isDereference=*/false, OpRange);
1439 }
1440
Sebastian Redl9f831db2009-07-25 15:41:38 +00001441 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1442 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1443 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001444
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001445 const char *inappropriate = 0;
1446 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001447 case OK_Ordinary:
1448 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001449 case OK_BitField: inappropriate = "bit-field"; break;
1450 case OK_VectorComponent: inappropriate = "vector element"; break;
1451 case OK_ObjCProperty: inappropriate = "property expression"; break;
1452 }
1453 if (inappropriate) {
1454 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1455 << inappropriate << DestType
1456 << OpRange << SrcExpr.get()->getSourceRange();
1457 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001458 return TC_NotApplicable;
1459 }
1460
Sebastian Redl9f831db2009-07-25 15:41:38 +00001461 // This code does this transformation for the checked types.
1462 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1463 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001464
Douglas Gregor51954272010-07-13 23:17:26 +00001465 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001466 }
1467
1468 // Canonicalize source for comparison.
1469 SrcType = Self.Context.getCanonicalType(SrcType);
1470
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001471 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1472 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001473 if (DestMemPtr && SrcMemPtr) {
1474 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1475 // can be explicitly converted to an rvalue of type "pointer to member
1476 // of Y of type T2" if T1 and T2 are both function types or both object
1477 // types.
1478 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1479 SrcMemPtr->getPointeeType()->isFunctionType())
1480 return TC_NotApplicable;
1481
1482 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1483 // constness.
1484 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1485 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001486 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1487 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001488 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001489 return TC_Failed;
1490 }
1491
Charles Davisebab1ed2010-08-16 05:30:44 +00001492 // Don't allow casting between member pointers of different sizes.
1493 if (Self.Context.getTypeSize(DestMemPtr) !=
1494 Self.Context.getTypeSize(SrcMemPtr)) {
1495 msg = diag::err_bad_cxx_cast_member_pointer_size;
1496 return TC_Failed;
1497 }
1498
Sebastian Redl9f831db2009-07-25 15:41:38 +00001499 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001500 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001501 return TC_Success;
1502 }
1503
1504 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001505 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001506 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1507 // type large enough to hold it. A value of std::nullptr_t can be
1508 // converted to an integral type; the conversion has the same meaning
1509 // and validity as a conversion of (void*)0 to the integral type.
1510 if (Self.Context.getTypeSize(SrcType) >
1511 Self.Context.getTypeSize(DestType)) {
1512 msg = diag::err_bad_reinterpret_cast_small_int;
1513 return TC_Failed;
1514 }
John McCalle3027922010-08-25 11:45:40 +00001515 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001516 return TC_Success;
1517 }
1518
Anders Carlsson570af5d2009-09-16 19:19:43 +00001519 bool destIsVector = DestType->isVectorType();
1520 bool srcIsVector = SrcType->isVectorType();
1521 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001522 // FIXME: Should this also apply to floating point types?
1523 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1524 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001525
1526 // Check if this is a cast between a vector and something else.
1527 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1528 !(srcIsVector && destIsVector))
1529 return TC_NotApplicable;
1530
1531 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001532 if (Self.Context.getTypeSize(SrcType)
1533 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001534 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001535 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001536 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001537
1538 if (destIsScalar)
1539 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1540 else if (srcIsScalar)
1541 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1542 else
1543 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1544
1545 return TC_Failed;
1546 }
1547
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001548 bool destIsPtr = DestType->isAnyPointerType() ||
1549 DestType->isBlockPointerType();
1550 bool srcIsPtr = SrcType->isAnyPointerType() ||
1551 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001552 if (!destIsPtr && !srcIsPtr) {
1553 // Except for std::nullptr_t->integer and lvalue->reference, which are
1554 // handled above, at least one of the two arguments must be a pointer.
1555 return TC_NotApplicable;
1556 }
1557
1558 if (SrcType == DestType) {
1559 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1560 // restrictions, a cast to the same type is allowed. The intent is not
1561 // entirely clear here, since all other paragraphs explicitly forbid casts
1562 // to the same type. However, the behavior of compilers is pretty consistent
1563 // on this point: allow same-type conversion if the involved types are
1564 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001565 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001566 return TC_Success;
1567 }
1568
Douglas Gregor6972a622010-06-16 00:35:25 +00001569 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001570 assert(srcIsPtr && "One type must be a pointer");
1571 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001572 // type large enough to hold it; except in Microsoft mode, where the
1573 // integral type size doesn't matter.
1574 if ((Self.Context.getTypeSize(SrcType) >
1575 Self.Context.getTypeSize(DestType)) &&
Francois Pichet0706d202011-09-17 17:15:52 +00001576 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001577 msg = diag::err_bad_reinterpret_cast_small_int;
1578 return TC_Failed;
1579 }
John McCalle3027922010-08-25 11:45:40 +00001580 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001581 return TC_Success;
1582 }
1583
Douglas Gregorb90df602010-06-16 00:17:44 +00001584 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001585 assert(destIsPtr && "One type must be a pointer");
1586 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1587 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001588 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1589 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001590 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001591 return TC_Success;
1592 }
1593
1594 if (!destIsPtr || !srcIsPtr) {
1595 // With the valid non-pointer conversions out of the way, we can be even
1596 // more stringent.
1597 return TC_NotApplicable;
1598 }
1599
1600 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1601 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001602 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1603 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001604 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001605 return TC_Failed;
1606 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001607
1608 // Cannot convert between block pointers and Objective-C object pointers.
1609 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1610 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1611 return TC_NotApplicable;
1612
John McCall9320b872011-09-09 05:25:32 +00001613 if (IsLValueCast) {
1614 Kind = CK_LValueBitCast;
1615 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001616 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001617 } else if (DestType->isBlockPointerType()) {
1618 if (!SrcType->isBlockPointerType()) {
1619 Kind = CK_AnyPointerToBlockPointerCast;
1620 } else {
1621 Kind = CK_BitCast;
1622 }
1623 } else {
1624 Kind = CK_BitCast;
1625 }
1626
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001627 // Any pointer can be cast to an Objective-C pointer type with a C-style
1628 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001629 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001630 return TC_Success;
1631 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001632
Sebastian Redl9f831db2009-07-25 15:41:38 +00001633 // Not casting away constness, so the only remaining check is for compatible
1634 // pointer categories.
1635
1636 if (SrcType->isFunctionPointerType()) {
1637 if (DestType->isFunctionPointerType()) {
1638 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1639 // a pointer to a function of a different type.
1640 return TC_Success;
1641 }
1642
1643 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1644 // an object type or vice versa is conditionally-supported.
1645 // Compilers support it in C++03 too, though, because it's necessary for
1646 // casting the return value of dlsym() and GetProcAddress().
1647 // FIXME: Conditionally-supported behavior should be configurable in the
1648 // TargetInfo or similar.
1649 if (!Self.getLangOptions().CPlusPlus0x)
1650 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1651 return TC_Success;
1652 }
1653
1654 if (DestType->isFunctionPointerType()) {
1655 // See above.
1656 if (!Self.getLangOptions().CPlusPlus0x)
1657 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1658 return TC_Success;
1659 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001660
Sebastian Redl9f831db2009-07-25 15:41:38 +00001661 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1662 // a pointer to an object of different type.
1663 // Void pointers are not specified, but supported by every compiler out there.
1664 // So we finish by allowing everything that remains - it's got to be two
1665 // object pointers.
1666 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001667}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001668
John McCallb50451a2011-10-05 07:41:44 +00001669void CastOperation::CheckCStyleCast(bool FunctionalStyle) {
1670 // Check for casts from __unknown_any before anything else.
1671 if (SrcExpr.get()->getType() == Self.Context.UnknownAnyTy) {
1672 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1673 SrcExpr.get(), Kind,
1674 ValueKind, BasePath);
1675 return;
1676 }
1677
Sebastian Redl9f831db2009-07-25 15:41:38 +00001678 // This test is outside everything else because it's the only case where
1679 // a non-lvalue-reference target type does not lead to decay.
1680 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
John McCallb50451a2011-10-05 07:41:44 +00001681 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00001682 Kind = CK_ToVoid;
1683
John McCallb50451a2011-10-05 07:41:44 +00001684 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1685 if (SrcExpr.isInvalid())
1686 return;
John McCall3aef3d82011-04-10 19:13:55 +00001687
John McCallb50451a2011-10-05 07:41:44 +00001688 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1689 SrcExpr = Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1690 SrcExpr.take(), /* Decay Function to ptr */ false,
1691 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00001692 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00001693 if (SrcExpr.isInvalid())
1694 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001695 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001696
John McCallb50451a2011-10-05 07:41:44 +00001697 if (SrcExpr.get()->getType() == Self.Context.BoundMemberTy) {
1698 Self.CheckPlaceholderExpr(SrcExpr.take()); // will always fail
1699 return;
1700 }
John McCall3aef3d82011-04-10 19:13:55 +00001701
John McCallb50451a2011-10-05 07:41:44 +00001702 assert(!SrcExpr.get()->getType()->isPlaceholderType());
1703
1704 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00001705 }
1706
Sebastian Redl9f831db2009-07-25 15:41:38 +00001707 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb50451a2011-10-05 07:41:44 +00001708 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1709 assert(Kind == CK_Dependent);
1710 return;
John McCall8cb679e2010-11-15 09:13:47 +00001711 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00001712
John McCallb50451a2011-10-05 07:41:44 +00001713 if (ValueKind == VK_RValue && !DestType->isRecordType()) {
1714 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1715 if (SrcExpr.isInvalid())
1716 return;
John Wiegley01296292011-04-08 18:41:53 +00001717 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001718
John McCall3aef3d82011-04-10 19:13:55 +00001719 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00001720 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00001721 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00001722 && (SrcExpr.get()->getType()->isIntegerType()
1723 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00001724 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00001725 return;
John McCall3aef3d82011-04-10 19:13:55 +00001726 }
1727
Sebastian Redl9f831db2009-07-25 15:41:38 +00001728 // C++ [expr.cast]p5: The conversions performed by
1729 // - a const_cast,
1730 // - a static_cast,
1731 // - a static_cast followed by a const_cast,
1732 // - a reinterpret_cast, or
1733 // - a reinterpret_cast followed by a const_cast,
1734 // can be performed using the cast notation of explicit type conversion.
1735 // [...] If a conversion can be interpreted in more than one of the ways
1736 // listed above, the interpretation that appears first in the list is used,
1737 // even if a cast resulting from that interpretation is ill-formed.
1738 // In plain language, this means trying a const_cast ...
1739 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb50451a2011-10-05 07:41:44 +00001740 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1741 /*CStyle*/true, msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001742 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001743 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001744
John McCall31168b02011-06-15 23:02:42 +00001745 Sema::CheckedConversionKind CCK
1746 = FunctionalStyle? Sema::CCK_FunctionalCast
1747 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001748 if (tcr == TC_NotApplicable) {
1749 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00001750 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1751 msg, Kind, BasePath);
1752 if (SrcExpr.isInvalid())
1753 return;
1754
Sebastian Redl9f831db2009-07-25 15:41:38 +00001755 if (tcr == TC_NotApplicable) {
1756 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00001757 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1758 OpRange, msg, Kind);
1759 if (SrcExpr.isInvalid())
1760 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001761 }
1762 }
1763
John McCallb50451a2011-10-05 07:41:44 +00001764 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1765 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00001766
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001767 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00001768 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001769 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00001770 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1771 DestType,
1772 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001773 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001774
Richard Trieu70d14f52011-04-16 01:09:30 +00001775 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001776 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001777
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001778 } else {
John McCallb50451a2011-10-05 07:41:44 +00001779 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1780 OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001781 }
John McCallb50451a2011-10-05 07:41:44 +00001782 } else if (Kind == CK_BitCast) {
1783 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001784 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001785
John McCallb50451a2011-10-05 07:41:44 +00001786 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00001787 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00001788 SrcExpr = ExprError();
1789}
1790
1791ExprResult Sema::CXXBuildCStyleCastExpr(SourceLocation LPLoc,
1792 TypeSourceInfo *CastTypeInfo,
1793 SourceLocation RPLoc,
1794 Expr *CastExpr) {
1795 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
1796 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
1797 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
1798
1799 Op.CheckCStyleCast(/*FunctionalStyle=*/ false);
1800 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001801 return ExprError();
1802
John McCallb50451a2011-10-05 07:41:44 +00001803 return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
1804 Op.Kind, Op.SrcExpr.take(), &Op.BasePath,
1805 CastTypeInfo, LPLoc, RPLoc));
1806}
1807
1808ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
1809 SourceLocation LPLoc,
1810 Expr *CastExpr,
1811 SourceLocation RPLoc) {
1812 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
1813 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
1814 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
1815
1816 Op.CheckCStyleCast(/*FunctionalStyle=*/ true);
1817 if (Op.SrcExpr.isInvalid())
1818 return ExprError();
1819
1820 return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
1821 Op.ValueKind, CastTypeInfo,
1822 Op.DestRange.getBegin(),
1823 Op.Kind, Op.SrcExpr.take(),
1824 &Op.BasePath, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00001825}