blob: 1f386388bef3494a91e9ec7fedb01d2658dc9f9e [file] [log] [blame]
John McCall9776e432011-10-06 23:25:11 +00001//===--- SemaCXXCast.cpp - Semantic Analysis for Casts --------------------===//
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00002//
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//
John McCall9776e432011-10-06 23:25:11 +000010// This file implements semantic analysis for casts.
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000011//
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"
John McCall9776e432011-10-06 23:25:11 +000017#include "clang/AST/ExprObjC.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000020#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000021#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000022#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000023using namespace clang;
24
Douglas Gregore81f58e2010-11-08 03:40:48 +000025
Douglas Gregore81f58e2010-11-08 03:40:48 +000026
Sebastian Redl9f831db2009-07-25 15:41:38 +000027enum TryCastResult {
28 TC_NotApplicable, ///< The cast method is not applicable.
29 TC_Success, ///< The cast method is appropriate and successful.
30 TC_Failed ///< The cast method is appropriate, but failed. A
31 ///< diagnostic has been emitted.
32};
33
34enum CastType {
35 CT_Const, ///< const_cast
36 CT_Static, ///< static_cast
37 CT_Reinterpret, ///< reinterpret_cast
38 CT_Dynamic, ///< dynamic_cast
39 CT_CStyle, ///< (Type)expr
40 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000041};
42
John McCallb50451a2011-10-05 07:41:44 +000043namespace {
44 struct CastOperation {
45 CastOperation(Sema &S, QualType destType, ExprResult src)
46 : Self(S), SrcExpr(src), DestType(destType),
47 ResultType(destType.getNonLValueExprType(S.Context)),
48 ValueKind(Expr::getValueKindForType(destType)),
John McCall9776e432011-10-06 23:25:11 +000049 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
50
51 if (const BuiltinType *placeholder =
52 src.get()->getType()->getAsPlaceholderType()) {
53 PlaceholderKind = placeholder->getKind();
54 } else {
55 PlaceholderKind = (BuiltinType::Kind) 0;
56 }
57 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000058
John McCallb50451a2011-10-05 07:41:44 +000059 Sema &Self;
60 ExprResult SrcExpr;
61 QualType DestType;
62 QualType ResultType;
63 ExprValueKind ValueKind;
64 CastKind Kind;
65 bool IsARCUnbridgedCast;
John McCall9776e432011-10-06 23:25:11 +000066 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000067 CXXCastPath BasePath;
Douglas Gregore81f58e2010-11-08 03:40:48 +000068
John McCallb50451a2011-10-05 07:41:44 +000069 SourceRange OpRange;
70 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000071
John McCall9776e432011-10-06 23:25:11 +000072 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000073 void CheckConstCast();
74 void CheckReinterpretCast();
75 void CheckStaticCast();
76 void CheckDynamicCast();
John McCall9776e432011-10-06 23:25:11 +000077 void CheckCXXCStyleCast(bool FunctionalCast);
78 void CheckCStyleCast();
79
80 // Internal convenience methods.
81
82 /// Try to handle the given placeholder expression kind. Return
83 /// true if the source expression has the appropriate placeholder
84 /// kind. A placeholder can only be claimed once.
85 bool claimPlaceholder(BuiltinType::Kind K) {
86 if (PlaceholderKind != K) return false;
87
88 PlaceholderKind = (BuiltinType::Kind) 0;
89 return true;
90 }
91
92 bool isPlaceholder() const {
93 return PlaceholderKind != 0;
94 }
95 bool isPlaceholder(BuiltinType::Kind K) const {
96 return PlaceholderKind == K;
97 }
John McCallb50451a2011-10-05 07:41:44 +000098
99 void checkCastAlign() {
100 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
101 }
102
103 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
104 Expr *src = SrcExpr.get();
105 Self.CheckObjCARCConversion(OpRange, DestType, src, CCK);
106 SrcExpr = src;
107 }
John McCall9776e432011-10-06 23:25:11 +0000108
109 /// Check for and handle non-overload placeholder expressions.
110 void checkNonOverloadPlaceholders() {
111 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
112 return;
113
114 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
115 if (SrcExpr.isInvalid())
116 return;
117 PlaceholderKind = (BuiltinType::Kind) 0;
118 }
John McCallb50451a2011-10-05 07:41:44 +0000119 };
120}
Sebastian Redl842ef522008-11-08 13:00:26 +0000121
John McCall31168b02011-06-15 23:02:42 +0000122static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
123 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000124
125// The Try functions attempt a specific way of casting. If they succeed, they
126// return TC_Success. If their way of casting is not appropriate for the given
127// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
128// to emit if no other way succeeds. If their way of casting is appropriate but
129// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
130// they emit a specialized diagnostic.
131// All diagnostics returned by these functions must expect the same three
132// arguments:
133// %0: Cast Type (a value from the CastType enumeration)
134// %1: Source Type
135// %2: Destination Type
136static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000137 QualType DestType, bool CStyle,
138 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000139 CXXCastPath &BasePath,
140 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000141static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000142 QualType DestType, bool CStyle,
143 const SourceRange &OpRange,
144 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000145 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000146 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000147static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
148 QualType DestType, bool CStyle,
149 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000150 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000151 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000152 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000153static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
154 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000155 const SourceRange &OpRange,
156 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000157 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000158 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000159 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000160static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000161 QualType SrcType,
162 QualType DestType,bool CStyle,
163 const SourceRange &OpRange,
164 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000165 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000166 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000167
John Wiegley01296292011-04-08 18:41:53 +0000168static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000169 QualType DestType,
170 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000171 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000172 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000173 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +0000174static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000175 QualType DestType,
176 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000177 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000178 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000179 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000180 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000181static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
182 bool CStyle, unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000183static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000184 QualType DestType, bool CStyle,
185 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000186 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000187 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000188
Douglas Gregorb491ed32011-02-19 21:32:49 +0000189
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000190/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000191ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000192Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000193 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000194 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000195 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000196 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000197
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000198 assert(!D.isInvalidType());
199
200 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
201 if (D.isInvalidType())
202 return ExprError();
203
204 if (getLangOptions().CPlusPlus) {
205 // Check that there are no default arguments (C++ only).
206 CheckExtraCXXDefaultArguments(D);
207 }
208
209 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
John McCalld377e042010-01-15 19:13:16 +0000210 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
211 SourceRange(LParenLoc, RParenLoc));
212}
213
John McCalldadc5752010-08-24 06:29:42 +0000214ExprResult
John McCalld377e042010-01-15 19:13:16 +0000215Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000216 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000217 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000218 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000219 QualType DestType = DestTInfo->getType();
220
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000221 // If the type is dependent, we won't do the semantic analysis now.
222 // FIXME: should we check this in a more fine-grained manner?
John Wiegley01296292011-04-08 18:41:53 +0000223 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000224
John McCallb50451a2011-10-05 07:41:44 +0000225 CastOperation Op(*this, DestType, E);
226 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
227 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000228
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000229 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000230 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000231
232 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000233 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000234 Op.CheckConstCast();
235 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000236 return ExprError();
237 }
John McCallb50451a2011-10-05 07:41:44 +0000238 return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
239 Op.SrcExpr.take(), DestTInfo, OpLoc,
Douglas Gregor4478f852011-01-12 22:41:29 +0000240 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000241
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000242 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000243 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000244 Op.CheckDynamicCast();
245 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000246 return ExprError();
247 }
John McCallb50451a2011-10-05 07:41:44 +0000248 return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType,
249 Op.ValueKind, Op.Kind,
250 Op.SrcExpr.take(), &Op.BasePath,
251 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000252 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000253 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000254 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000255 Op.CheckReinterpretCast();
256 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000257 return ExprError();
258 }
John McCallb50451a2011-10-05 07:41:44 +0000259 return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
260 Op.ValueKind, Op.Kind,
261 Op.SrcExpr.take(), 0,
262 DestTInfo, OpLoc,
263 Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000264 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000265 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000266 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000267 Op.CheckStaticCast();
268 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000269 return ExprError();
270 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000271
John McCallb50451a2011-10-05 07:41:44 +0000272 return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
273 Op.Kind, Op.SrcExpr.take(),
274 &Op.BasePath, DestTInfo, OpLoc,
275 Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000276 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000277 }
278
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000279 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000280}
281
John McCall909acf82011-02-14 18:34:10 +0000282/// Try to diagnose a failed overloaded cast. Returns true if
283/// diagnostics were emitted.
284static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
285 SourceRange range, Expr *src,
286 QualType destType) {
287 switch (CT) {
288 // These cast kinds don't consider user-defined conversions.
289 case CT_Const:
290 case CT_Reinterpret:
291 case CT_Dynamic:
292 return false;
293
294 // These do.
295 case CT_Static:
296 case CT_CStyle:
297 case CT_Functional:
298 break;
299 }
300
301 QualType srcType = src->getType();
302 if (!destType->isRecordType() && !srcType->isRecordType())
303 return false;
304
305 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
306 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000307 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
308 range)
309 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
310 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall909acf82011-02-14 18:34:10 +0000311 InitializationSequence sequence(S, entity, initKind, &src, 1);
312
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000313 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000314 switch (sequence.getFailureKind()) {
315 default: return false;
316
317 case InitializationSequence::FK_ConstructorOverloadFailed:
318 case InitializationSequence::FK_UserConversionOverloadFailed:
319 break;
320 }
321
322 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
323
324 unsigned msg = 0;
325 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
326
327 switch (sequence.getFailedOverloadResult()) {
328 case OR_Success: llvm_unreachable("successful failed overload");
329 return false;
330 case OR_No_Viable_Function:
331 if (candidates.empty())
332 msg = diag::err_ovl_no_conversion_in_cast;
333 else
334 msg = diag::err_ovl_no_viable_conversion_in_cast;
335 howManyCandidates = OCD_AllCandidates;
336 break;
337
338 case OR_Ambiguous:
339 msg = diag::err_ovl_ambiguous_conversion_in_cast;
340 howManyCandidates = OCD_ViableCandidates;
341 break;
342
343 case OR_Deleted:
344 msg = diag::err_ovl_deleted_conversion_in_cast;
345 howManyCandidates = OCD_ViableCandidates;
346 break;
347 }
348
349 S.Diag(range.getBegin(), msg)
350 << CT << srcType << destType
351 << range << src->getSourceRange();
352
353 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
354
355 return true;
356}
357
358/// Diagnose a failed cast.
359static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
360 SourceRange opRange, Expr *src, QualType destType) {
John McCall0009fcc2011-04-26 20:42:42 +0000361 if (src->getType() == S.Context.BoundMemberTy) {
362 (void) S.CheckPlaceholderExpr(src); // will always fail
363 return;
364 }
365
John McCall909acf82011-02-14 18:34:10 +0000366 if (msg == diag::err_bad_cxx_cast_generic &&
367 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
368 return;
369
370 S.Diag(opRange.getBegin(), msg) << castType
371 << src->getType() << destType << opRange << src->getSourceRange();
372}
373
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000374/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
375/// this removes one level of indirection from both types, provided that they're
376/// the same kind of pointer (plain or to-member). Unlike the Sema function,
377/// this one doesn't care if the two pointers-to-member don't point into the
378/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000379static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000380 const PointerType *T1PtrType = T1->getAs<PointerType>(),
381 *T2PtrType = T2->getAs<PointerType>();
382 if (T1PtrType && T2PtrType) {
383 T1 = T1PtrType->getPointeeType();
384 T2 = T2PtrType->getPointeeType();
385 return true;
386 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000387 const ObjCObjectPointerType *T1ObjCPtrType =
388 T1->getAs<ObjCObjectPointerType>(),
389 *T2ObjCPtrType =
390 T2->getAs<ObjCObjectPointerType>();
391 if (T1ObjCPtrType) {
392 if (T2ObjCPtrType) {
393 T1 = T1ObjCPtrType->getPointeeType();
394 T2 = T2ObjCPtrType->getPointeeType();
395 return true;
396 }
397 else if (T2PtrType) {
398 T1 = T1ObjCPtrType->getPointeeType();
399 T2 = T2PtrType->getPointeeType();
400 return true;
401 }
402 }
403 else if (T2ObjCPtrType) {
404 if (T1PtrType) {
405 T2 = T2ObjCPtrType->getPointeeType();
406 T1 = T1PtrType->getPointeeType();
407 return true;
408 }
409 }
410
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000411 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
412 *T2MPType = T2->getAs<MemberPointerType>();
413 if (T1MPType && T2MPType) {
414 T1 = T1MPType->getPointeeType();
415 T2 = T2MPType->getPointeeType();
416 return true;
417 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000418
419 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
420 *T2BPType = T2->getAs<BlockPointerType>();
421 if (T1BPType && T2BPType) {
422 T1 = T1BPType->getPointeeType();
423 T2 = T2BPType->getPointeeType();
424 return true;
425 }
426
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000427 return false;
428}
429
Sebastian Redla5a77a62009-01-27 23:18:31 +0000430/// CastsAwayConstness - Check if the pointer conversion from SrcType to
431/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
432/// the cast checkers. Both arguments must denote pointer (possibly to member)
433/// types.
John McCall31168b02011-06-15 23:02:42 +0000434///
435/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
436///
437/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000438static bool
John McCall31168b02011-06-15 23:02:42 +0000439CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
440 bool CheckCVR, bool CheckObjCLifetime) {
441 // If the only checking we care about is for Objective-C lifetime qualifiers,
442 // and we're not in ARC mode, there's nothing to check.
443 if (!CheckCVR && CheckObjCLifetime &&
444 !Self.Context.getLangOptions().ObjCAutoRefCount)
445 return false;
446
Sebastian Redla5a77a62009-01-27 23:18:31 +0000447 // Casting away constness is defined in C++ 5.2.11p8 with reference to
448 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
449 // the rules are non-trivial. So first we construct Tcv *...cv* as described
450 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000451 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
452 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000453 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000454 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
455 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000456 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000457
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000458 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
459 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000460 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000461
Douglas Gregorb472e932011-04-15 17:59:54 +0000462 // Find the qualifiers. We only care about cvr-qualifiers for the
463 // purpose of this check, because other qualifiers (address spaces,
464 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000465 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000466 // Determine the relevant qualifiers at this level.
467 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000468 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000469 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000470
471 Qualifiers RetainedSrcQuals, RetainedDestQuals;
472 if (CheckCVR) {
473 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
474 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
475 }
476
477 if (CheckObjCLifetime &&
478 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
479 return true;
480
481 cv1.push_back(RetainedSrcQuals);
482 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000483 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000484 if (cv1.empty())
485 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000486
487 // Construct void pointers with those qualifiers (in reverse order of
488 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000489 QualType SrcConstruct = Self.Context.VoidTy;
490 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000491 ASTContext &Context = Self.Context;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall8ccfcb52009-09-24 19:53:00 +0000493 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000494 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000495 SrcConstruct
496 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
497 DestConstruct
498 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000499 }
500
501 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000502 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000503 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000504 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
505 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000506}
507
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000508/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
509/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
510/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000511void CastOperation::CheckDynamicCast() {
512 QualType OrigSrcType = SrcExpr.get()->getType();
513 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000514
515 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
516 // or "pointer to cv void".
517
518 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000519 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000520 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000521 if (DestPointer) {
522 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000523 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000524 DestPointee = DestReference->getPointeeType();
525 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000526 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000527 << this->DestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000528 return;
529 }
530
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000531 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000532 if (DestPointee->isVoidType()) {
533 assert(DestPointer && "Reference to void is not possible");
534 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000535 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000536 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000537 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000538 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000539 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000540 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000541 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000542 return;
543 }
544
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000545 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
546 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000547 // an lvalue of a complete class type, [...]. If T is an rvalue reference
548 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000549 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000550 QualType SrcPointee;
551 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000552 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000553 SrcPointee = SrcPointer->getPointeeType();
554 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000555 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000556 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000557 return;
558 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000559 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000560 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000561 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000562 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000563 }
564 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000565 } else {
566 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000567 }
568
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000569 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000570 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000571 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000572 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley01296292011-04-08 18:41:53 +0000573 << SrcExpr.get()->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000574 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000575 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000576 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000577 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000578 return;
579 }
580
581 assert((DestPointer || DestReference) &&
582 "Bad destination non-ptr/ref slipped through.");
583 assert((DestRecord || DestPointee->isVoidType()) &&
584 "Bad destination pointee slipped through.");
585 assert(SrcRecord && "Bad source pointee slipped through.");
586
587 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
588 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000589 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000590 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000591 return;
592 }
593
594 // C++ 5.2.7p3: If the type of v is the same as the required result type,
595 // [except for cv].
596 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000597 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000598 return;
599 }
600
601 // C++ 5.2.7p5
602 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000603 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000604 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
605 OpRange.getBegin(), OpRange,
606 &BasePath))
607 return;
608
John McCalle3027922010-08-25 11:45:40 +0000609 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000610
611 // If we are casting to or through a virtual base class, we need a
612 // vtable.
613 if (Self.BasePathInvolvesVirtualBase(BasePath))
614 Self.MarkVTableUsed(OpRange.getBegin(),
615 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000616 return;
617 }
618
619 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000620 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000621 assert(SrcDecl && "Definition missing");
622 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000623 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000624 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000625 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000626 Self.MarkVTableUsed(OpRange.getBegin(),
627 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000628
629 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000630 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000631}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000632
633/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
634/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
635/// like this:
636/// const char *str = "literal";
637/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000638void CastOperation::CheckConstCast() {
639 if (ValueKind == VK_RValue) {
John Wiegley01296292011-04-08 18:41:53 +0000640 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
641 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
642 return;
643 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000644
645 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley01296292011-04-08 18:41:53 +0000646 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9f831db2009-07-25 15:41:38 +0000647 && msg != 0)
648 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000649 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000650}
651
652/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
653/// valid.
654/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
655/// like this:
656/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000657void CastOperation::CheckReinterpretCast() {
658 if (ValueKind == VK_RValue) {
John Wiegley01296292011-04-08 18:41:53 +0000659 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
660 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
661 return;
662 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000663
664 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000665 TryCastResult tcr =
666 TryReinterpretCast(Self, SrcExpr, DestType,
667 /*CStyle*/false, OpRange, msg, Kind);
668 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000669 {
John Wiegley01296292011-04-08 18:41:53 +0000670 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
671 return;
672 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000673 //FIXME: &f<int>; is overloaded and resolvable
674 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000675 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000676 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000677 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000678
John McCall909acf82011-02-14 18:34:10 +0000679 } else {
John Wiegley01296292011-04-08 18:41:53 +0000680 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000681 }
John McCall31168b02011-06-15 23:02:42 +0000682 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb50451a2011-10-05 07:41:44 +0000683 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCall31168b02011-06-15 23:02:42 +0000684 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000685}
686
687
688/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
689/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
690/// implicit conversions explicit and getting rid of data loss warnings.
John McCallb50451a2011-10-05 07:41:44 +0000691void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000692 if (isPlaceholder()) {
693 checkNonOverloadPlaceholders();
694 if (SrcExpr.isInvalid())
695 return;
696 }
697
Sebastian Redl9f831db2009-07-25 15:41:38 +0000698 // This test is outside everything else because it's the only case where
699 // a non-lvalue-reference target type does not lead to decay.
700 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000701 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000702 Kind = CK_ToVoid;
703
704 if (claimPlaceholder(BuiltinType::Overload)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +0000705 ExprResult SingleFunctionExpression =
John McCall9776e432011-10-06 23:25:11 +0000706 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +0000707 false, // Decay Function to ptr
708 true, // Complain
709 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall9776e432011-10-06 23:25:11 +0000710 if (SingleFunctionExpression.isUsable())
711 SrcExpr = SingleFunctionExpression;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000712 }
John McCall9776e432011-10-06 23:25:11 +0000713
714 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000715 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000716 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000717
John McCallb50451a2011-10-05 07:41:44 +0000718 if (ValueKind == VK_RValue && !DestType->isRecordType()) {
John Wiegley01296292011-04-08 18:41:53 +0000719 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
720 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
721 return;
722 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000723
724 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000725 TryCastResult tcr
726 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
727 Kind, BasePath);
728 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000729 if (SrcExpr.isInvalid())
730 return;
731 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
732 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000733 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000734 << oe->getName() << DestType << OpRange
735 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000736 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000737 } else {
John Wiegley01296292011-04-08 18:41:53 +0000738 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000739 }
John McCall31168b02011-06-15 23:02:42 +0000740 } else if (tcr == TC_Success) {
741 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000742 checkCastAlign();
743 if (Self.getLangOptions().ObjCAutoRefCount)
744 checkObjCARCConversion(Sema::CCK_OtherCast);
745 } else if (Kind == CK_BitCast) {
746 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000747 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000748}
749
750/// TryStaticCast - Check if a static cast can be performed, and do so if
751/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
752/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000753static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000754 QualType DestType,
755 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000756 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000757 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000758 CXXCastPath &BasePath) {
John McCall31168b02011-06-15 23:02:42 +0000759 // Determine whether we have the semantics of a C-style cast.
760 bool CStyle
761 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
762
Sebastian Redl9f831db2009-07-25 15:41:38 +0000763 // The order the tests is not entirely arbitrary. There is one conversion
764 // that can be handled in two different ways. Given:
765 // struct A {};
766 // struct B : public A {
767 // B(); B(const A&);
768 // };
769 // const A &a = B();
770 // the cast static_cast<const B&>(a) could be seen as either a static
771 // reference downcast, or an explicit invocation of the user-defined
772 // conversion using B's conversion constructor.
773 // DR 427 specifies that the downcast is to be applied here.
774
775 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
776 // Done outside this function.
777
778 TryCastResult tcr;
779
780 // C++ 5.2.9p5, reference downcast.
781 // See the function for details.
782 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley01296292011-04-08 18:41:53 +0000783 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000784 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000785 if (tcr != TC_NotApplicable)
786 return tcr;
787
Douglas Gregor465184a2011-01-22 00:06:57 +0000788 // C++0x [expr.static.cast]p3:
789 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
790 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley01296292011-04-08 18:41:53 +0000791 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregorce950842011-01-26 21:04:06 +0000792 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000793 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000794 return tcr;
795
796 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
797 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000798 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000799 Kind);
John Wiegley01296292011-04-08 18:41:53 +0000800 if (SrcExpr.isInvalid())
801 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000802 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000803 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000804
Sebastian Redl9f831db2009-07-25 15:41:38 +0000805 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
806 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
807 // conversions, subject to further restrictions.
808 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
809 // of qualification conversions impossible.
810 // In the CStyle case, the earlier attempt to const_cast should have taken
811 // care of reverse qualification conversions.
812
John Wiegley01296292011-04-08 18:41:53 +0000813 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000814
Douglas Gregor0bf31402010-10-08 23:50:27 +0000815 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000816 // converted to an integral type. [...] A value of a scoped enumeration type
817 // can also be explicitly converted to a floating-point type [...].
818 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
819 if (Enum->getDecl()->isScoped()) {
820 if (DestType->isBooleanType()) {
821 Kind = CK_IntegralToBoolean;
822 return TC_Success;
823 } else if (DestType->isIntegralType(Self.Context)) {
824 Kind = CK_IntegralCast;
825 return TC_Success;
826 } else if (DestType->isRealFloatingType()) {
827 Kind = CK_IntegralToFloating;
828 return TC_Success;
829 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000830 }
831 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000832
Sebastian Redl9f831db2009-07-25 15:41:38 +0000833 // Reverse integral promotion/conversion. All such conversions are themselves
834 // again integral promotions or conversions and are thus already handled by
835 // p2 (TryDirectInitialization above).
836 // (Note: any data loss warnings should be suppressed.)
837 // The exception is the reverse of enum->integer, i.e. integer->enum (and
838 // enum->enum). See also C++ 5.2.9p7.
839 // The same goes for reverse floating point promotion/conversion and
840 // floating-integral conversions. Again, only floating->enum is relevant.
841 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +0000842 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +0000843 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000844 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +0000845 } else if (SrcType->isRealFloatingType()) {
846 Kind = CK_FloatingToIntegral;
847 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000848 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000849 }
850
851 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
852 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000853 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000854 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000855 if (tcr != TC_NotApplicable)
856 return tcr;
857
858 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
859 // conversion. C++ 5.2.9p9 has additional information.
860 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000861 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000862 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000863 if (tcr != TC_NotApplicable)
864 return tcr;
865
866 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
867 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
868 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000869 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000870 QualType SrcPointee = SrcPointer->getPointeeType();
871 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000872 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000873 QualType DestPointee = DestPointer->getPointeeType();
874 if (DestPointee->isIncompleteOrObjectType()) {
875 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +0000876 // to a qualifier violation. Note that we permit Objective-C lifetime
877 // and GC qualifier mismatches here.
878 if (!CStyle) {
879 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
880 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
881 DestPointeeQuals.removeObjCGCAttr();
882 DestPointeeQuals.removeObjCLifetime();
883 SrcPointeeQuals.removeObjCGCAttr();
884 SrcPointeeQuals.removeObjCLifetime();
885 if (DestPointeeQuals != SrcPointeeQuals &&
886 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
887 msg = diag::err_bad_cxx_cast_qualifiers_away;
888 return TC_Failed;
889 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000890 }
John McCalle3027922010-08-25 11:45:40 +0000891 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000892 return TC_Success;
893 }
894 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000895 else if (DestType->isObjCObjectPointerType()) {
896 // allow both c-style cast and static_cast of objective-c pointers as
897 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +0000898 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000899 return TC_Success;
900 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000901 else if (CStyle && DestType->isBlockPointerType()) {
902 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000903 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000904 return TC_Success;
905 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000906 }
907 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000908 // Allow arbitray objective-c pointer conversion with static casts.
909 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000910 DestType->isObjCObjectPointerType()) {
911 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000912 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000913 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000914
Sebastian Redl9f831db2009-07-25 15:41:38 +0000915 // We tried everything. Everything! Nothing works! :-(
916 return TC_NotApplicable;
917}
918
919/// Tests whether a conversion according to N2844 is valid.
920TryCastResult
921TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000922 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
923 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000924 // C++0x [expr.static.cast]p3:
925 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
926 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000927 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000928 if (!R)
929 return TC_NotApplicable;
930
Douglas Gregor465184a2011-01-22 00:06:57 +0000931 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000932 return TC_NotApplicable;
933
934 // Because we try the reference downcast before this function, from now on
935 // this is the only cast possibility, so we issue an error if we fail now.
936 // FIXME: Should allow casting away constness if CStyle.
937 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000938 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +0000939 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000940 QualType FromType = SrcExpr->getType();
941 QualType ToType = R->getPointeeType();
942 if (CStyle) {
943 FromType = FromType.getUnqualifiedType();
944 ToType = ToType.getUnqualifiedType();
945 }
946
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000947 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000948 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +0000949 DerivedToBase, ObjCConversion,
950 ObjCLifetimeConversion)
951 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000952 msg = diag::err_bad_lvalue_to_rvalue_cast;
953 return TC_Failed;
954 }
955
Douglas Gregorba278e22011-01-25 16:13:26 +0000956 if (DerivedToBase) {
957 Kind = CK_DerivedToBase;
958 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
959 /*DetectVirtual=*/true);
960 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
961 return TC_NotApplicable;
962
963 Self.BuildBasePathArray(Paths, BasePath);
964 } else
965 Kind = CK_NoOp;
966
Sebastian Redl9f831db2009-07-25 15:41:38 +0000967 return TC_Success;
968}
969
970/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
971TryCastResult
972TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
973 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000974 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000975 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000976 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
977 // cast to type "reference to cv2 D", where D is a class derived from B,
978 // if a valid standard conversion from "pointer to D" to "pointer to B"
979 // exists, cv2 >= cv1, and B is not a virtual base class of D.
980 // In addition, DR54 clarifies that the base must be accessible in the
981 // current context. Although the wording of DR54 only applies to the pointer
982 // variant of this rule, the intent is clearly for it to apply to the this
983 // conversion as well.
984
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000985 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000986 if (!DestReference) {
987 return TC_NotApplicable;
988 }
989 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000990 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000991 // We know the left side is an lvalue reference, so we can suggest a reason.
992 msg = diag::err_bad_cxx_cast_rvalue;
993 return TC_NotApplicable;
994 }
995
996 QualType DestPointee = DestReference->getPointeeType();
997
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000998 return TryStaticDowncast(Self,
999 Self.Context.getCanonicalType(SrcExpr->getType()),
1000 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001001 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1002 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001003}
1004
1005/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1006TryCastResult
1007TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001008 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001009 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001010 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001011 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1012 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1013 // is a class derived from B, if a valid standard conversion from "pointer
1014 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1015 // class of D.
1016 // In addition, DR54 clarifies that the base must be accessible in the
1017 // current context.
1018
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001019 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001020 if (!DestPointer) {
1021 return TC_NotApplicable;
1022 }
1023
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001024 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 if (!SrcPointer) {
1026 msg = diag::err_bad_static_cast_pointer_nonpointer;
1027 return TC_NotApplicable;
1028 }
1029
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001030 return TryStaticDowncast(Self,
1031 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1032 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001033 CStyle, OpRange, SrcType, DestType, msg, Kind,
1034 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001035}
1036
1037/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1038/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001039/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001040TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001041TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001042 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001043 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001044 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001045 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +00001046 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1047 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001048 return TC_NotApplicable;
1049
Sebastian Redl9f831db2009-07-25 15:41:38 +00001050 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001051 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001052 return TC_NotApplicable;
1053 }
1054
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001055 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001056 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001057 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1058 return TC_NotApplicable;
1059 }
1060
1061 // Target type does derive from source type. Now we're serious. If an error
1062 // appears now, it's not ignored.
1063 // This may not be entirely in line with the standard. Take for example:
1064 // struct A {};
1065 // struct B : virtual A {
1066 // B(A&);
1067 // };
Mike Stump11289f42009-09-09 15:08:12 +00001068 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001069 // void f()
1070 // {
1071 // (void)static_cast<const B&>(*((A*)0));
1072 // }
1073 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1074 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1075 // However, both GCC and Comeau reject this example, and accepting it would
1076 // mean more complex code if we're to preserve the nice error message.
1077 // FIXME: Being 100% compliant here would be nice to have.
1078
1079 // Must preserve cv, as always, unless we're in C-style mode.
1080 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001081 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001082 return TC_Failed;
1083 }
1084
1085 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1086 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1087 // that it builds the paths in reverse order.
1088 // To sum up: record all paths to the base and build a nice string from
1089 // them. Use it to spice up the error message.
1090 if (!Paths.isRecordingPaths()) {
1091 Paths.clear();
1092 Paths.setRecordingPaths(true);
1093 Self.IsDerivedFrom(DestType, SrcType, Paths);
1094 }
1095 std::string PathDisplayStr;
1096 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001097 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001098 PI != PE; ++PI) {
1099 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1100 // We haven't displayed a path to this particular base
1101 // class subobject yet.
1102 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001103 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1104 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001105 EI != EE; ++EI)
1106 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001107 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001108 }
1109 }
1110
1111 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001112 << QualType(SrcType).getUnqualifiedType()
1113 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001114 << PathDisplayStr << OpRange;
1115 msg = 0;
1116 return TC_Failed;
1117 }
1118
1119 if (Paths.getDetectedVirtual() != 0) {
1120 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1121 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1122 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1123 msg = 0;
1124 return TC_Failed;
1125 }
1126
John McCallfe9cf0a2011-02-14 23:21:33 +00001127 if (!CStyle) {
1128 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1129 SrcType, DestType,
1130 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001131 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001132 case Sema::AR_accessible:
1133 case Sema::AR_delayed: // be optimistic
1134 case Sema::AR_dependent: // be optimistic
1135 break;
1136
1137 case Sema::AR_inaccessible:
1138 msg = 0;
1139 return TC_Failed;
1140 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001141 }
1142
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001143 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001144 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001145 return TC_Success;
1146}
1147
1148/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1149/// C++ 5.2.9p9 is valid:
1150///
1151/// An rvalue of type "pointer to member of D of type cv1 T" can be
1152/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1153/// where B is a base class of D [...].
1154///
1155TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001156TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001157 QualType DestType, bool CStyle,
1158 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001159 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001160 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001161 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001162 if (!DestMemPtr)
1163 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001164
1165 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001166 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001167 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001168 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001169 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001170 FoundOverload)) {
1171 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1172 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1173 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1174 WasOverloadedFunction = true;
1175 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001176 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001177
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001178 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001179 if (!SrcMemPtr) {
1180 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1181 return TC_NotApplicable;
1182 }
1183
1184 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001185 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1186 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001187 return TC_NotApplicable;
1188
1189 // B base of D
1190 QualType SrcClass(SrcMemPtr->getClass(), 0);
1191 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001192 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001193 /*DetectVirtual=*/true);
1194 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1195 return TC_NotApplicable;
1196 }
1197
1198 // 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 +00001199 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001200 Paths.clear();
1201 Paths.setRecordingPaths(true);
1202 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1203 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001204 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001205 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1206 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1207 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1208 msg = 0;
1209 return TC_Failed;
1210 }
1211
1212 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1213 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1214 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1215 msg = 0;
1216 return TC_Failed;
1217 }
1218
John McCallfe9cf0a2011-02-14 23:21:33 +00001219 if (!CStyle) {
1220 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1221 DestClass, SrcClass,
1222 Paths.front(),
1223 diag::err_upcast_to_inaccessible_base)) {
1224 case Sema::AR_accessible:
1225 case Sema::AR_delayed:
1226 case Sema::AR_dependent:
1227 // Optimistically assume that the delayed and dependent cases
1228 // will work out.
1229 break;
1230
1231 case Sema::AR_inaccessible:
1232 msg = 0;
1233 return TC_Failed;
1234 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001235 }
1236
Douglas Gregorc934bc82010-03-07 23:24:59 +00001237 if (WasOverloadedFunction) {
1238 // Resolve the address of the overloaded function again, this time
1239 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001240 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001241 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001242 true,
1243 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001244 if (!Fn) {
1245 msg = 0;
1246 return TC_Failed;
1247 }
1248
John McCall16df1e52010-03-30 21:47:33 +00001249 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001250 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001251 msg = 0;
1252 return TC_Failed;
1253 }
1254 }
1255
Anders Carlssonb78feca2010-04-24 19:22:20 +00001256 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001257 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001258 return TC_Success;
1259}
1260
1261/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1262/// is valid:
1263///
1264/// An expression e can be explicitly converted to a type T using a
1265/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1266TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001267TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001268 Sema::CheckedConversionKind CCK,
1269 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001270 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001271 if (DestType->isRecordType()) {
1272 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1273 diag::err_bad_dynamic_cast_incomplete)) {
1274 msg = 0;
1275 return TC_Failed;
1276 }
1277 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001278
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001279 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1280 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001281 = (CCK == Sema::CCK_CStyleCast)
1282 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1283 : (CCK == Sema::CCK_FunctionalCast)
1284 ? InitializationKind::CreateFunctionalCast(OpRange)
1285 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001286 Expr *SrcExprRaw = SrcExpr.get();
1287 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001288
1289 // At this point of CheckStaticCast, if the destination is a reference,
1290 // or the expression is an overload expression this has to work.
1291 // There is no other way that works.
1292 // On the other hand, if we're checking a C-style cast, we've still got
1293 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001294 bool CStyle
1295 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001296 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001297 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001298
John McCalldadc5752010-08-24 06:29:42 +00001299 ExprResult Result
John Wiegley01296292011-04-08 18:41:53 +00001300 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001301 if (Result.isInvalid()) {
1302 msg = 0;
1303 return TC_Failed;
1304 }
1305
Douglas Gregorb33eed02010-04-16 22:09:46 +00001306 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001307 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001308 else
John McCalle3027922010-08-25 11:45:40 +00001309 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001310
John Wiegley01296292011-04-08 18:41:53 +00001311 SrcExpr = move(Result);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001312 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001313}
1314
1315/// TryConstCast - See if a const_cast from source to destination is allowed,
1316/// and perform it if it is.
1317static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1318 bool CStyle, unsigned &msg) {
1319 DestType = Self.Context.getCanonicalType(DestType);
1320 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001321 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1322 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001323 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1324 // is C-style, static_cast might find a way, so we simply suggest a
1325 // message and tell the parent to keep searching.
1326 msg = diag::err_bad_cxx_cast_rvalue;
1327 return TC_NotApplicable;
1328 }
1329
1330 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1331 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1332 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1333 SrcType = Self.Context.getPointerType(SrcType);
1334 }
1335
1336 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1337 // the rules for const_cast are the same as those used for pointers.
1338
John McCall0e704f72010-05-18 09:35:29 +00001339 if (!DestType->isPointerType() &&
1340 !DestType->isMemberPointerType() &&
1341 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001342 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1343 // was a reference type, we converted it to a pointer above.
1344 // The status of rvalue references isn't entirely clear, but it looks like
1345 // conversion to them is simply invalid.
1346 // C++ 5.2.11p3: For two pointer types [...]
1347 if (!CStyle)
1348 msg = diag::err_bad_const_cast_dest;
1349 return TC_NotApplicable;
1350 }
1351 if (DestType->isFunctionPointerType() ||
1352 DestType->isMemberFunctionPointerType()) {
1353 // Cannot cast direct function pointers.
1354 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1355 // T is the ultimate pointee of source and target type.
1356 if (!CStyle)
1357 msg = diag::err_bad_const_cast_dest;
1358 return TC_NotApplicable;
1359 }
1360 SrcType = Self.Context.getCanonicalType(SrcType);
1361
1362 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1363 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001364 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1365 // in multi-level pointers may change, but the level count must be the same,
1366 // as must be the final pointee type.
1367 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001368 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001369 Qualifiers SrcQuals, DestQuals;
1370 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1371 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1372
1373 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1374 // the other qualifiers (e.g., address spaces) are identical.
1375 SrcQuals.removeCVRQualifiers();
1376 DestQuals.removeCVRQualifiers();
1377 if (SrcQuals != DestQuals)
1378 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001379 }
1380
1381 // Since we're dealing in canonical types, the remainder must be the same.
1382 if (SrcType != DestType)
1383 return TC_NotApplicable;
1384
1385 return TC_Success;
1386}
1387
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001388// Checks for undefined behavior in reinterpret_cast.
1389// The cases that is checked for is:
1390// *reinterpret_cast<T*>(&a)
1391// reinterpret_cast<T&>(a)
1392// where accessing 'a' as type 'T' will result in undefined behavior.
1393void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1394 bool IsDereference,
1395 SourceRange Range) {
1396 unsigned DiagID = IsDereference ?
1397 diag::warn_pointer_indirection_from_incompatible_type :
1398 diag::warn_undefined_reinterpret_cast;
1399
1400 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00001401 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001402 return;
1403 }
1404
1405 QualType SrcTy, DestTy;
1406 if (IsDereference) {
1407 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1408 return;
1409 }
1410 SrcTy = SrcType->getPointeeType();
1411 DestTy = DestType->getPointeeType();
1412 } else {
1413 if (!DestType->getAs<ReferenceType>()) {
1414 return;
1415 }
1416 SrcTy = SrcType;
1417 DestTy = DestType->getPointeeType();
1418 }
1419
1420 // Cast is compatible if the types are the same.
1421 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1422 return;
1423 }
1424 // or one of the types is a char or void type
1425 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1426 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1427 return;
1428 }
1429 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001430 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001431 return;
1432 }
1433
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001434 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001435 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1436 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1437 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1438 return;
1439 }
1440 }
1441
1442 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1443}
Douglas Gregor1beec452011-03-12 01:48:56 +00001444
John Wiegley01296292011-04-08 18:41:53 +00001445static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001446 QualType DestType, bool CStyle,
1447 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001448 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001449 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001450 bool IsLValueCast = false;
1451
Sebastian Redl9f831db2009-07-25 15:41:38 +00001452 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001453 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001454
1455 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001456 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1457 if (SrcType == Self.Context.OverloadTy) {
1458 // ... unless foo<int> resolves to an lvalue unambiguously
1459 ExprResult SingleFunctionExpr =
John Wiegley01296292011-04-08 18:41:53 +00001460 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregorb491ed32011-02-19 21:32:49 +00001461 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1462 );
1463 if (SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001464 SrcExpr = move(SingleFunctionExpr);
1465 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001466 }
1467 else
1468 return TC_NotApplicable;
1469 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001470
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001471 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001472 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00001473 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001474 // Cannot cast non-lvalue to lvalue reference type. See the similar
1475 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001476 msg = diag::err_bad_cxx_cast_rvalue;
1477 return TC_NotApplicable;
1478 }
1479
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001480 if (!CStyle) {
1481 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1482 /*isDereference=*/false, OpRange);
1483 }
1484
Sebastian Redl9f831db2009-07-25 15:41:38 +00001485 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1486 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1487 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001488
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001489 const char *inappropriate = 0;
1490 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001491 case OK_Ordinary:
1492 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001493 case OK_BitField: inappropriate = "bit-field"; break;
1494 case OK_VectorComponent: inappropriate = "vector element"; break;
1495 case OK_ObjCProperty: inappropriate = "property expression"; break;
1496 }
1497 if (inappropriate) {
1498 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1499 << inappropriate << DestType
1500 << OpRange << SrcExpr.get()->getSourceRange();
1501 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001502 return TC_NotApplicable;
1503 }
1504
Sebastian Redl9f831db2009-07-25 15:41:38 +00001505 // This code does this transformation for the checked types.
1506 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1507 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001508
Douglas Gregor51954272010-07-13 23:17:26 +00001509 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001510 }
1511
1512 // Canonicalize source for comparison.
1513 SrcType = Self.Context.getCanonicalType(SrcType);
1514
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001515 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1516 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001517 if (DestMemPtr && SrcMemPtr) {
1518 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1519 // can be explicitly converted to an rvalue of type "pointer to member
1520 // of Y of type T2" if T1 and T2 are both function types or both object
1521 // types.
1522 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1523 SrcMemPtr->getPointeeType()->isFunctionType())
1524 return TC_NotApplicable;
1525
1526 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1527 // constness.
1528 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1529 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001530 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1531 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001532 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001533 return TC_Failed;
1534 }
1535
Charles Davisebab1ed2010-08-16 05:30:44 +00001536 // Don't allow casting between member pointers of different sizes.
1537 if (Self.Context.getTypeSize(DestMemPtr) !=
1538 Self.Context.getTypeSize(SrcMemPtr)) {
1539 msg = diag::err_bad_cxx_cast_member_pointer_size;
1540 return TC_Failed;
1541 }
1542
Sebastian Redl9f831db2009-07-25 15:41:38 +00001543 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001544 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001545 return TC_Success;
1546 }
1547
1548 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001549 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001550 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1551 // type large enough to hold it. A value of std::nullptr_t can be
1552 // converted to an integral type; the conversion has the same meaning
1553 // and validity as a conversion of (void*)0 to the integral type.
1554 if (Self.Context.getTypeSize(SrcType) >
1555 Self.Context.getTypeSize(DestType)) {
1556 msg = diag::err_bad_reinterpret_cast_small_int;
1557 return TC_Failed;
1558 }
John McCalle3027922010-08-25 11:45:40 +00001559 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001560 return TC_Success;
1561 }
1562
Anders Carlsson570af5d2009-09-16 19:19:43 +00001563 bool destIsVector = DestType->isVectorType();
1564 bool srcIsVector = SrcType->isVectorType();
1565 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001566 // FIXME: Should this also apply to floating point types?
1567 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1568 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001569
1570 // Check if this is a cast between a vector and something else.
1571 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1572 !(srcIsVector && destIsVector))
1573 return TC_NotApplicable;
1574
1575 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001576 if (Self.Context.getTypeSize(SrcType)
1577 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001578 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001579 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001580 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001581
1582 if (destIsScalar)
1583 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1584 else if (srcIsScalar)
1585 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1586 else
1587 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1588
1589 return TC_Failed;
1590 }
1591
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001592 bool destIsPtr = DestType->isAnyPointerType() ||
1593 DestType->isBlockPointerType();
1594 bool srcIsPtr = SrcType->isAnyPointerType() ||
1595 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001596 if (!destIsPtr && !srcIsPtr) {
1597 // Except for std::nullptr_t->integer and lvalue->reference, which are
1598 // handled above, at least one of the two arguments must be a pointer.
1599 return TC_NotApplicable;
1600 }
1601
1602 if (SrcType == DestType) {
1603 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1604 // restrictions, a cast to the same type is allowed. The intent is not
1605 // entirely clear here, since all other paragraphs explicitly forbid casts
1606 // to the same type. However, the behavior of compilers is pretty consistent
1607 // on this point: allow same-type conversion if the involved types are
1608 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001609 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001610 return TC_Success;
1611 }
1612
Douglas Gregor6972a622010-06-16 00:35:25 +00001613 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001614 assert(srcIsPtr && "One type must be a pointer");
1615 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001616 // type large enough to hold it; except in Microsoft mode, where the
1617 // integral type size doesn't matter.
1618 if ((Self.Context.getTypeSize(SrcType) >
1619 Self.Context.getTypeSize(DestType)) &&
Francois Pichet0706d202011-09-17 17:15:52 +00001620 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001621 msg = diag::err_bad_reinterpret_cast_small_int;
1622 return TC_Failed;
1623 }
John McCalle3027922010-08-25 11:45:40 +00001624 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001625 return TC_Success;
1626 }
1627
Douglas Gregorb90df602010-06-16 00:17:44 +00001628 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001629 assert(destIsPtr && "One type must be a pointer");
1630 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1631 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001632 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1633 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001634 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001635 return TC_Success;
1636 }
1637
1638 if (!destIsPtr || !srcIsPtr) {
1639 // With the valid non-pointer conversions out of the way, we can be even
1640 // more stringent.
1641 return TC_NotApplicable;
1642 }
1643
1644 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1645 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001646 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1647 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001648 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001649 return TC_Failed;
1650 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001651
1652 // Cannot convert between block pointers and Objective-C object pointers.
1653 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1654 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1655 return TC_NotApplicable;
1656
John McCall9320b872011-09-09 05:25:32 +00001657 if (IsLValueCast) {
1658 Kind = CK_LValueBitCast;
1659 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001660 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001661 } else if (DestType->isBlockPointerType()) {
1662 if (!SrcType->isBlockPointerType()) {
1663 Kind = CK_AnyPointerToBlockPointerCast;
1664 } else {
1665 Kind = CK_BitCast;
1666 }
1667 } else {
1668 Kind = CK_BitCast;
1669 }
1670
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001671 // Any pointer can be cast to an Objective-C pointer type with a C-style
1672 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001673 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001674 return TC_Success;
1675 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001676
Sebastian Redl9f831db2009-07-25 15:41:38 +00001677 // Not casting away constness, so the only remaining check is for compatible
1678 // pointer categories.
1679
1680 if (SrcType->isFunctionPointerType()) {
1681 if (DestType->isFunctionPointerType()) {
1682 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1683 // a pointer to a function of a different type.
1684 return TC_Success;
1685 }
1686
1687 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1688 // an object type or vice versa is conditionally-supported.
1689 // Compilers support it in C++03 too, though, because it's necessary for
1690 // casting the return value of dlsym() and GetProcAddress().
1691 // FIXME: Conditionally-supported behavior should be configurable in the
1692 // TargetInfo or similar.
1693 if (!Self.getLangOptions().CPlusPlus0x)
1694 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1695 return TC_Success;
1696 }
1697
1698 if (DestType->isFunctionPointerType()) {
1699 // See above.
1700 if (!Self.getLangOptions().CPlusPlus0x)
1701 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1702 return TC_Success;
1703 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001704
Sebastian Redl9f831db2009-07-25 15:41:38 +00001705 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1706 // a pointer to an object of different type.
1707 // Void pointers are not specified, but supported by every compiler out there.
1708 // So we finish by allowing everything that remains - it's got to be two
1709 // object pointers.
1710 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001711}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001712
John McCall9776e432011-10-06 23:25:11 +00001713void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
1714 // Handle placeholders.
1715 if (isPlaceholder()) {
1716 // C-style casts can resolve __unknown_any types.
1717 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1718 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1719 SrcExpr.get(), Kind,
1720 ValueKind, BasePath);
1721 return;
1722 }
John McCallb50451a2011-10-05 07:41:44 +00001723
John McCall9776e432011-10-06 23:25:11 +00001724 checkNonOverloadPlaceholders();
1725 if (SrcExpr.isInvalid())
1726 return;
1727 }
1728
1729 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00001730 // This test is outside everything else because it's the only case where
1731 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00001732 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00001733 Kind = CK_ToVoid;
1734
John McCall9776e432011-10-06 23:25:11 +00001735 if (claimPlaceholder(BuiltinType::Overload)) {
John McCallb50451a2011-10-05 07:41:44 +00001736 SrcExpr = Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1737 SrcExpr.take(), /* Decay Function to ptr */ false,
1738 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00001739 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00001740 if (SrcExpr.isInvalid())
1741 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001742 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001743
John McCall9776e432011-10-06 23:25:11 +00001744 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1745 if (SrcExpr.isInvalid())
John McCallb50451a2011-10-05 07:41:44 +00001746 return;
John McCallb50451a2011-10-05 07:41:44 +00001747
1748 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00001749 }
1750
Sebastian Redl9f831db2009-07-25 15:41:38 +00001751 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb50451a2011-10-05 07:41:44 +00001752 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1753 assert(Kind == CK_Dependent);
1754 return;
John McCall8cb679e2010-11-15 09:13:47 +00001755 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00001756
John McCallb50451a2011-10-05 07:41:44 +00001757 if (ValueKind == VK_RValue && !DestType->isRecordType()) {
1758 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1759 if (SrcExpr.isInvalid())
1760 return;
John Wiegley01296292011-04-08 18:41:53 +00001761 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001762
John McCall3aef3d82011-04-10 19:13:55 +00001763 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00001764 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00001765 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00001766 && (SrcExpr.get()->getType()->isIntegerType()
1767 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00001768 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00001769 return;
John McCall3aef3d82011-04-10 19:13:55 +00001770 }
1771
Sebastian Redl9f831db2009-07-25 15:41:38 +00001772 // C++ [expr.cast]p5: The conversions performed by
1773 // - a const_cast,
1774 // - a static_cast,
1775 // - a static_cast followed by a const_cast,
1776 // - a reinterpret_cast, or
1777 // - a reinterpret_cast followed by a const_cast,
1778 // can be performed using the cast notation of explicit type conversion.
1779 // [...] If a conversion can be interpreted in more than one of the ways
1780 // listed above, the interpretation that appears first in the list is used,
1781 // even if a cast resulting from that interpretation is ill-formed.
1782 // In plain language, this means trying a const_cast ...
1783 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb50451a2011-10-05 07:41:44 +00001784 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1785 /*CStyle*/true, msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001786 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001787 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001788
John McCall31168b02011-06-15 23:02:42 +00001789 Sema::CheckedConversionKind CCK
1790 = FunctionalStyle? Sema::CCK_FunctionalCast
1791 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001792 if (tcr == TC_NotApplicable) {
1793 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00001794 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1795 msg, Kind, BasePath);
1796 if (SrcExpr.isInvalid())
1797 return;
1798
Sebastian Redl9f831db2009-07-25 15:41:38 +00001799 if (tcr == TC_NotApplicable) {
1800 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00001801 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1802 OpRange, msg, Kind);
1803 if (SrcExpr.isInvalid())
1804 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001805 }
1806 }
1807
John McCallb50451a2011-10-05 07:41:44 +00001808 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1809 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00001810
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001811 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00001812 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001813 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00001814 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1815 DestType,
1816 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001817 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001818
Richard Trieu70d14f52011-04-16 01:09:30 +00001819 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001820 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001821
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001822 } else {
John McCallb50451a2011-10-05 07:41:44 +00001823 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1824 OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001825 }
John McCallb50451a2011-10-05 07:41:44 +00001826 } else if (Kind == CK_BitCast) {
1827 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001828 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001829
John McCallb50451a2011-10-05 07:41:44 +00001830 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00001831 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00001832 SrcExpr = ExprError();
1833}
1834
John McCall9776e432011-10-06 23:25:11 +00001835/// Check the semantics of a C-style cast operation, in C.
1836void CastOperation::CheckCStyleCast() {
1837 assert(!Self.getLangOptions().CPlusPlus);
1838
1839 // Handle placeholders.
1840 if (isPlaceholder()) {
1841 // C-style casts can resolve __unknown_any types.
1842 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1843 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1844 SrcExpr.get(), Kind,
1845 ValueKind, BasePath);
1846 return;
1847 }
1848
1849 checkNonOverloadPlaceholders();
1850 if (SrcExpr.isInvalid())
1851 return;
1852 }
1853
1854 assert(!isPlaceholder());
1855
1856 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1857 // type needs to be scalar.
1858 if (DestType->isVoidType()) {
1859 // We don't necessarily do lvalue-to-rvalue conversions on this.
1860 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1861 if (SrcExpr.isInvalid())
1862 return;
1863
1864 // Cast to void allows any expr type.
1865 Kind = CK_ToVoid;
1866 return;
1867 }
1868
1869 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1870 if (SrcExpr.isInvalid())
1871 return;
1872 QualType SrcType = SrcExpr.get()->getType();
1873
1874 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1875 diag::err_typecheck_cast_to_incomplete)) {
1876 SrcExpr = ExprError();
1877 return;
1878 }
1879
1880 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1881 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1882
1883 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1884 // GCC struct/union extension: allow cast to self.
1885 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1886 << DestType << SrcExpr.get()->getSourceRange();
1887 Kind = CK_NoOp;
1888 return;
1889 }
1890
1891 // GCC's cast to union extension.
1892 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1893 RecordDecl *RD = DestRecordTy->getDecl();
1894 RecordDecl::field_iterator Field, FieldEnd;
1895 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1896 Field != FieldEnd; ++Field) {
1897 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1898 !Field->isUnnamedBitfield()) {
1899 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1900 << SrcExpr.get()->getSourceRange();
1901 break;
1902 }
1903 }
1904 if (Field == FieldEnd) {
1905 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1906 << SrcType << SrcExpr.get()->getSourceRange();
1907 SrcExpr = ExprError();
1908 return;
1909 }
1910 Kind = CK_ToUnion;
1911 return;
1912 }
1913
1914 // Reject any other conversions to non-scalar types.
1915 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1916 << DestType << SrcExpr.get()->getSourceRange();
1917 SrcExpr = ExprError();
1918 return;
1919 }
1920
1921 // The type we're casting to is known to be a scalar or vector.
1922
1923 // Require the operand to be a scalar or vector.
1924 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1925 Self.Diag(SrcExpr.get()->getExprLoc(),
1926 diag::err_typecheck_expect_scalar_operand)
1927 << SrcType << SrcExpr.get()->getSourceRange();
1928 SrcExpr = ExprError();
1929 return;
1930 }
1931
1932 if (DestType->isExtVectorType()) {
1933 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1934 return;
1935 }
1936
1937 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1938 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1939 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1940 Kind = CK_VectorSplat;
1941 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1942 SrcExpr = ExprError();
1943 }
1944 return;
1945 }
1946
1947 if (SrcType->isVectorType()) {
1948 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1949 SrcExpr = ExprError();
1950 return;
1951 }
1952
1953 // The source and target types are both scalars, i.e.
1954 // - arithmetic types (fundamental, enum, and complex)
1955 // - all kinds of pointers
1956 // Note that member pointers were filtered out with C++, above.
1957
1958 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
1959 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
1960 SrcExpr = ExprError();
1961 return;
1962 }
1963
1964 // If either type is a pointer, the other type has to be either an
1965 // integer or a pointer.
1966 if (!DestType->isArithmeticType()) {
1967 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
1968 Self.Diag(SrcExpr.get()->getExprLoc(),
1969 diag::err_cast_pointer_from_non_pointer_int)
1970 << SrcType << SrcExpr.get()->getSourceRange();
1971 SrcExpr = ExprError();
1972 return;
1973 }
1974 } else if (!SrcType->isArithmeticType()) {
1975 if (!DestType->isIntegralType(Self.Context) &&
1976 DestType->isArithmeticType()) {
1977 Self.Diag(SrcExpr.get()->getLocStart(),
1978 diag::err_cast_pointer_to_non_pointer_int)
1979 << SrcType << SrcExpr.get()->getSourceRange();
1980 SrcExpr = ExprError();
1981 return;
1982 }
1983 }
1984
1985 // ARC imposes extra restrictions on casts.
1986 if (Self.getLangOptions().ObjCAutoRefCount) {
1987 checkObjCARCConversion(Sema::CCK_CStyleCast);
1988 if (SrcExpr.isInvalid())
1989 return;
1990
1991 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
1992 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
1993 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
1994 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
1995 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
1996 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
1997 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
1998 Self.Diag(SrcExpr.get()->getLocStart(),
1999 diag::err_typecheck_incompatible_ownership)
2000 << SrcType << DestType << Sema::AA_Casting
2001 << SrcExpr.get()->getSourceRange();
2002 return;
2003 }
2004 }
2005 }
2006 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2007 Self.Diag(SrcExpr.get()->getLocStart(),
2008 diag::err_arc_convesion_of_weak_unavailable)
2009 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2010 SrcExpr = ExprError();
2011 return;
2012 }
2013 }
2014
2015 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2016 if (SrcExpr.isInvalid())
2017 return;
2018
2019 if (Kind == CK_BitCast)
2020 checkCastAlign();
2021}
2022
2023ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2024 TypeSourceInfo *CastTypeInfo,
2025 SourceLocation RPLoc,
2026 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002027 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2028 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2029 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2030
John McCall9776e432011-10-06 23:25:11 +00002031 if (getLangOptions().CPlusPlus) {
2032 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false);
2033 } else {
2034 Op.CheckCStyleCast();
2035 }
2036
John McCallb50451a2011-10-05 07:41:44 +00002037 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002038 return ExprError();
2039
John McCallb50451a2011-10-05 07:41:44 +00002040 return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
2041 Op.Kind, Op.SrcExpr.take(), &Op.BasePath,
2042 CastTypeInfo, LPLoc, RPLoc));
2043}
2044
2045ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2046 SourceLocation LPLoc,
2047 Expr *CastExpr,
2048 SourceLocation RPLoc) {
2049 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2050 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2051 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2052
John McCall9776e432011-10-06 23:25:11 +00002053 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true);
John McCallb50451a2011-10-05 07:41:44 +00002054 if (Op.SrcExpr.isInvalid())
2055 return ExprError();
2056
2057 return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2058 Op.ValueKind, CastTypeInfo,
2059 Op.DestRange.getBegin(),
2060 Op.Kind, Op.SrcExpr.take(),
2061 &Op.BasePath, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002062}