blob: b20732a5f72b153e5fd7e22b093868cdb7b82e9d [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.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 McCall3cec19f2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000019#include "clang/AST/ExprCXX.h"
John McCall9776e432011-10-06 23:25:11 +000020#include "clang/AST/ExprObjC.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000024#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000025#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026using namespace clang;
27
Douglas Gregore81f58e2010-11-08 03:40:48 +000028
Douglas Gregore81f58e2010-11-08 03:40:48 +000029
Sebastian Redl9f831db2009-07-25 15:41:38 +000030enum TryCastResult {
31 TC_NotApplicable, ///< The cast method is not applicable.
32 TC_Success, ///< The cast method is appropriate and successful.
33 TC_Failed ///< The cast method is appropriate, but failed. A
34 ///< diagnostic has been emitted.
35};
36
37enum CastType {
38 CT_Const, ///< const_cast
39 CT_Static, ///< static_cast
40 CT_Reinterpret, ///< reinterpret_cast
41 CT_Dynamic, ///< dynamic_cast
42 CT_CStyle, ///< (Type)expr
43 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000044};
45
John McCallb50451a2011-10-05 07:41:44 +000046namespace {
47 struct CastOperation {
48 CastOperation(Sema &S, QualType destType, ExprResult src)
49 : Self(S), SrcExpr(src), DestType(destType),
50 ResultType(destType.getNonLValueExprType(S.Context)),
51 ValueKind(Expr::getValueKindForType(destType)),
John McCall50a2c2c2011-10-11 23:14:30 +000052 Kind(CK_Dependent) {
John McCall9776e432011-10-06 23:25:11 +000053
54 if (const BuiltinType *placeholder =
55 src.get()->getType()->getAsPlaceholderType()) {
56 PlaceholderKind = placeholder->getKind();
57 } else {
58 PlaceholderKind = (BuiltinType::Kind) 0;
59 }
60 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000061
John McCallb50451a2011-10-05 07:41:44 +000062 Sema &Self;
63 ExprResult SrcExpr;
64 QualType DestType;
65 QualType ResultType;
66 ExprValueKind ValueKind;
67 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000068 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000069 CXXCastPath BasePath;
Douglas Gregore81f58e2010-11-08 03:40:48 +000070
John McCallb50451a2011-10-05 07:41:44 +000071 SourceRange OpRange;
72 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000073
John McCall9776e432011-10-06 23:25:11 +000074 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000075 void CheckConstCast();
76 void CheckReinterpretCast();
77 void CheckStaticCast();
78 void CheckDynamicCast();
John McCall9776e432011-10-06 23:25:11 +000079 void CheckCXXCStyleCast(bool FunctionalCast);
80 void CheckCStyleCast();
81
82 // Internal convenience methods.
83
84 /// Try to handle the given placeholder expression kind. Return
85 /// true if the source expression has the appropriate placeholder
86 /// kind. A placeholder can only be claimed once.
87 bool claimPlaceholder(BuiltinType::Kind K) {
88 if (PlaceholderKind != K) return false;
89
90 PlaceholderKind = (BuiltinType::Kind) 0;
91 return true;
92 }
93
94 bool isPlaceholder() const {
95 return PlaceholderKind != 0;
96 }
97 bool isPlaceholder(BuiltinType::Kind K) const {
98 return PlaceholderKind == K;
99 }
John McCallb50451a2011-10-05 07:41:44 +0000100
101 void checkCastAlign() {
102 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
103 }
104
105 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
106 Expr *src = SrcExpr.get();
107 Self.CheckObjCARCConversion(OpRange, DestType, src, CCK);
108 SrcExpr = src;
109 }
John McCall9776e432011-10-06 23:25:11 +0000110
111 /// Check for and handle non-overload placeholder expressions.
112 void checkNonOverloadPlaceholders() {
113 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
114 return;
115
116 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
117 if (SrcExpr.isInvalid())
118 return;
119 PlaceholderKind = (BuiltinType::Kind) 0;
120 }
John McCallb50451a2011-10-05 07:41:44 +0000121 };
122}
Sebastian Redl842ef522008-11-08 13:00:26 +0000123
John McCall31168b02011-06-15 23:02:42 +0000124static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
125 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000126
127// The Try functions attempt a specific way of casting. If they succeed, they
128// return TC_Success. If their way of casting is not appropriate for the given
129// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
130// to emit if no other way succeeds. If their way of casting is appropriate but
131// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
132// they emit a specialized diagnostic.
133// All diagnostics returned by these functions must expect the same three
134// arguments:
135// %0: Cast Type (a value from the CastType enumeration)
136// %1: Source Type
137// %2: Destination Type
138static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000139 QualType DestType, bool CStyle,
140 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000141 CXXCastPath &BasePath,
142 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000143static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000144 QualType DestType, bool CStyle,
145 const SourceRange &OpRange,
146 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000147 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000148 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000149static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
150 QualType DestType, bool CStyle,
151 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000152 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000153 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000154 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000155static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
156 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000157 const SourceRange &OpRange,
158 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000159 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000160 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000161 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000162static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000163 QualType SrcType,
164 QualType DestType,bool CStyle,
165 const SourceRange &OpRange,
166 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000167 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000168 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000169
John Wiegley01296292011-04-08 18:41:53 +0000170static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000171 QualType DestType,
172 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000173 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000174 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000175 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +0000176static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000177 QualType DestType,
178 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000179 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000180 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000181 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000182 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000183static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
184 bool CStyle, unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000185static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000186 QualType DestType, bool CStyle,
187 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000188 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000189 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000190
Douglas Gregorb491ed32011-02-19 21:32:49 +0000191
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000192/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000193ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000194Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000195 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000196 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000197 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000198 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000199
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000200 assert(!D.isInvalidType());
201
202 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
203 if (D.isInvalidType())
204 return ExprError();
205
206 if (getLangOptions().CPlusPlus) {
207 // Check that there are no default arguments (C++ only).
208 CheckExtraCXXDefaultArguments(D);
209 }
210
211 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
John McCalld377e042010-01-15 19:13:16 +0000212 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
213 SourceRange(LParenLoc, RParenLoc));
214}
215
John McCalldadc5752010-08-24 06:29:42 +0000216ExprResult
John McCalld377e042010-01-15 19:13:16 +0000217Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000218 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000219 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000220 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000221 QualType DestType = DestTInfo->getType();
222
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000223 // If the type is dependent, we won't do the semantic analysis now.
224 // FIXME: should we check this in a more fine-grained manner?
John Wiegley01296292011-04-08 18:41:53 +0000225 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000226
John McCallb50451a2011-10-05 07:41:44 +0000227 CastOperation Op(*this, DestType, E);
228 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
229 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000230
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000231 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000232 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000233
234 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000235 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000236 Op.CheckConstCast();
237 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000238 return ExprError();
239 }
John McCallb50451a2011-10-05 07:41:44 +0000240 return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
241 Op.SrcExpr.take(), DestTInfo, OpLoc,
Douglas Gregor4478f852011-01-12 22:41:29 +0000242 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000243
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000244 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000245 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000246 Op.CheckDynamicCast();
247 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000248 return ExprError();
249 }
John McCallb50451a2011-10-05 07:41:44 +0000250 return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType,
251 Op.ValueKind, Op.Kind,
252 Op.SrcExpr.take(), &Op.BasePath,
253 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000254 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000255 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000256 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000257 Op.CheckReinterpretCast();
258 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000259 return ExprError();
260 }
John McCallb50451a2011-10-05 07:41:44 +0000261 return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
262 Op.ValueKind, Op.Kind,
263 Op.SrcExpr.take(), 0,
264 DestTInfo, OpLoc,
265 Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000266 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000267 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000268 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000269 Op.CheckStaticCast();
270 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000271 return ExprError();
272 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000273
John McCallb50451a2011-10-05 07:41:44 +0000274 return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
275 Op.Kind, Op.SrcExpr.take(),
276 &Op.BasePath, DestTInfo, OpLoc,
277 Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000278 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000279 }
280
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000281 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000282}
283
John McCall909acf82011-02-14 18:34:10 +0000284/// Try to diagnose a failed overloaded cast. Returns true if
285/// diagnostics were emitted.
286static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
287 SourceRange range, Expr *src,
288 QualType destType) {
289 switch (CT) {
290 // These cast kinds don't consider user-defined conversions.
291 case CT_Const:
292 case CT_Reinterpret:
293 case CT_Dynamic:
294 return false;
295
296 // These do.
297 case CT_Static:
298 case CT_CStyle:
299 case CT_Functional:
300 break;
301 }
302
303 QualType srcType = src->getType();
304 if (!destType->isRecordType() && !srcType->isRecordType())
305 return false;
306
307 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
308 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000309 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
310 range)
311 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
312 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall909acf82011-02-14 18:34:10 +0000313 InitializationSequence sequence(S, entity, initKind, &src, 1);
314
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000315 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000316 switch (sequence.getFailureKind()) {
317 default: return false;
318
319 case InitializationSequence::FK_ConstructorOverloadFailed:
320 case InitializationSequence::FK_UserConversionOverloadFailed:
321 break;
322 }
323
324 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
325
326 unsigned msg = 0;
327 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
328
329 switch (sequence.getFailedOverloadResult()) {
330 case OR_Success: llvm_unreachable("successful failed overload");
331 return false;
332 case OR_No_Viable_Function:
333 if (candidates.empty())
334 msg = diag::err_ovl_no_conversion_in_cast;
335 else
336 msg = diag::err_ovl_no_viable_conversion_in_cast;
337 howManyCandidates = OCD_AllCandidates;
338 break;
339
340 case OR_Ambiguous:
341 msg = diag::err_ovl_ambiguous_conversion_in_cast;
342 howManyCandidates = OCD_ViableCandidates;
343 break;
344
345 case OR_Deleted:
346 msg = diag::err_ovl_deleted_conversion_in_cast;
347 howManyCandidates = OCD_ViableCandidates;
348 break;
349 }
350
351 S.Diag(range.getBegin(), msg)
352 << CT << srcType << destType
353 << range << src->getSourceRange();
354
355 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
356
357 return true;
358}
359
360/// Diagnose a failed cast.
361static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
362 SourceRange opRange, Expr *src, QualType destType) {
John McCall0009fcc2011-04-26 20:42:42 +0000363 if (src->getType() == S.Context.BoundMemberTy) {
364 (void) S.CheckPlaceholderExpr(src); // will always fail
365 return;
366 }
367
John McCall909acf82011-02-14 18:34:10 +0000368 if (msg == diag::err_bad_cxx_cast_generic &&
369 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
370 return;
371
372 S.Diag(opRange.getBegin(), msg) << castType
373 << src->getType() << destType << opRange << src->getSourceRange();
374}
375
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000376/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
377/// this removes one level of indirection from both types, provided that they're
378/// the same kind of pointer (plain or to-member). Unlike the Sema function,
379/// this one doesn't care if the two pointers-to-member don't point into the
380/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000381static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000382 const PointerType *T1PtrType = T1->getAs<PointerType>(),
383 *T2PtrType = T2->getAs<PointerType>();
384 if (T1PtrType && T2PtrType) {
385 T1 = T1PtrType->getPointeeType();
386 T2 = T2PtrType->getPointeeType();
387 return true;
388 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000389 const ObjCObjectPointerType *T1ObjCPtrType =
390 T1->getAs<ObjCObjectPointerType>(),
391 *T2ObjCPtrType =
392 T2->getAs<ObjCObjectPointerType>();
393 if (T1ObjCPtrType) {
394 if (T2ObjCPtrType) {
395 T1 = T1ObjCPtrType->getPointeeType();
396 T2 = T2ObjCPtrType->getPointeeType();
397 return true;
398 }
399 else if (T2PtrType) {
400 T1 = T1ObjCPtrType->getPointeeType();
401 T2 = T2PtrType->getPointeeType();
402 return true;
403 }
404 }
405 else if (T2ObjCPtrType) {
406 if (T1PtrType) {
407 T2 = T2ObjCPtrType->getPointeeType();
408 T1 = T1PtrType->getPointeeType();
409 return true;
410 }
411 }
412
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000413 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
414 *T2MPType = T2->getAs<MemberPointerType>();
415 if (T1MPType && T2MPType) {
416 T1 = T1MPType->getPointeeType();
417 T2 = T2MPType->getPointeeType();
418 return true;
419 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000420
421 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
422 *T2BPType = T2->getAs<BlockPointerType>();
423 if (T1BPType && T2BPType) {
424 T1 = T1BPType->getPointeeType();
425 T2 = T2BPType->getPointeeType();
426 return true;
427 }
428
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000429 return false;
430}
431
Sebastian Redla5a77a62009-01-27 23:18:31 +0000432/// CastsAwayConstness - Check if the pointer conversion from SrcType to
433/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
434/// the cast checkers. Both arguments must denote pointer (possibly to member)
435/// types.
John McCall31168b02011-06-15 23:02:42 +0000436///
437/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
438///
439/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000440static bool
John McCall31168b02011-06-15 23:02:42 +0000441CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
442 bool CheckCVR, bool CheckObjCLifetime) {
443 // If the only checking we care about is for Objective-C lifetime qualifiers,
444 // and we're not in ARC mode, there's nothing to check.
445 if (!CheckCVR && CheckObjCLifetime &&
446 !Self.Context.getLangOptions().ObjCAutoRefCount)
447 return false;
448
Sebastian Redla5a77a62009-01-27 23:18:31 +0000449 // Casting away constness is defined in C++ 5.2.11p8 with reference to
450 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
451 // the rules are non-trivial. So first we construct Tcv *...cv* as described
452 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000453 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
454 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000455 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000456 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
457 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000458 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000459
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000460 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
461 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000463
Douglas Gregorb472e932011-04-15 17:59:54 +0000464 // Find the qualifiers. We only care about cvr-qualifiers for the
465 // purpose of this check, because other qualifiers (address spaces,
466 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000467 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000468 // Determine the relevant qualifiers at this level.
469 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000470 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000471 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000472
473 Qualifiers RetainedSrcQuals, RetainedDestQuals;
474 if (CheckCVR) {
475 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
476 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
477 }
478
479 if (CheckObjCLifetime &&
480 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
481 return true;
482
483 cv1.push_back(RetainedSrcQuals);
484 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000485 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000486 if (cv1.empty())
487 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000488
489 // Construct void pointers with those qualifiers (in reverse order of
490 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000491 QualType SrcConstruct = Self.Context.VoidTy;
492 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000493 ASTContext &Context = Self.Context;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall8ccfcb52009-09-24 19:53:00 +0000495 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000496 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000497 SrcConstruct
498 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
499 DestConstruct
500 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000501 }
502
503 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000504 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000505 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000506 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
507 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000508}
509
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000510/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
511/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
512/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000513void CastOperation::CheckDynamicCast() {
514 QualType OrigSrcType = SrcExpr.get()->getType();
515 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000516
517 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
518 // or "pointer to cv void".
519
520 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000521 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000522 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000523 if (DestPointer) {
524 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000525 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000526 DestPointee = DestReference->getPointeeType();
527 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000528 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000529 << this->DestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000530 return;
531 }
532
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000533 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000534 if (DestPointee->isVoidType()) {
535 assert(DestPointer && "Reference to void is not possible");
536 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000537 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000538 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000539 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000540 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000541 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000542 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000543 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000544 return;
545 }
546
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000547 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
548 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000549 // an lvalue of a complete class type, [...]. If T is an rvalue reference
550 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000551 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000552 QualType SrcPointee;
553 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000554 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000555 SrcPointee = SrcPointer->getPointeeType();
556 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000557 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000558 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000559 return;
560 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000561 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000562 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000563 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000564 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000565 }
566 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000567 } else {
568 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000569 }
570
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000571 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000572 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000573 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000574 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley01296292011-04-08 18:41:53 +0000575 << SrcExpr.get()->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000576 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000577 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000578 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000579 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000580 return;
581 }
582
583 assert((DestPointer || DestReference) &&
584 "Bad destination non-ptr/ref slipped through.");
585 assert((DestRecord || DestPointee->isVoidType()) &&
586 "Bad destination pointee slipped through.");
587 assert(SrcRecord && "Bad source pointee slipped through.");
588
589 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
590 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000591 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000592 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000593 return;
594 }
595
596 // C++ 5.2.7p3: If the type of v is the same as the required result type,
597 // [except for cv].
598 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000599 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000600 return;
601 }
602
603 // C++ 5.2.7p5
604 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000605 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000606 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
607 OpRange.getBegin(), OpRange,
608 &BasePath))
609 return;
610
John McCalle3027922010-08-25 11:45:40 +0000611 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000612
613 // If we are casting to or through a virtual base class, we need a
614 // vtable.
615 if (Self.BasePathInvolvesVirtualBase(BasePath))
616 Self.MarkVTableUsed(OpRange.getBegin(),
617 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000618 return;
619 }
620
621 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000622 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000623 assert(SrcDecl && "Definition missing");
624 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000625 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000626 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000627 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000628 Self.MarkVTableUsed(OpRange.getBegin(),
629 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000630
631 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000632 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000633}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000634
635/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
636/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
637/// like this:
638/// const char *str = "literal";
639/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000640void CastOperation::CheckConstCast() {
John McCall50a2c2c2011-10-11 23:14:30 +0000641 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000642 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
643 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
644 return;
645 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000646
647 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley01296292011-04-08 18:41:53 +0000648 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9f831db2009-07-25 15:41:38 +0000649 && msg != 0)
650 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000651 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000652}
653
654/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
655/// valid.
656/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
657/// like this:
658/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000659void CastOperation::CheckReinterpretCast() {
John McCall50a2c2c2011-10-11 23:14:30 +0000660 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000661 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
662 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
663 return;
664 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000665
666 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000667 TryCastResult tcr =
668 TryReinterpretCast(Self, SrcExpr, DestType,
669 /*CStyle*/false, OpRange, msg, Kind);
670 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000671 {
John Wiegley01296292011-04-08 18:41:53 +0000672 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
673 return;
674 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000675 //FIXME: &f<int>; is overloaded and resolvable
676 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000677 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000678 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000679 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000680
John McCall909acf82011-02-14 18:34:10 +0000681 } else {
John Wiegley01296292011-04-08 18:41:53 +0000682 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000683 }
John McCall31168b02011-06-15 23:02:42 +0000684 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb50451a2011-10-05 07:41:44 +0000685 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCall31168b02011-06-15 23:02:42 +0000686 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000687}
688
689
690/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
691/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
692/// implicit conversions explicit and getting rid of data loss warnings.
John McCallb50451a2011-10-05 07:41:44 +0000693void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000694 if (isPlaceholder()) {
695 checkNonOverloadPlaceholders();
696 if (SrcExpr.isInvalid())
697 return;
698 }
699
Sebastian Redl9f831db2009-07-25 15:41:38 +0000700 // This test is outside everything else because it's the only case where
701 // a non-lvalue-reference target type does not lead to decay.
702 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000703 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000704 Kind = CK_ToVoid;
705
706 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000707 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000708 false, // Decay Function to ptr
709 true, // Complain
710 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000711 if (SrcExpr.isInvalid())
712 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000713 }
John McCall9776e432011-10-06 23:25:11 +0000714
715 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000716 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000717 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000718
John McCall50a2c2c2011-10-11 23:14:30 +0000719 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
720 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000721 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
722 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
723 return;
724 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000725
726 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000727 TryCastResult tcr
728 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
729 Kind, BasePath);
730 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000731 if (SrcExpr.isInvalid())
732 return;
733 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
734 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000735 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000736 << oe->getName() << DestType << OpRange
737 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000738 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000739 } else {
John Wiegley01296292011-04-08 18:41:53 +0000740 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000741 }
John McCall31168b02011-06-15 23:02:42 +0000742 } else if (tcr == TC_Success) {
743 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000744 checkCastAlign();
745 if (Self.getLangOptions().ObjCAutoRefCount)
746 checkObjCARCConversion(Sema::CCK_OtherCast);
747 } else if (Kind == CK_BitCast) {
748 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000749 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000750}
751
752/// TryStaticCast - Check if a static cast can be performed, and do so if
753/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
754/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000755static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000756 QualType DestType,
757 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000758 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000759 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000760 CXXCastPath &BasePath) {
John McCall31168b02011-06-15 23:02:42 +0000761 // Determine whether we have the semantics of a C-style cast.
762 bool CStyle
763 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
764
Sebastian Redl9f831db2009-07-25 15:41:38 +0000765 // The order the tests is not entirely arbitrary. There is one conversion
766 // that can be handled in two different ways. Given:
767 // struct A {};
768 // struct B : public A {
769 // B(); B(const A&);
770 // };
771 // const A &a = B();
772 // the cast static_cast<const B&>(a) could be seen as either a static
773 // reference downcast, or an explicit invocation of the user-defined
774 // conversion using B's conversion constructor.
775 // DR 427 specifies that the downcast is to be applied here.
776
777 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
778 // Done outside this function.
779
780 TryCastResult tcr;
781
782 // C++ 5.2.9p5, reference downcast.
783 // See the function for details.
784 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley01296292011-04-08 18:41:53 +0000785 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000786 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000787 if (tcr != TC_NotApplicable)
788 return tcr;
789
Douglas Gregor465184a2011-01-22 00:06:57 +0000790 // C++0x [expr.static.cast]p3:
791 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
792 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley01296292011-04-08 18:41:53 +0000793 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregorce950842011-01-26 21:04:06 +0000794 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000795 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000796 return tcr;
797
798 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
799 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000800 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000801 Kind);
John Wiegley01296292011-04-08 18:41:53 +0000802 if (SrcExpr.isInvalid())
803 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000804 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000805 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000806
Sebastian Redl9f831db2009-07-25 15:41:38 +0000807 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
808 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
809 // conversions, subject to further restrictions.
810 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
811 // of qualification conversions impossible.
812 // In the CStyle case, the earlier attempt to const_cast should have taken
813 // care of reverse qualification conversions.
814
John Wiegley01296292011-04-08 18:41:53 +0000815 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000816
Douglas Gregor0bf31402010-10-08 23:50:27 +0000817 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000818 // converted to an integral type. [...] A value of a scoped enumeration type
819 // can also be explicitly converted to a floating-point type [...].
820 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
821 if (Enum->getDecl()->isScoped()) {
822 if (DestType->isBooleanType()) {
823 Kind = CK_IntegralToBoolean;
824 return TC_Success;
825 } else if (DestType->isIntegralType(Self.Context)) {
826 Kind = CK_IntegralCast;
827 return TC_Success;
828 } else if (DestType->isRealFloatingType()) {
829 Kind = CK_IntegralToFloating;
830 return TC_Success;
831 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000832 }
833 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000834
Sebastian Redl9f831db2009-07-25 15:41:38 +0000835 // Reverse integral promotion/conversion. All such conversions are themselves
836 // again integral promotions or conversions and are thus already handled by
837 // p2 (TryDirectInitialization above).
838 // (Note: any data loss warnings should be suppressed.)
839 // The exception is the reverse of enum->integer, i.e. integer->enum (and
840 // enum->enum). See also C++ 5.2.9p7.
841 // The same goes for reverse floating point promotion/conversion and
842 // floating-integral conversions. Again, only floating->enum is relevant.
843 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +0000844 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +0000845 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000846 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +0000847 } else if (SrcType->isRealFloatingType()) {
848 Kind = CK_FloatingToIntegral;
849 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000850 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000851 }
852
853 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
854 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000855 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000856 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000857 if (tcr != TC_NotApplicable)
858 return tcr;
859
860 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
861 // conversion. C++ 5.2.9p9 has additional information.
862 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000863 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000864 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000865 if (tcr != TC_NotApplicable)
866 return tcr;
867
868 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
869 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
870 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000871 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000872 QualType SrcPointee = SrcPointer->getPointeeType();
873 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000874 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000875 QualType DestPointee = DestPointer->getPointeeType();
876 if (DestPointee->isIncompleteOrObjectType()) {
877 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +0000878 // to a qualifier violation. Note that we permit Objective-C lifetime
879 // and GC qualifier mismatches here.
880 if (!CStyle) {
881 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
882 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
883 DestPointeeQuals.removeObjCGCAttr();
884 DestPointeeQuals.removeObjCLifetime();
885 SrcPointeeQuals.removeObjCGCAttr();
886 SrcPointeeQuals.removeObjCLifetime();
887 if (DestPointeeQuals != SrcPointeeQuals &&
888 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
889 msg = diag::err_bad_cxx_cast_qualifiers_away;
890 return TC_Failed;
891 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000892 }
John McCalle3027922010-08-25 11:45:40 +0000893 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000894 return TC_Success;
895 }
896 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000897 else if (DestType->isObjCObjectPointerType()) {
898 // allow both c-style cast and static_cast of objective-c pointers as
899 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +0000900 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000901 return TC_Success;
902 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000903 else if (CStyle && DestType->isBlockPointerType()) {
904 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000905 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000906 return TC_Success;
907 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000908 }
909 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000910 // Allow arbitray objective-c pointer conversion with static casts.
911 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000912 DestType->isObjCObjectPointerType()) {
913 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000914 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000915 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000916
Sebastian Redl9f831db2009-07-25 15:41:38 +0000917 // We tried everything. Everything! Nothing works! :-(
918 return TC_NotApplicable;
919}
920
921/// Tests whether a conversion according to N2844 is valid.
922TryCastResult
923TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000924 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
925 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000926 // C++0x [expr.static.cast]p3:
927 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
928 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000930 if (!R)
931 return TC_NotApplicable;
932
Douglas Gregor465184a2011-01-22 00:06:57 +0000933 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000934 return TC_NotApplicable;
935
936 // Because we try the reference downcast before this function, from now on
937 // this is the only cast possibility, so we issue an error if we fail now.
938 // FIXME: Should allow casting away constness if CStyle.
939 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000940 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +0000941 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000942 QualType FromType = SrcExpr->getType();
943 QualType ToType = R->getPointeeType();
944 if (CStyle) {
945 FromType = FromType.getUnqualifiedType();
946 ToType = ToType.getUnqualifiedType();
947 }
948
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000949 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000950 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +0000951 DerivedToBase, ObjCConversion,
952 ObjCLifetimeConversion)
953 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000954 msg = diag::err_bad_lvalue_to_rvalue_cast;
955 return TC_Failed;
956 }
957
Douglas Gregorba278e22011-01-25 16:13:26 +0000958 if (DerivedToBase) {
959 Kind = CK_DerivedToBase;
960 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
961 /*DetectVirtual=*/true);
962 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
963 return TC_NotApplicable;
964
965 Self.BuildBasePathArray(Paths, BasePath);
966 } else
967 Kind = CK_NoOp;
968
Sebastian Redl9f831db2009-07-25 15:41:38 +0000969 return TC_Success;
970}
971
972/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
973TryCastResult
974TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
975 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000976 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000977 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000978 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
979 // cast to type "reference to cv2 D", where D is a class derived from B,
980 // if a valid standard conversion from "pointer to D" to "pointer to B"
981 // exists, cv2 >= cv1, and B is not a virtual base class of D.
982 // In addition, DR54 clarifies that the base must be accessible in the
983 // current context. Although the wording of DR54 only applies to the pointer
984 // variant of this rule, the intent is clearly for it to apply to the this
985 // conversion as well.
986
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000987 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000988 if (!DestReference) {
989 return TC_NotApplicable;
990 }
991 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000992 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000993 // We know the left side is an lvalue reference, so we can suggest a reason.
994 msg = diag::err_bad_cxx_cast_rvalue;
995 return TC_NotApplicable;
996 }
997
998 QualType DestPointee = DestReference->getPointeeType();
999
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001000 return TryStaticDowncast(Self,
1001 Self.Context.getCanonicalType(SrcExpr->getType()),
1002 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001003 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1004 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001005}
1006
1007/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1008TryCastResult
1009TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001010 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001011 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001012 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001013 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1014 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1015 // is a class derived from B, if a valid standard conversion from "pointer
1016 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1017 // class of D.
1018 // In addition, DR54 clarifies that the base must be accessible in the
1019 // current context.
1020
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001021 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001022 if (!DestPointer) {
1023 return TC_NotApplicable;
1024 }
1025
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001026 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001027 if (!SrcPointer) {
1028 msg = diag::err_bad_static_cast_pointer_nonpointer;
1029 return TC_NotApplicable;
1030 }
1031
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001032 return TryStaticDowncast(Self,
1033 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1034 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001035 CStyle, OpRange, SrcType, DestType, msg, Kind,
1036 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001037}
1038
1039/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1040/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001041/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001042TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001043TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001044 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001045 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001046 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001047 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +00001048 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1049 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001050 return TC_NotApplicable;
1051
Sebastian Redl9f831db2009-07-25 15:41:38 +00001052 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001053 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001054 return TC_NotApplicable;
1055 }
1056
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001057 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001058 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001059 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1060 return TC_NotApplicable;
1061 }
1062
1063 // Target type does derive from source type. Now we're serious. If an error
1064 // appears now, it's not ignored.
1065 // This may not be entirely in line with the standard. Take for example:
1066 // struct A {};
1067 // struct B : virtual A {
1068 // B(A&);
1069 // };
Mike Stump11289f42009-09-09 15:08:12 +00001070 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001071 // void f()
1072 // {
1073 // (void)static_cast<const B&>(*((A*)0));
1074 // }
1075 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1076 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1077 // However, both GCC and Comeau reject this example, and accepting it would
1078 // mean more complex code if we're to preserve the nice error message.
1079 // FIXME: Being 100% compliant here would be nice to have.
1080
1081 // Must preserve cv, as always, unless we're in C-style mode.
1082 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001083 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001084 return TC_Failed;
1085 }
1086
1087 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1088 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1089 // that it builds the paths in reverse order.
1090 // To sum up: record all paths to the base and build a nice string from
1091 // them. Use it to spice up the error message.
1092 if (!Paths.isRecordingPaths()) {
1093 Paths.clear();
1094 Paths.setRecordingPaths(true);
1095 Self.IsDerivedFrom(DestType, SrcType, Paths);
1096 }
1097 std::string PathDisplayStr;
1098 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001099 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001100 PI != PE; ++PI) {
1101 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1102 // We haven't displayed a path to this particular base
1103 // class subobject yet.
1104 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001105 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1106 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001107 EI != EE; ++EI)
1108 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001109 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001110 }
1111 }
1112
1113 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001114 << QualType(SrcType).getUnqualifiedType()
1115 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001116 << PathDisplayStr << OpRange;
1117 msg = 0;
1118 return TC_Failed;
1119 }
1120
1121 if (Paths.getDetectedVirtual() != 0) {
1122 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1123 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1124 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1125 msg = 0;
1126 return TC_Failed;
1127 }
1128
John McCallfe9cf0a2011-02-14 23:21:33 +00001129 if (!CStyle) {
1130 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1131 SrcType, DestType,
1132 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001133 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001134 case Sema::AR_accessible:
1135 case Sema::AR_delayed: // be optimistic
1136 case Sema::AR_dependent: // be optimistic
1137 break;
1138
1139 case Sema::AR_inaccessible:
1140 msg = 0;
1141 return TC_Failed;
1142 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001143 }
1144
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001145 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001146 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001147 return TC_Success;
1148}
1149
1150/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1151/// C++ 5.2.9p9 is valid:
1152///
1153/// An rvalue of type "pointer to member of D of type cv1 T" can be
1154/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1155/// where B is a base class of D [...].
1156///
1157TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001158TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001159 QualType DestType, bool CStyle,
1160 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001161 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001162 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001163 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001164 if (!DestMemPtr)
1165 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001166
1167 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001168 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001169 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001170 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001171 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001172 FoundOverload)) {
1173 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1174 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1175 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1176 WasOverloadedFunction = true;
1177 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001178 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001179
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001180 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001181 if (!SrcMemPtr) {
1182 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1183 return TC_NotApplicable;
1184 }
1185
1186 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001187 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1188 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001189 return TC_NotApplicable;
1190
1191 // B base of D
1192 QualType SrcClass(SrcMemPtr->getClass(), 0);
1193 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001194 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001195 /*DetectVirtual=*/true);
1196 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1197 return TC_NotApplicable;
1198 }
1199
1200 // 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 +00001201 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001202 Paths.clear();
1203 Paths.setRecordingPaths(true);
1204 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1205 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001206 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001207 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1208 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1209 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1210 msg = 0;
1211 return TC_Failed;
1212 }
1213
1214 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1215 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1216 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1217 msg = 0;
1218 return TC_Failed;
1219 }
1220
John McCallfe9cf0a2011-02-14 23:21:33 +00001221 if (!CStyle) {
1222 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1223 DestClass, SrcClass,
1224 Paths.front(),
1225 diag::err_upcast_to_inaccessible_base)) {
1226 case Sema::AR_accessible:
1227 case Sema::AR_delayed:
1228 case Sema::AR_dependent:
1229 // Optimistically assume that the delayed and dependent cases
1230 // will work out.
1231 break;
1232
1233 case Sema::AR_inaccessible:
1234 msg = 0;
1235 return TC_Failed;
1236 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001237 }
1238
Douglas Gregorc934bc82010-03-07 23:24:59 +00001239 if (WasOverloadedFunction) {
1240 // Resolve the address of the overloaded function again, this time
1241 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001242 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001243 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001244 true,
1245 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001246 if (!Fn) {
1247 msg = 0;
1248 return TC_Failed;
1249 }
1250
John McCall16df1e52010-03-30 21:47:33 +00001251 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001252 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001253 msg = 0;
1254 return TC_Failed;
1255 }
1256 }
1257
Anders Carlssonb78feca2010-04-24 19:22:20 +00001258 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001259 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001260 return TC_Success;
1261}
1262
1263/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1264/// is valid:
1265///
1266/// An expression e can be explicitly converted to a type T using a
1267/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1268TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001269TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001270 Sema::CheckedConversionKind CCK,
1271 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001272 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001273 if (DestType->isRecordType()) {
1274 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1275 diag::err_bad_dynamic_cast_incomplete)) {
1276 msg = 0;
1277 return TC_Failed;
1278 }
1279 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001280
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001281 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1282 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001283 = (CCK == Sema::CCK_CStyleCast)
1284 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1285 : (CCK == Sema::CCK_FunctionalCast)
1286 ? InitializationKind::CreateFunctionalCast(OpRange)
1287 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001288 Expr *SrcExprRaw = SrcExpr.get();
1289 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001290
1291 // At this point of CheckStaticCast, if the destination is a reference,
1292 // or the expression is an overload expression this has to work.
1293 // There is no other way that works.
1294 // On the other hand, if we're checking a C-style cast, we've still got
1295 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001296 bool CStyle
1297 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001298 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001299 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001300
John McCalldadc5752010-08-24 06:29:42 +00001301 ExprResult Result
John Wiegley01296292011-04-08 18:41:53 +00001302 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001303 if (Result.isInvalid()) {
1304 msg = 0;
1305 return TC_Failed;
1306 }
1307
Douglas Gregorb33eed02010-04-16 22:09:46 +00001308 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001309 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001310 else
John McCalle3027922010-08-25 11:45:40 +00001311 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001312
John Wiegley01296292011-04-08 18:41:53 +00001313 SrcExpr = move(Result);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001314 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001315}
1316
1317/// TryConstCast - See if a const_cast from source to destination is allowed,
1318/// and perform it if it is.
1319static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1320 bool CStyle, unsigned &msg) {
1321 DestType = Self.Context.getCanonicalType(DestType);
1322 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001323 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1324 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001325 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1326 // is C-style, static_cast might find a way, so we simply suggest a
1327 // message and tell the parent to keep searching.
1328 msg = diag::err_bad_cxx_cast_rvalue;
1329 return TC_NotApplicable;
1330 }
1331
1332 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1333 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1334 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1335 SrcType = Self.Context.getPointerType(SrcType);
1336 }
1337
1338 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1339 // the rules for const_cast are the same as those used for pointers.
1340
John McCall0e704f72010-05-18 09:35:29 +00001341 if (!DestType->isPointerType() &&
1342 !DestType->isMemberPointerType() &&
1343 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001344 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1345 // was a reference type, we converted it to a pointer above.
1346 // The status of rvalue references isn't entirely clear, but it looks like
1347 // conversion to them is simply invalid.
1348 // C++ 5.2.11p3: For two pointer types [...]
1349 if (!CStyle)
1350 msg = diag::err_bad_const_cast_dest;
1351 return TC_NotApplicable;
1352 }
1353 if (DestType->isFunctionPointerType() ||
1354 DestType->isMemberFunctionPointerType()) {
1355 // Cannot cast direct function pointers.
1356 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1357 // T is the ultimate pointee of source and target type.
1358 if (!CStyle)
1359 msg = diag::err_bad_const_cast_dest;
1360 return TC_NotApplicable;
1361 }
1362 SrcType = Self.Context.getCanonicalType(SrcType);
1363
1364 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1365 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001366 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1367 // in multi-level pointers may change, but the level count must be the same,
1368 // as must be the final pointee type.
1369 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001370 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001371 Qualifiers SrcQuals, DestQuals;
1372 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1373 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1374
1375 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1376 // the other qualifiers (e.g., address spaces) are identical.
1377 SrcQuals.removeCVRQualifiers();
1378 DestQuals.removeCVRQualifiers();
1379 if (SrcQuals != DestQuals)
1380 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001381 }
1382
1383 // Since we're dealing in canonical types, the remainder must be the same.
1384 if (SrcType != DestType)
1385 return TC_NotApplicable;
1386
1387 return TC_Success;
1388}
1389
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001390// Checks for undefined behavior in reinterpret_cast.
1391// The cases that is checked for is:
1392// *reinterpret_cast<T*>(&a)
1393// reinterpret_cast<T&>(a)
1394// where accessing 'a' as type 'T' will result in undefined behavior.
1395void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1396 bool IsDereference,
1397 SourceRange Range) {
1398 unsigned DiagID = IsDereference ?
1399 diag::warn_pointer_indirection_from_incompatible_type :
1400 diag::warn_undefined_reinterpret_cast;
1401
1402 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00001403 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001404 return;
1405 }
1406
1407 QualType SrcTy, DestTy;
1408 if (IsDereference) {
1409 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1410 return;
1411 }
1412 SrcTy = SrcType->getPointeeType();
1413 DestTy = DestType->getPointeeType();
1414 } else {
1415 if (!DestType->getAs<ReferenceType>()) {
1416 return;
1417 }
1418 SrcTy = SrcType;
1419 DestTy = DestType->getPointeeType();
1420 }
1421
1422 // Cast is compatible if the types are the same.
1423 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1424 return;
1425 }
1426 // or one of the types is a char or void type
1427 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1428 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1429 return;
1430 }
1431 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001432 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001433 return;
1434 }
1435
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001436 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001437 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1438 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1439 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1440 return;
1441 }
1442 }
1443
1444 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1445}
Douglas Gregor1beec452011-03-12 01:48:56 +00001446
John Wiegley01296292011-04-08 18:41:53 +00001447static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001448 QualType DestType, bool CStyle,
1449 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001450 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001451 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001452 bool IsLValueCast = false;
1453
Sebastian Redl9f831db2009-07-25 15:41:38 +00001454 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001455 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001456
1457 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001458 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1459 if (SrcType == Self.Context.OverloadTy) {
John McCall50a2c2c2011-10-11 23:14:30 +00001460 // ... unless foo<int> resolves to an lvalue unambiguously.
1461 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1462 // like it?
1463 ExprResult SingleFunctionExpr = SrcExpr;
1464 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1465 SingleFunctionExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001466 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall50a2c2c2011-10-11 23:14:30 +00001467 ) && SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001468 SrcExpr = move(SingleFunctionExpr);
1469 SrcType = SrcExpr.get()->getType();
John McCall50a2c2c2011-10-11 23:14:30 +00001470 } else {
Douglas Gregorb491ed32011-02-19 21:32:49 +00001471 return TC_NotApplicable;
John McCall50a2c2c2011-10-11 23:14:30 +00001472 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001473 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001474
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001475 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001476 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00001477 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001478 // Cannot cast non-lvalue to lvalue reference type. See the similar
1479 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001480 msg = diag::err_bad_cxx_cast_rvalue;
1481 return TC_NotApplicable;
1482 }
1483
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001484 if (!CStyle) {
1485 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1486 /*isDereference=*/false, OpRange);
1487 }
1488
Sebastian Redl9f831db2009-07-25 15:41:38 +00001489 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1490 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1491 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001492
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001493 const char *inappropriate = 0;
1494 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001495 case OK_Ordinary:
1496 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001497 case OK_BitField: inappropriate = "bit-field"; break;
1498 case OK_VectorComponent: inappropriate = "vector element"; break;
1499 case OK_ObjCProperty: inappropriate = "property expression"; break;
1500 }
1501 if (inappropriate) {
1502 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1503 << inappropriate << DestType
1504 << OpRange << SrcExpr.get()->getSourceRange();
1505 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001506 return TC_NotApplicable;
1507 }
1508
Sebastian Redl9f831db2009-07-25 15:41:38 +00001509 // This code does this transformation for the checked types.
1510 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1511 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001512
Douglas Gregor51954272010-07-13 23:17:26 +00001513 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001514 }
1515
1516 // Canonicalize source for comparison.
1517 SrcType = Self.Context.getCanonicalType(SrcType);
1518
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001519 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1520 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001521 if (DestMemPtr && SrcMemPtr) {
1522 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1523 // can be explicitly converted to an rvalue of type "pointer to member
1524 // of Y of type T2" if T1 and T2 are both function types or both object
1525 // types.
1526 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1527 SrcMemPtr->getPointeeType()->isFunctionType())
1528 return TC_NotApplicable;
1529
1530 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1531 // constness.
1532 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1533 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001534 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1535 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001536 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001537 return TC_Failed;
1538 }
1539
Charles Davisebab1ed2010-08-16 05:30:44 +00001540 // Don't allow casting between member pointers of different sizes.
1541 if (Self.Context.getTypeSize(DestMemPtr) !=
1542 Self.Context.getTypeSize(SrcMemPtr)) {
1543 msg = diag::err_bad_cxx_cast_member_pointer_size;
1544 return TC_Failed;
1545 }
1546
Sebastian Redl9f831db2009-07-25 15:41:38 +00001547 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001548 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001549 return TC_Success;
1550 }
1551
1552 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001553 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001554 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1555 // type large enough to hold it. A value of std::nullptr_t can be
1556 // converted to an integral type; the conversion has the same meaning
1557 // and validity as a conversion of (void*)0 to the integral type.
1558 if (Self.Context.getTypeSize(SrcType) >
1559 Self.Context.getTypeSize(DestType)) {
1560 msg = diag::err_bad_reinterpret_cast_small_int;
1561 return TC_Failed;
1562 }
John McCalle3027922010-08-25 11:45:40 +00001563 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001564 return TC_Success;
1565 }
1566
Anders Carlsson570af5d2009-09-16 19:19:43 +00001567 bool destIsVector = DestType->isVectorType();
1568 bool srcIsVector = SrcType->isVectorType();
1569 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001570 // FIXME: Should this also apply to floating point types?
1571 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1572 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001573
1574 // Check if this is a cast between a vector and something else.
1575 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1576 !(srcIsVector && destIsVector))
1577 return TC_NotApplicable;
1578
1579 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001580 if (Self.Context.getTypeSize(SrcType)
1581 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001582 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001583 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001584 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001585
1586 if (destIsScalar)
1587 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1588 else if (srcIsScalar)
1589 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1590 else
1591 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1592
1593 return TC_Failed;
1594 }
1595
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001596 bool destIsPtr = DestType->isAnyPointerType() ||
1597 DestType->isBlockPointerType();
1598 bool srcIsPtr = SrcType->isAnyPointerType() ||
1599 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001600 if (!destIsPtr && !srcIsPtr) {
1601 // Except for std::nullptr_t->integer and lvalue->reference, which are
1602 // handled above, at least one of the two arguments must be a pointer.
1603 return TC_NotApplicable;
1604 }
1605
1606 if (SrcType == DestType) {
1607 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1608 // restrictions, a cast to the same type is allowed. The intent is not
1609 // entirely clear here, since all other paragraphs explicitly forbid casts
1610 // to the same type. However, the behavior of compilers is pretty consistent
1611 // on this point: allow same-type conversion if the involved types are
1612 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001613 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001614 return TC_Success;
1615 }
1616
Douglas Gregor6972a622010-06-16 00:35:25 +00001617 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001618 assert(srcIsPtr && "One type must be a pointer");
1619 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001620 // type large enough to hold it; except in Microsoft mode, where the
1621 // integral type size doesn't matter.
1622 if ((Self.Context.getTypeSize(SrcType) >
1623 Self.Context.getTypeSize(DestType)) &&
Francois Pichet0706d202011-09-17 17:15:52 +00001624 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001625 msg = diag::err_bad_reinterpret_cast_small_int;
1626 return TC_Failed;
1627 }
John McCalle3027922010-08-25 11:45:40 +00001628 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001629 return TC_Success;
1630 }
1631
Douglas Gregorb90df602010-06-16 00:17:44 +00001632 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001633 assert(destIsPtr && "One type must be a pointer");
1634 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1635 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001636 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1637 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001638 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001639 return TC_Success;
1640 }
1641
1642 if (!destIsPtr || !srcIsPtr) {
1643 // With the valid non-pointer conversions out of the way, we can be even
1644 // more stringent.
1645 return TC_NotApplicable;
1646 }
1647
1648 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1649 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001650 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1651 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001652 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001653 return TC_Failed;
1654 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001655
1656 // Cannot convert between block pointers and Objective-C object pointers.
1657 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1658 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1659 return TC_NotApplicable;
1660
John McCall9320b872011-09-09 05:25:32 +00001661 if (IsLValueCast) {
1662 Kind = CK_LValueBitCast;
1663 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001664 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001665 } else if (DestType->isBlockPointerType()) {
1666 if (!SrcType->isBlockPointerType()) {
1667 Kind = CK_AnyPointerToBlockPointerCast;
1668 } else {
1669 Kind = CK_BitCast;
1670 }
1671 } else {
1672 Kind = CK_BitCast;
1673 }
1674
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001675 // Any pointer can be cast to an Objective-C pointer type with a C-style
1676 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001677 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001678 return TC_Success;
1679 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001680
Sebastian Redl9f831db2009-07-25 15:41:38 +00001681 // Not casting away constness, so the only remaining check is for compatible
1682 // pointer categories.
1683
1684 if (SrcType->isFunctionPointerType()) {
1685 if (DestType->isFunctionPointerType()) {
1686 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1687 // a pointer to a function of a different type.
1688 return TC_Success;
1689 }
1690
1691 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1692 // an object type or vice versa is conditionally-supported.
1693 // Compilers support it in C++03 too, though, because it's necessary for
1694 // casting the return value of dlsym() and GetProcAddress().
1695 // FIXME: Conditionally-supported behavior should be configurable in the
1696 // TargetInfo or similar.
1697 if (!Self.getLangOptions().CPlusPlus0x)
1698 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1699 return TC_Success;
1700 }
1701
1702 if (DestType->isFunctionPointerType()) {
1703 // See above.
1704 if (!Self.getLangOptions().CPlusPlus0x)
1705 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1706 return TC_Success;
1707 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001708
Sebastian Redl9f831db2009-07-25 15:41:38 +00001709 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1710 // a pointer to an object of different type.
1711 // Void pointers are not specified, but supported by every compiler out there.
1712 // So we finish by allowing everything that remains - it's got to be two
1713 // object pointers.
1714 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001715}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001716
John McCall9776e432011-10-06 23:25:11 +00001717void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
1718 // Handle placeholders.
1719 if (isPlaceholder()) {
1720 // C-style casts can resolve __unknown_any types.
1721 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1722 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1723 SrcExpr.get(), Kind,
1724 ValueKind, BasePath);
1725 return;
1726 }
John McCallb50451a2011-10-05 07:41:44 +00001727
John McCall9776e432011-10-06 23:25:11 +00001728 checkNonOverloadPlaceholders();
1729 if (SrcExpr.isInvalid())
1730 return;
John McCalla072f5d2011-10-17 17:42:19 +00001731 }
John McCall9776e432011-10-06 23:25:11 +00001732
1733 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00001734 // This test is outside everything else because it's the only case where
1735 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00001736 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00001737 Kind = CK_ToVoid;
1738
John McCall9776e432011-10-06 23:25:11 +00001739 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001740 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1741 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00001742 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00001743 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00001744 if (SrcExpr.isInvalid())
1745 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001746 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001747
John McCall9776e432011-10-06 23:25:11 +00001748 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1749 if (SrcExpr.isInvalid())
John McCallb50451a2011-10-05 07:41:44 +00001750 return;
John McCallb50451a2011-10-05 07:41:44 +00001751
1752 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00001753 }
1754
Sebastian Redl9f831db2009-07-25 15:41:38 +00001755 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb50451a2011-10-05 07:41:44 +00001756 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1757 assert(Kind == CK_Dependent);
1758 return;
John McCall8cb679e2010-11-15 09:13:47 +00001759 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00001760
John McCall50a2c2c2011-10-11 23:14:30 +00001761 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1762 !isPlaceholder(BuiltinType::Overload)) {
John McCallb50451a2011-10-05 07:41:44 +00001763 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1764 if (SrcExpr.isInvalid())
1765 return;
John Wiegley01296292011-04-08 18:41:53 +00001766 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001767
John McCall3aef3d82011-04-10 19:13:55 +00001768 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00001769 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00001770 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00001771 && (SrcExpr.get()->getType()->isIntegerType()
1772 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00001773 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00001774 return;
John McCall3aef3d82011-04-10 19:13:55 +00001775 }
1776
Sebastian Redl9f831db2009-07-25 15:41:38 +00001777 // C++ [expr.cast]p5: The conversions performed by
1778 // - a const_cast,
1779 // - a static_cast,
1780 // - a static_cast followed by a const_cast,
1781 // - a reinterpret_cast, or
1782 // - a reinterpret_cast followed by a const_cast,
1783 // can be performed using the cast notation of explicit type conversion.
1784 // [...] If a conversion can be interpreted in more than one of the ways
1785 // listed above, the interpretation that appears first in the list is used,
1786 // even if a cast resulting from that interpretation is ill-formed.
1787 // In plain language, this means trying a const_cast ...
1788 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb50451a2011-10-05 07:41:44 +00001789 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1790 /*CStyle*/true, msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001791 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001792 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001793
John McCall31168b02011-06-15 23:02:42 +00001794 Sema::CheckedConversionKind CCK
1795 = FunctionalStyle? Sema::CCK_FunctionalCast
1796 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001797 if (tcr == TC_NotApplicable) {
1798 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00001799 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1800 msg, Kind, BasePath);
1801 if (SrcExpr.isInvalid())
1802 return;
1803
Sebastian Redl9f831db2009-07-25 15:41:38 +00001804 if (tcr == TC_NotApplicable) {
1805 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00001806 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1807 OpRange, msg, Kind);
1808 if (SrcExpr.isInvalid())
1809 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001810 }
1811 }
1812
John McCallb50451a2011-10-05 07:41:44 +00001813 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1814 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00001815
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001816 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00001817 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001818 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00001819 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1820 DestType,
1821 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001822 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001823
Richard Trieu70d14f52011-04-16 01:09:30 +00001824 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001825 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001826
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001827 } else {
John McCallb50451a2011-10-05 07:41:44 +00001828 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1829 OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001830 }
John McCallb50451a2011-10-05 07:41:44 +00001831 } else if (Kind == CK_BitCast) {
1832 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001833 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001834
John McCallb50451a2011-10-05 07:41:44 +00001835 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00001836 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00001837 SrcExpr = ExprError();
1838}
1839
John McCall9776e432011-10-06 23:25:11 +00001840/// Check the semantics of a C-style cast operation, in C.
1841void CastOperation::CheckCStyleCast() {
1842 assert(!Self.getLangOptions().CPlusPlus);
1843
1844 // Handle placeholders.
1845 if (isPlaceholder()) {
1846 // C-style casts can resolve __unknown_any types.
1847 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1848 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1849 SrcExpr.get(), Kind,
1850 ValueKind, BasePath);
1851 return;
1852 }
1853
John McCall50a2c2c2011-10-11 23:14:30 +00001854 // We allow overloads in C, but we don't allow them to be resolved
1855 // by anything except calls.
1856 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
John McCall9776e432011-10-06 23:25:11 +00001857 if (SrcExpr.isInvalid())
1858 return;
1859 }
1860
1861 assert(!isPlaceholder());
1862
1863 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1864 // type needs to be scalar.
1865 if (DestType->isVoidType()) {
1866 // We don't necessarily do lvalue-to-rvalue conversions on this.
1867 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1868 if (SrcExpr.isInvalid())
1869 return;
1870
1871 // Cast to void allows any expr type.
1872 Kind = CK_ToVoid;
1873 return;
1874 }
1875
1876 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1877 if (SrcExpr.isInvalid())
1878 return;
1879 QualType SrcType = SrcExpr.get()->getType();
1880
1881 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1882 diag::err_typecheck_cast_to_incomplete)) {
1883 SrcExpr = ExprError();
1884 return;
1885 }
1886
1887 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1888 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1889
1890 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1891 // GCC struct/union extension: allow cast to self.
1892 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1893 << DestType << SrcExpr.get()->getSourceRange();
1894 Kind = CK_NoOp;
1895 return;
1896 }
1897
1898 // GCC's cast to union extension.
1899 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1900 RecordDecl *RD = DestRecordTy->getDecl();
1901 RecordDecl::field_iterator Field, FieldEnd;
1902 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1903 Field != FieldEnd; ++Field) {
1904 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1905 !Field->isUnnamedBitfield()) {
1906 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1907 << SrcExpr.get()->getSourceRange();
1908 break;
1909 }
1910 }
1911 if (Field == FieldEnd) {
1912 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1913 << SrcType << SrcExpr.get()->getSourceRange();
1914 SrcExpr = ExprError();
1915 return;
1916 }
1917 Kind = CK_ToUnion;
1918 return;
1919 }
1920
1921 // Reject any other conversions to non-scalar types.
1922 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1923 << DestType << SrcExpr.get()->getSourceRange();
1924 SrcExpr = ExprError();
1925 return;
1926 }
1927
1928 // The type we're casting to is known to be a scalar or vector.
1929
1930 // Require the operand to be a scalar or vector.
1931 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1932 Self.Diag(SrcExpr.get()->getExprLoc(),
1933 diag::err_typecheck_expect_scalar_operand)
1934 << SrcType << SrcExpr.get()->getSourceRange();
1935 SrcExpr = ExprError();
1936 return;
1937 }
1938
1939 if (DestType->isExtVectorType()) {
1940 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1941 return;
1942 }
1943
1944 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1945 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1946 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1947 Kind = CK_VectorSplat;
1948 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1949 SrcExpr = ExprError();
1950 }
1951 return;
1952 }
1953
1954 if (SrcType->isVectorType()) {
1955 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1956 SrcExpr = ExprError();
1957 return;
1958 }
1959
1960 // The source and target types are both scalars, i.e.
1961 // - arithmetic types (fundamental, enum, and complex)
1962 // - all kinds of pointers
1963 // Note that member pointers were filtered out with C++, above.
1964
1965 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
1966 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
1967 SrcExpr = ExprError();
1968 return;
1969 }
1970
1971 // If either type is a pointer, the other type has to be either an
1972 // integer or a pointer.
1973 if (!DestType->isArithmeticType()) {
1974 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
1975 Self.Diag(SrcExpr.get()->getExprLoc(),
1976 diag::err_cast_pointer_from_non_pointer_int)
1977 << SrcType << SrcExpr.get()->getSourceRange();
1978 SrcExpr = ExprError();
1979 return;
1980 }
1981 } else if (!SrcType->isArithmeticType()) {
1982 if (!DestType->isIntegralType(Self.Context) &&
1983 DestType->isArithmeticType()) {
1984 Self.Diag(SrcExpr.get()->getLocStart(),
1985 diag::err_cast_pointer_to_non_pointer_int)
1986 << SrcType << SrcExpr.get()->getSourceRange();
1987 SrcExpr = ExprError();
1988 return;
1989 }
1990 }
1991
1992 // ARC imposes extra restrictions on casts.
1993 if (Self.getLangOptions().ObjCAutoRefCount) {
1994 checkObjCARCConversion(Sema::CCK_CStyleCast);
1995 if (SrcExpr.isInvalid())
1996 return;
1997
1998 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
1999 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2000 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2001 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2002 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2003 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2004 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2005 Self.Diag(SrcExpr.get()->getLocStart(),
2006 diag::err_typecheck_incompatible_ownership)
2007 << SrcType << DestType << Sema::AA_Casting
2008 << SrcExpr.get()->getSourceRange();
2009 return;
2010 }
2011 }
2012 }
2013 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2014 Self.Diag(SrcExpr.get()->getLocStart(),
2015 diag::err_arc_convesion_of_weak_unavailable)
2016 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2017 SrcExpr = ExprError();
2018 return;
2019 }
2020 }
2021
2022 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2023 if (SrcExpr.isInvalid())
2024 return;
2025
2026 if (Kind == CK_BitCast)
2027 checkCastAlign();
2028}
2029
2030ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2031 TypeSourceInfo *CastTypeInfo,
2032 SourceLocation RPLoc,
2033 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002034 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2035 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2036 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2037
John McCall9776e432011-10-06 23:25:11 +00002038 if (getLangOptions().CPlusPlus) {
2039 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false);
2040 } else {
2041 Op.CheckCStyleCast();
2042 }
2043
John McCallb50451a2011-10-05 07:41:44 +00002044 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002045 return ExprError();
2046
John McCallb50451a2011-10-05 07:41:44 +00002047 return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
2048 Op.Kind, Op.SrcExpr.take(), &Op.BasePath,
2049 CastTypeInfo, LPLoc, RPLoc));
2050}
2051
2052ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2053 SourceLocation LPLoc,
2054 Expr *CastExpr,
2055 SourceLocation RPLoc) {
2056 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2057 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2058 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2059
John McCall9776e432011-10-06 23:25:11 +00002060 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true);
John McCallb50451a2011-10-05 07:41:44 +00002061 if (Op.SrcExpr.isInvalid())
2062 return ExprError();
2063
2064 return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2065 Op.ValueKind, CastTypeInfo,
2066 Op.DestRange.getBegin(),
2067 Op.Kind, Op.SrcExpr.take(),
2068 &Op.BasePath, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002069}