blob: 46b5b45306485dbb50ea8cdd3a2a6b8b8cb510b6 [file] [log] [blame]
John McCalld8d3ced2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl26d85b12008-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 McCalld8d3ced2011-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 Redl26d85b12008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCall437da052013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000025#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000026#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000027using namespace clang;
28
Douglas Gregor8e960432010-11-08 03:40:48 +000029
Douglas Gregor8e960432010-11-08 03:40:48 +000030
Sebastian Redl9cc11e72009-07-25 15:41:38 +000031enum TryCastResult {
32 TC_NotApplicable, ///< The cast method is not applicable.
33 TC_Success, ///< The cast method is appropriate and successful.
34 TC_Failed ///< The cast method is appropriate, but failed. A
35 ///< diagnostic has been emitted.
36};
37
38enum CastType {
39 CT_Const, ///< const_cast
40 CT_Static, ///< static_cast
41 CT_Reinterpret, ///< reinterpret_cast
42 CT_Dynamic, ///< dynamic_cast
43 CT_CStyle, ///< (Type)expr
44 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000045};
46
John McCallb45ae252011-10-05 07:41:44 +000047namespace {
48 struct CastOperation {
49 CastOperation(Sema &S, QualType destType, ExprResult src)
50 : Self(S), SrcExpr(src), DestType(destType),
51 ResultType(destType.getNonLValueExprType(S.Context)),
52 ValueKind(Expr::getValueKindForType(destType)),
John McCall5acb0c92011-10-17 18:40:02 +000053 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCalla180f042011-10-06 23:25:11 +000054
55 if (const BuiltinType *placeholder =
56 src.get()->getType()->getAsPlaceholderType()) {
57 PlaceholderKind = placeholder->getKind();
58 } else {
59 PlaceholderKind = (BuiltinType::Kind) 0;
60 }
61 }
Douglas Gregor8e960432010-11-08 03:40:48 +000062
John McCallb45ae252011-10-05 07:41:44 +000063 Sema &Self;
64 ExprResult SrcExpr;
65 QualType DestType;
66 QualType ResultType;
67 ExprValueKind ValueKind;
68 CastKind Kind;
John McCalla180f042011-10-06 23:25:11 +000069 BuiltinType::Kind PlaceholderKind;
John McCallb45ae252011-10-05 07:41:44 +000070 CXXCastPath BasePath;
John McCall5acb0c92011-10-17 18:40:02 +000071 bool IsARCUnbridgedCast;
Douglas Gregor8e960432010-11-08 03:40:48 +000072
John McCallb45ae252011-10-05 07:41:44 +000073 SourceRange OpRange;
74 SourceRange DestRange;
Douglas Gregor8e960432010-11-08 03:40:48 +000075
John McCalla180f042011-10-06 23:25:11 +000076 // Top-level semantics-checking routines.
John McCallb45ae252011-10-05 07:41:44 +000077 void CheckConstCast();
78 void CheckReinterpretCast();
Richard Smithc8d7f582011-11-29 22:48:16 +000079 void CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +000080 void CheckDynamicCast();
Sebastian Redl6dc00f62012-02-12 18:41:05 +000081 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCalla180f042011-10-06 23:25:11 +000082 void CheckCStyleCast();
83
John McCall5acb0c92011-10-17 18:40:02 +000084 /// Complete an apparently-successful cast operation that yields
85 /// the given expression.
86 ExprResult complete(CastExpr *castExpr) {
87 // If this is an unbridged cast, wrap the result in an implicit
88 // cast that yields the unbridged-cast placeholder type.
89 if (IsARCUnbridgedCast) {
90 castExpr = ImplicitCastExpr::Create(Self.Context,
91 Self.Context.ARCUnbridgedCastTy,
92 CK_Dependent, castExpr, 0,
93 castExpr->getValueKind());
94 }
95 return Self.Owned(castExpr);
96 }
97
John McCalla180f042011-10-06 23:25:11 +000098 // Internal convenience methods.
99
100 /// Try to handle the given placeholder expression kind. Return
101 /// true if the source expression has the appropriate placeholder
102 /// kind. A placeholder can only be claimed once.
103 bool claimPlaceholder(BuiltinType::Kind K) {
104 if (PlaceholderKind != K) return false;
105
106 PlaceholderKind = (BuiltinType::Kind) 0;
107 return true;
108 }
109
110 bool isPlaceholder() const {
111 return PlaceholderKind != 0;
112 }
113 bool isPlaceholder(BuiltinType::Kind K) const {
114 return PlaceholderKind == K;
115 }
John McCallb45ae252011-10-05 07:41:44 +0000116
117 void checkCastAlign() {
118 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
119 }
120
121 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000122 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall5acb0c92011-10-17 18:40:02 +0000123
John McCallb45ae252011-10-05 07:41:44 +0000124 Expr *src = SrcExpr.get();
John McCall5acb0c92011-10-17 18:40:02 +0000125 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
126 Sema::ACR_unbridged)
127 IsARCUnbridgedCast = true;
John McCallb45ae252011-10-05 07:41:44 +0000128 SrcExpr = src;
129 }
John McCalla180f042011-10-06 23:25:11 +0000130
131 /// Check for and handle non-overload placeholder expressions.
132 void checkNonOverloadPlaceholders() {
133 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
134 return;
135
136 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
137 if (SrcExpr.isInvalid())
138 return;
139 PlaceholderKind = (BuiltinType::Kind) 0;
140 }
John McCallb45ae252011-10-05 07:41:44 +0000141 };
142}
Sebastian Redl37d6de32008-11-08 13:00:26 +0000143
John McCallf85e1932011-06-15 23:02:42 +0000144static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000146
147// The Try functions attempt a specific way of casting. If they succeed, they
148// return TC_Success. If their way of casting is not appropriate for the given
149// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
150// to emit if no other way succeeds. If their way of casting is appropriate but
151// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
152// they emit a specialized diagnostic.
153// All diagnostics returned by these functions must expect the same three
154// arguments:
155// %0: Cast Type (a value from the CastType enumeration)
156// %1: Source Type
157// %2: Destination Type
158static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000159 QualType DestType, bool CStyle,
160 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +0000161 CXXCastPath &BasePath,
162 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000163static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000164 QualType DestType, bool CStyle,
165 const SourceRange &OpRange,
166 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000167 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000168 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000169static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170 QualType DestType, bool CStyle,
171 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000172 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000173 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000174 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000175static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000177 const SourceRange &OpRange,
178 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000179 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000180 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000181 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000182static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000183 QualType SrcType,
184 QualType DestType,bool CStyle,
185 const SourceRange &OpRange,
186 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000187 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000188 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000189
John Wiegley429bb272011-04-08 18:41:53 +0000190static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000191 QualType DestType,
192 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000193 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000194 unsigned &msg, CastKind &Kind,
195 bool ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000196static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000197 QualType DestType,
198 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000199 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000200 unsigned &msg, CastKind &Kind,
201 CXXCastPath &BasePath,
202 bool ListInitialization);
Richard Smith41cb3d92013-06-14 22:27:52 +0000203static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
204 QualType DestType, bool CStyle,
205 unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000206static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000207 QualType DestType, bool CStyle,
208 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000209 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000210 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000211
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000212
Sebastian Redl26d85b12008-11-05 21:50:06 +0000213/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000214ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000216 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000217 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000218 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000219 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000220
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000221 assert(!D.isInvalidType());
222
223 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
224 if (D.isInvalidType())
225 return ExprError();
226
David Blaikie4e4d0842012-03-11 07:00:24 +0000227 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000228 // Check that there are no default arguments (C++ only).
229 CheckExtraCXXDefaultArguments(D);
230 }
231
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000232 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCallc89724c2010-01-15 19:13:16 +0000233 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
234 SourceRange(LParenLoc, RParenLoc));
235}
236
John McCall60d7b3a2010-08-24 06:29:42 +0000237ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000238Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000239 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000240 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000241 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000242 QualType DestType = DestTInfo->getType();
243
Douglas Gregor9103bb22008-12-17 22:52:20 +0000244 // If the type is dependent, we won't do the semantic analysis now.
245 // FIXME: should we check this in a more fine-grained manner?
Eli Friedmanf91e86c2013-09-19 01:12:33 +0000246 bool TypeDependent = DestType->isDependentType() ||
247 Ex.get()->isTypeDependent() ||
248 Ex.get()->isValueDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000249
John McCallb45ae252011-10-05 07:41:44 +0000250 CastOperation Op(*this, DestType, E);
251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000253
Sebastian Redl26d85b12008-11-05 21:50:06 +0000254 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000255 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000256
257 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000258 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000259 Op.CheckConstCast();
260 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000261 return ExprError();
262 }
John McCall5acb0c92011-10-17 18:40:02 +0000263 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
264 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000265 OpLoc, Parens.getEnd(),
266 AngleBrackets));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000267
Anders Carlsson714179b2009-08-02 19:07:59 +0000268 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000269 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000270 Op.CheckDynamicCast();
271 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000272 return ExprError();
273 }
John McCall5acb0c92011-10-17 18:40:02 +0000274 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
275 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
276 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000277 OpLoc, Parens.getEnd(),
278 AngleBrackets));
Anders Carlsson714179b2009-08-02 19:07:59 +0000279 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000280 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000281 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000282 Op.CheckReinterpretCast();
283 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000284 return ExprError();
285 }
John McCall5acb0c92011-10-17 18:40:02 +0000286 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
287 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
288 0, DestTInfo, OpLoc,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000289 Parens.getEnd(),
290 AngleBrackets));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000291 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000292 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000293 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000294 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000295 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000296 return ExprError();
297 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000298
John McCall5acb0c92011-10-17 18:40:02 +0000299 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
300 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
301 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000302 OpLoc, Parens.getEnd(),
303 AngleBrackets));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000304 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000305 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306}
307
John McCall79ab2c82011-02-14 18:34:10 +0000308/// Try to diagnose a failed overloaded cast. Returns true if
309/// diagnostics were emitted.
310static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
311 SourceRange range, Expr *src,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000312 QualType destType,
313 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000314 switch (CT) {
315 // These cast kinds don't consider user-defined conversions.
316 case CT_Const:
317 case CT_Reinterpret:
318 case CT_Dynamic:
319 return false;
320
321 // These do.
322 case CT_Static:
323 case CT_CStyle:
324 case CT_Functional:
325 break;
326 }
327
328 QualType srcType = src->getType();
329 if (!destType->isRecordType() && !srcType->isRecordType())
330 return false;
331
332 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
333 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000334 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000335 range, listInitialization)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000336 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000337 listInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +0000338 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000339 InitializationSequence sequence(S, entity, initKind, src);
John McCall79ab2c82011-02-14 18:34:10 +0000340
Sebastian Redl383616c2011-06-05 12:23:28 +0000341 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000342 switch (sequence.getFailureKind()) {
343 default: return false;
344
345 case InitializationSequence::FK_ConstructorOverloadFailed:
346 case InitializationSequence::FK_UserConversionOverloadFailed:
347 break;
348 }
349
350 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
351
352 unsigned msg = 0;
353 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
354
355 switch (sequence.getFailedOverloadResult()) {
356 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000357 case OR_No_Viable_Function:
358 if (candidates.empty())
359 msg = diag::err_ovl_no_conversion_in_cast;
360 else
361 msg = diag::err_ovl_no_viable_conversion_in_cast;
362 howManyCandidates = OCD_AllCandidates;
363 break;
364
365 case OR_Ambiguous:
366 msg = diag::err_ovl_ambiguous_conversion_in_cast;
367 howManyCandidates = OCD_ViableCandidates;
368 break;
369
370 case OR_Deleted:
371 msg = diag::err_ovl_deleted_conversion_in_cast;
372 howManyCandidates = OCD_ViableCandidates;
373 break;
374 }
375
376 S.Diag(range.getBegin(), msg)
377 << CT << srcType << destType
378 << range << src->getSourceRange();
379
Ahmed Charles13a140c2012-02-25 11:00:22 +0000380 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall79ab2c82011-02-14 18:34:10 +0000381
382 return true;
383}
384
385/// Diagnose a failed cast.
386static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000387 SourceRange opRange, Expr *src, QualType destType,
388 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000389 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000390 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
391 listInitialization))
John McCall79ab2c82011-02-14 18:34:10 +0000392 return;
393
394 S.Diag(opRange.getBegin(), msg) << castType
395 << src->getType() << destType << opRange << src->getSourceRange();
396}
397
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000398/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
399/// this removes one level of indirection from both types, provided that they're
400/// the same kind of pointer (plain or to-member). Unlike the Sema function,
401/// this one doesn't care if the two pointers-to-member don't point into the
402/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000403static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000404 const PointerType *T1PtrType = T1->getAs<PointerType>(),
405 *T2PtrType = T2->getAs<PointerType>();
406 if (T1PtrType && T2PtrType) {
407 T1 = T1PtrType->getPointeeType();
408 T2 = T2PtrType->getPointeeType();
409 return true;
410 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000411 const ObjCObjectPointerType *T1ObjCPtrType =
412 T1->getAs<ObjCObjectPointerType>(),
413 *T2ObjCPtrType =
414 T2->getAs<ObjCObjectPointerType>();
415 if (T1ObjCPtrType) {
416 if (T2ObjCPtrType) {
417 T1 = T1ObjCPtrType->getPointeeType();
418 T2 = T2ObjCPtrType->getPointeeType();
419 return true;
420 }
421 else if (T2PtrType) {
422 T1 = T1ObjCPtrType->getPointeeType();
423 T2 = T2PtrType->getPointeeType();
424 return true;
425 }
426 }
427 else if (T2ObjCPtrType) {
428 if (T1PtrType) {
429 T2 = T2ObjCPtrType->getPointeeType();
430 T1 = T1PtrType->getPointeeType();
431 return true;
432 }
433 }
434
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000435 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
436 *T2MPType = T2->getAs<MemberPointerType>();
437 if (T1MPType && T2MPType) {
438 T1 = T1MPType->getPointeeType();
439 T2 = T2MPType->getPointeeType();
440 return true;
441 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000442
443 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
444 *T2BPType = T2->getAs<BlockPointerType>();
445 if (T1BPType && T2BPType) {
446 T1 = T1BPType->getPointeeType();
447 T2 = T2BPType->getPointeeType();
448 return true;
449 }
450
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000451 return false;
452}
453
Sebastian Redldb647282009-01-27 23:18:31 +0000454/// CastsAwayConstness - Check if the pointer conversion from SrcType to
455/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
456/// the cast checkers. Both arguments must denote pointer (possibly to member)
457/// types.
John McCallf85e1932011-06-15 23:02:42 +0000458///
459/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
460///
461/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000462static bool
John McCallf85e1932011-06-15 23:02:42 +0000463CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
464 bool CheckCVR, bool CheckObjCLifetime) {
465 // If the only checking we care about is for Objective-C lifetime qualifiers,
466 // and we're not in ARC mode, there's nothing to check.
467 if (!CheckCVR && CheckObjCLifetime &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000468 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000469 return false;
470
Sebastian Redldb647282009-01-27 23:18:31 +0000471 // Casting away constness is defined in C++ 5.2.11p8 with reference to
472 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
473 // the rules are non-trivial. So first we construct Tcv *...cv* as described
474 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000475 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
476 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000477 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000478 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
479 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000480 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000481
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000482 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
483 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000485
Douglas Gregord4c5f842011-04-15 17:59:54 +0000486 // Find the qualifiers. We only care about cvr-qualifiers for the
487 // purpose of this check, because other qualifiers (address spaces,
488 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000489 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000490 // Determine the relevant qualifiers at this level.
491 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000492 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000493 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000494
495 Qualifiers RetainedSrcQuals, RetainedDestQuals;
496 if (CheckCVR) {
497 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
498 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
499 }
500
501 if (CheckObjCLifetime &&
502 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
503 return true;
504
505 cv1.push_back(RetainedSrcQuals);
506 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000507 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000508 if (cv1.empty())
509 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000510
511 // Construct void pointers with those qualifiers (in reverse order of
512 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000513 QualType SrcConstruct = Self.Context.VoidTy;
514 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000515 ASTContext &Context = Self.Context;
Craig Topper163fbf82013-07-08 03:55:09 +0000516 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
517 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000518 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000519 SrcConstruct
520 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
521 DestConstruct
522 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000523 }
524
525 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000526 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000527 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000528 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
529 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000530}
531
Sebastian Redl26d85b12008-11-05 21:50:06 +0000532/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
533/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
534/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000535void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000536 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000537 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000538 else if (isPlaceholder())
539 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
540 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
541 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000542
John McCallb45ae252011-10-05 07:41:44 +0000543 QualType OrigSrcType = SrcExpr.get()->getType();
544 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000545
546 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
547 // or "pointer to cv void".
548
549 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000550 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000551 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000552 if (DestPointer) {
553 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000554 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000555 DestPointee = DestReference->getPointeeType();
556 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000557 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000558 << this->DestType << DestRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000559 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000560 return;
561 }
562
Ted Kremenek6217b802009-07-29 21:53:49 +0000563 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000564 if (DestPointee->isVoidType()) {
565 assert(DestPointer && "Reference to void is not possible");
566 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000567 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000568 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman2437c862013-07-26 23:47:47 +0000569 DestRange)) {
570 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000571 return;
Eli Friedman2437c862013-07-26 23:47:47 +0000572 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000573 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000574 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000575 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000576 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000577 return;
578 }
579
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000580 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
581 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000582 // an lvalue of a complete class type, [...]. If T is an rvalue reference
583 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000584 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000585 QualType SrcPointee;
586 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000587 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000588 SrcPointee = SrcPointer->getPointeeType();
589 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000590 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000591 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman2437c862013-07-26 23:47:47 +0000592 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000593 return;
594 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000595 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000596 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000597 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000598 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000599 }
600 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000601 } else {
602 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000603 }
604
Ted Kremenek6217b802009-07-29 21:53:49 +0000605 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000606 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000607 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000608 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman2437c862013-07-26 23:47:47 +0000609 SrcExpr.get())) {
610 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000611 return;
Eli Friedman2437c862013-07-26 23:47:47 +0000612 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000613 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000614 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000615 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman2437c862013-07-26 23:47:47 +0000616 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000617 return;
618 }
619
620 assert((DestPointer || DestReference) &&
621 "Bad destination non-ptr/ref slipped through.");
622 assert((DestRecord || DestPointee->isVoidType()) &&
623 "Bad destination pointee slipped through.");
624 assert(SrcRecord && "Bad source pointee slipped through.");
625
626 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
627 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000628 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000629 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000630 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000631 return;
632 }
633
634 // C++ 5.2.7p3: If the type of v is the same as the required result type,
635 // [except for cv].
636 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000637 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000638 return;
639 }
640
641 // C++ 5.2.7p5
642 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000643 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000644 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
645 OpRange.getBegin(), OpRange,
Eli Friedman2437c862013-07-26 23:47:47 +0000646 &BasePath)) {
647 SrcExpr = ExprError();
648 return;
649 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000650
John McCall2de56d12010-08-25 11:45:40 +0000651 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000652
653 // If we are casting to or through a virtual base class, we need a
654 // vtable.
655 if (Self.BasePathInvolvesVirtualBase(BasePath))
656 Self.MarkVTableUsed(OpRange.getBegin(),
657 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000658 return;
659 }
660
661 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000662 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000663 assert(SrcDecl && "Definition missing");
664 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000665 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000666 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman2437c862013-07-26 23:47:47 +0000667 SrcExpr = ExprError();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000668 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000669 Self.MarkVTableUsed(OpRange.getBegin(),
670 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000671
Arnaud A. de Grandmaison789d82a2013-08-01 08:28:32 +0000672 // dynamic_cast is not available with fno-rtti
673 if (!Self.getLangOpts().RTTI) {
674 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
675 SrcExpr = ExprError();
676 return;
677 }
678
Sebastian Redl26d85b12008-11-05 21:50:06 +0000679 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000680 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000681}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000682
683/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
684/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
685/// like this:
686/// const char *str = "literal";
687/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000688void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000689 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000690 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000691 else if (isPlaceholder())
692 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
693 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
694 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000695
696 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith41cb3d92013-06-14 22:27:52 +0000697 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman2437c862013-07-26 23:47:47 +0000698 && msg != 0) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000699 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000700 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000701 SrcExpr = ExprError();
702 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000703}
704
John McCall437da052013-03-22 02:58:14 +0000705/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
706/// or downcast between respective pointers or references.
707static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
708 QualType DestType,
709 SourceRange OpRange) {
710 QualType SrcType = SrcExpr->getType();
711 // When casting from pointer or reference, get pointee type; use original
712 // type otherwise.
713 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
714 const CXXRecordDecl *SrcRD =
715 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
716
John McCallfdb468f2013-03-27 00:03:48 +0000717 // Examining subobjects for records is only possible if the complete and
718 // valid definition is available. Also, template instantiation is not
719 // allowed here.
720 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCall437da052013-03-22 02:58:14 +0000721 return;
722
723 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
724
John McCallfdb468f2013-03-27 00:03:48 +0000725 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCall437da052013-03-22 02:58:14 +0000726 return;
727
728 enum {
729 ReinterpretUpcast,
730 ReinterpretDowncast
731 } ReinterpretKind;
732
733 CXXBasePaths BasePaths;
734
735 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
736 ReinterpretKind = ReinterpretUpcast;
737 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
738 ReinterpretKind = ReinterpretDowncast;
739 else
740 return;
741
742 bool VirtualBase = true;
743 bool NonZeroOffset = false;
John McCallfdb468f2013-03-27 00:03:48 +0000744 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCall437da052013-03-22 02:58:14 +0000745 E = BasePaths.end();
746 I != E; ++I) {
747 const CXXBasePath &Path = *I;
748 CharUnits Offset = CharUnits::Zero();
749 bool IsVirtual = false;
750 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
751 IElem != EElem; ++IElem) {
752 IsVirtual = IElem->Base->isVirtual();
753 if (IsVirtual)
754 break;
755 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
756 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallfdb468f2013-03-27 00:03:48 +0000757 // Don't check if any base has invalid declaration or has no definition
758 // since it has no layout info.
759 const CXXRecordDecl *Class = IElem->Class,
760 *ClassDefinition = Class->getDefinition();
761 if (Class->isInvalidDecl() || !ClassDefinition ||
762 !ClassDefinition->isCompleteDefinition())
763 return;
764
John McCall437da052013-03-22 02:58:14 +0000765 const ASTRecordLayout &DerivedLayout =
John McCallfdb468f2013-03-27 00:03:48 +0000766 Self.Context.getASTRecordLayout(Class);
John McCall437da052013-03-22 02:58:14 +0000767 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
768 }
769 if (!IsVirtual) {
770 // Don't warn if any path is a non-virtually derived base at offset zero.
771 if (Offset.isZero())
772 return;
773 // Offset makes sense only for non-virtual bases.
774 else
775 NonZeroOffset = true;
776 }
777 VirtualBase = VirtualBase && IsVirtual;
778 }
779
Andy Gibbsde7afe02013-06-19 13:33:37 +0000780 (void) NonZeroOffset; // Silence set but not used warning.
John McCall437da052013-03-22 02:58:14 +0000781 assert((VirtualBase || NonZeroOffset) &&
782 "Should have returned if has non-virtual base with zero offset");
783
784 QualType BaseType =
785 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
786 QualType DerivedType =
787 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
788
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000789 SourceLocation BeginLoc = OpRange.getBegin();
790 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000791 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000792 << OpRange;
793 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000794 << int(ReinterpretKind)
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000795 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCall437da052013-03-22 02:58:14 +0000796}
797
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000798/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
799/// valid.
800/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
801/// like this:
802/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000803void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000804 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000805 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000806 else
807 checkNonOverloadPlaceholders();
808 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
809 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000810
811 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000812 TryCastResult tcr =
813 TryReinterpretCast(Self, SrcExpr, DestType,
814 /*CStyle*/false, OpRange, msg, Kind);
815 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000816 {
John Wiegley429bb272011-04-08 18:41:53 +0000817 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
818 return;
819 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000820 //FIXME: &f<int>; is overloaded and resolvable
821 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000822 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000823 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000824 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000825
John McCall79ab2c82011-02-14 18:34:10 +0000826 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000827 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
828 DestType, /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000829 }
Eli Friedman2437c862013-07-26 23:47:47 +0000830 SrcExpr = ExprError();
John McCall437da052013-03-22 02:58:14 +0000831 } else if (tcr == TC_Success) {
832 if (Self.getLangOpts().ObjCAutoRefCount)
833 checkObjCARCConversion(Sema::CCK_OtherCast);
834 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCallf85e1932011-06-15 23:02:42 +0000835 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000836}
837
838
839/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
840/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
841/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000842void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000843 if (isPlaceholder()) {
844 checkNonOverloadPlaceholders();
845 if (SrcExpr.isInvalid())
846 return;
847 }
848
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000849 // This test is outside everything else because it's the only case where
850 // a non-lvalue-reference target type does not lead to decay.
851 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000852 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000853 Kind = CK_ToVoid;
854
855 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000856 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000857 false, // Decay Function to ptr
858 true, // Complain
859 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000860 if (SrcExpr.isInvalid())
861 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000862 }
John McCalla180f042011-10-06 23:25:11 +0000863
864 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000865 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000866 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000867
John McCall6dbba4f2011-10-11 23:14:30 +0000868 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
869 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000870 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
871 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
872 return;
873 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000874
875 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000876 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000877 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000878 Kind, BasePath, /*ListInitialization=*/false);
John McCallf85e1932011-06-15 23:02:42 +0000879 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000880 if (SrcExpr.isInvalid())
881 return;
882 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
883 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000884 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000885 << oe->getName() << DestType << OpRange
886 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000887 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000888 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000889 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
890 /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000891 }
Eli Friedman2437c862013-07-26 23:47:47 +0000892 SrcExpr = ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000893 } else if (tcr == TC_Success) {
894 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000895 checkCastAlign();
David Blaikie4e4d0842012-03-11 07:00:24 +0000896 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000897 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000898 } else if (Kind == CK_BitCast) {
899 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000900 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000901}
902
903/// TryStaticCast - Check if a static cast can be performed, and do so if
904/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
905/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000906static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000907 QualType DestType,
908 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000909 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000910 CastKind &Kind, CXXCastPath &BasePath,
911 bool ListInitialization) {
John McCallf85e1932011-06-15 23:02:42 +0000912 // Determine whether we have the semantics of a C-style cast.
913 bool CStyle
914 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
915
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000916 // The order the tests is not entirely arbitrary. There is one conversion
917 // that can be handled in two different ways. Given:
918 // struct A {};
919 // struct B : public A {
920 // B(); B(const A&);
921 // };
922 // const A &a = B();
923 // the cast static_cast<const B&>(a) could be seen as either a static
924 // reference downcast, or an explicit invocation of the user-defined
925 // conversion using B's conversion constructor.
926 // DR 427 specifies that the downcast is to be applied here.
927
928 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
929 // Done outside this function.
930
931 TryCastResult tcr;
932
933 // C++ 5.2.9p5, reference downcast.
934 // See the function for details.
935 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000936 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
937 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000938 if (tcr != TC_NotApplicable)
939 return tcr;
940
Douglas Gregordc843f22011-01-22 00:06:57 +0000941 // C++0x [expr.static.cast]p3:
942 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
943 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000944 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
945 BasePath, msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000946 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000947 return tcr;
948
949 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
950 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000951 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000952 Kind, ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000953 if (SrcExpr.isInvalid())
954 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000955 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000956 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000957
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000958 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
959 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
960 // conversions, subject to further restrictions.
961 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
962 // of qualification conversions impossible.
963 // In the CStyle case, the earlier attempt to const_cast should have taken
964 // care of reverse qualification conversions.
965
John Wiegley429bb272011-04-08 18:41:53 +0000966 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000967
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000968 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000969 // converted to an integral type. [...] A value of a scoped enumeration type
970 // can also be explicitly converted to a floating-point type [...].
971 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
972 if (Enum->getDecl()->isScoped()) {
973 if (DestType->isBooleanType()) {
974 Kind = CK_IntegralToBoolean;
975 return TC_Success;
976 } else if (DestType->isIntegralType(Self.Context)) {
977 Kind = CK_IntegralCast;
978 return TC_Success;
979 } else if (DestType->isRealFloatingType()) {
980 Kind = CK_IntegralToFloating;
981 return TC_Success;
982 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000983 }
984 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000985
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000986 // Reverse integral promotion/conversion. All such conversions are themselves
987 // again integral promotions or conversions and are thus already handled by
988 // p2 (TryDirectInitialization above).
989 // (Note: any data loss warnings should be suppressed.)
990 // The exception is the reverse of enum->integer, i.e. integer->enum (and
991 // enum->enum). See also C++ 5.2.9p7.
992 // The same goes for reverse floating point promotion/conversion and
993 // floating-integral conversions. Again, only floating->enum is relevant.
994 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000995 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000996 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000997 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000998 } else if (SrcType->isRealFloatingType()) {
999 Kind = CK_FloatingToIntegral;
1000 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +00001001 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001002 }
1003
1004 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1005 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001006 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001007 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001008 if (tcr != TC_NotApplicable)
1009 return tcr;
1010
1011 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1012 // conversion. C++ 5.2.9p9 has additional information.
1013 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001014 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +00001015 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001016 if (tcr != TC_NotApplicable)
1017 return tcr;
1018
1019 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1020 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1021 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +00001022 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001023 QualType SrcPointee = SrcPointer->getPointeeType();
1024 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001026 QualType DestPointee = DestPointer->getPointeeType();
1027 if (DestPointee->isIncompleteOrObjectType()) {
1028 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +00001029 // to a qualifier violation. Note that we permit Objective-C lifetime
1030 // and GC qualifier mismatches here.
1031 if (!CStyle) {
1032 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1033 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1034 DestPointeeQuals.removeObjCGCAttr();
1035 DestPointeeQuals.removeObjCLifetime();
1036 SrcPointeeQuals.removeObjCGCAttr();
1037 SrcPointeeQuals.removeObjCLifetime();
1038 if (DestPointeeQuals != SrcPointeeQuals &&
1039 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1040 msg = diag::err_bad_cxx_cast_qualifiers_away;
1041 return TC_Failed;
1042 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001043 }
John McCall2de56d12010-08-25 11:45:40 +00001044 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001045 return TC_Success;
1046 }
1047 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +00001048 else if (DestType->isObjCObjectPointerType()) {
1049 // allow both c-style cast and static_cast of objective-c pointers as
1050 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +00001051 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001052 return TC_Success;
1053 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001054 else if (CStyle && DestType->isBlockPointerType()) {
1055 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +00001056 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001057 return TC_Success;
1058 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001059 }
1060 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001061 // Allow arbitray objective-c pointer conversion with static casts.
1062 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001063 DestType->isObjCObjectPointerType()) {
1064 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001065 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +00001066 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001067
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001068 // We tried everything. Everything! Nothing works! :-(
1069 return TC_NotApplicable;
1070}
1071
1072/// Tests whether a conversion according to N2844 is valid.
1073TryCastResult
1074TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001075 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1076 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +00001077 // C++0x [expr.static.cast]p3:
1078 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1079 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +00001080 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001081 if (!R)
1082 return TC_NotApplicable;
1083
Douglas Gregordc843f22011-01-22 00:06:57 +00001084 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001085 return TC_NotApplicable;
1086
1087 // Because we try the reference downcast before this function, from now on
1088 // this is the only cast possibility, so we issue an error if we fail now.
1089 // FIXME: Should allow casting away constness if CStyle.
1090 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00001091 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00001092 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001093 QualType FromType = SrcExpr->getType();
1094 QualType ToType = R->getPointeeType();
1095 if (CStyle) {
1096 FromType = FromType.getUnqualifiedType();
1097 ToType = ToType.getUnqualifiedType();
1098 }
1099
Douglas Gregor393896f2009-11-05 13:06:35 +00001100 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001101 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +00001102 DerivedToBase, ObjCConversion,
1103 ObjCLifetimeConversion)
1104 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001105 msg = diag::err_bad_lvalue_to_rvalue_cast;
1106 return TC_Failed;
1107 }
1108
Douglas Gregor88b22a42011-01-25 16:13:26 +00001109 if (DerivedToBase) {
1110 Kind = CK_DerivedToBase;
1111 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1112 /*DetectVirtual=*/true);
1113 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1114 return TC_NotApplicable;
1115
1116 Self.BuildBasePathArray(Paths, BasePath);
1117 } else
1118 Kind = CK_NoOp;
1119
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001120 return TC_Success;
1121}
1122
1123/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1124TryCastResult
1125TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1126 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001127 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001128 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001129 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1130 // cast to type "reference to cv2 D", where D is a class derived from B,
1131 // if a valid standard conversion from "pointer to D" to "pointer to B"
1132 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1133 // In addition, DR54 clarifies that the base must be accessible in the
1134 // current context. Although the wording of DR54 only applies to the pointer
1135 // variant of this rule, the intent is clearly for it to apply to the this
1136 // conversion as well.
1137
Ted Kremenek6217b802009-07-29 21:53:49 +00001138 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001139 if (!DestReference) {
1140 return TC_NotApplicable;
1141 }
1142 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001143 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001144 // We know the left side is an lvalue reference, so we can suggest a reason.
1145 msg = diag::err_bad_cxx_cast_rvalue;
1146 return TC_NotApplicable;
1147 }
1148
1149 QualType DestPointee = DestReference->getPointeeType();
1150
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001151 return TryStaticDowncast(Self,
1152 Self.Context.getCanonicalType(SrcExpr->getType()),
1153 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001154 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1155 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001156}
1157
1158/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1159TryCastResult
1160TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001161 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001162 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001163 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001164 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1165 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1166 // is a class derived from B, if a valid standard conversion from "pointer
1167 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1168 // class of D.
1169 // In addition, DR54 clarifies that the base must be accessible in the
1170 // current context.
1171
Ted Kremenek6217b802009-07-29 21:53:49 +00001172 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001173 if (!DestPointer) {
1174 return TC_NotApplicable;
1175 }
1176
Ted Kremenek6217b802009-07-29 21:53:49 +00001177 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001178 if (!SrcPointer) {
1179 msg = diag::err_bad_static_cast_pointer_nonpointer;
1180 return TC_NotApplicable;
1181 }
1182
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001183 return TryStaticDowncast(Self,
1184 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1185 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001186 CStyle, OpRange, SrcType, DestType, msg, Kind,
1187 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001188}
1189
1190/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1191/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001192/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001193TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001194TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001195 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001196 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001197 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001198 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregord10099e2012-05-04 16:32:21 +00001199 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1200 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001201 return TC_NotApplicable;
1202
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001203 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001204 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001205 return TC_NotApplicable;
1206 }
1207
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001208 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001209 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001210 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1211 return TC_NotApplicable;
1212 }
1213
1214 // Target type does derive from source type. Now we're serious. If an error
1215 // appears now, it's not ignored.
1216 // This may not be entirely in line with the standard. Take for example:
1217 // struct A {};
1218 // struct B : virtual A {
1219 // B(A&);
1220 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001221 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001222 // void f()
1223 // {
1224 // (void)static_cast<const B&>(*((A*)0));
1225 // }
1226 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1227 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1228 // However, both GCC and Comeau reject this example, and accepting it would
1229 // mean more complex code if we're to preserve the nice error message.
1230 // FIXME: Being 100% compliant here would be nice to have.
1231
1232 // Must preserve cv, as always, unless we're in C-style mode.
1233 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001234 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001235 return TC_Failed;
1236 }
1237
1238 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1239 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1240 // that it builds the paths in reverse order.
1241 // To sum up: record all paths to the base and build a nice string from
1242 // them. Use it to spice up the error message.
1243 if (!Paths.isRecordingPaths()) {
1244 Paths.clear();
1245 Paths.setRecordingPaths(true);
1246 Self.IsDerivedFrom(DestType, SrcType, Paths);
1247 }
1248 std::string PathDisplayStr;
1249 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001250 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001251 PI != PE; ++PI) {
1252 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1253 // We haven't displayed a path to this particular base
1254 // class subobject yet.
1255 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001256 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1257 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001258 EI != EE; ++EI)
1259 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001260 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001261 }
1262 }
1263
1264 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001265 << QualType(SrcType).getUnqualifiedType()
1266 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001267 << PathDisplayStr << OpRange;
1268 msg = 0;
1269 return TC_Failed;
1270 }
1271
1272 if (Paths.getDetectedVirtual() != 0) {
1273 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1274 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1275 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1276 msg = 0;
1277 return TC_Failed;
1278 }
1279
John McCall417d39f2011-02-14 23:21:33 +00001280 if (!CStyle) {
1281 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1282 SrcType, DestType,
1283 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001284 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001285 case Sema::AR_accessible:
1286 case Sema::AR_delayed: // be optimistic
1287 case Sema::AR_dependent: // be optimistic
1288 break;
1289
1290 case Sema::AR_inaccessible:
1291 msg = 0;
1292 return TC_Failed;
1293 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001294 }
1295
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001296 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001297 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001298 return TC_Success;
1299}
1300
1301/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1302/// C++ 5.2.9p9 is valid:
1303///
1304/// An rvalue of type "pointer to member of D of type cv1 T" can be
1305/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1306/// where B is a base class of D [...].
1307///
1308TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001309TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001310 QualType DestType, bool CStyle,
1311 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001312 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001313 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001314 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001315 if (!DestMemPtr)
1316 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001317
1318 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001319 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001320 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001321 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001322 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001323 FoundOverload)) {
1324 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1325 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1326 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1327 WasOverloadedFunction = true;
1328 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001329 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001330
Ted Kremenek6217b802009-07-29 21:53:49 +00001331 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001332 if (!SrcMemPtr) {
1333 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1334 return TC_NotApplicable;
1335 }
1336
1337 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001338 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1339 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001340 return TC_NotApplicable;
1341
1342 // B base of D
1343 QualType SrcClass(SrcMemPtr->getClass(), 0);
1344 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001345 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001346 /*DetectVirtual=*/true);
1347 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1348 return TC_NotApplicable;
1349 }
1350
1351 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +00001352 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001353 Paths.clear();
1354 Paths.setRecordingPaths(true);
1355 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1356 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001357 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001358 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1359 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1360 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1361 msg = 0;
1362 return TC_Failed;
1363 }
1364
1365 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1366 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1367 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1368 msg = 0;
1369 return TC_Failed;
1370 }
1371
John McCall417d39f2011-02-14 23:21:33 +00001372 if (!CStyle) {
1373 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1374 DestClass, SrcClass,
1375 Paths.front(),
1376 diag::err_upcast_to_inaccessible_base)) {
1377 case Sema::AR_accessible:
1378 case Sema::AR_delayed:
1379 case Sema::AR_dependent:
1380 // Optimistically assume that the delayed and dependent cases
1381 // will work out.
1382 break;
1383
1384 case Sema::AR_inaccessible:
1385 msg = 0;
1386 return TC_Failed;
1387 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001388 }
1389
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001390 if (WasOverloadedFunction) {
1391 // Resolve the address of the overloaded function again, this time
1392 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001393 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001394 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001395 true,
1396 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001397 if (!Fn) {
1398 msg = 0;
1399 return TC_Failed;
1400 }
1401
John McCall6bb80172010-03-30 21:47:33 +00001402 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001403 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001404 msg = 0;
1405 return TC_Failed;
1406 }
1407 }
1408
Anders Carlssoncee22422010-04-24 19:22:20 +00001409 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001410 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001411 return TC_Success;
1412}
1413
1414/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1415/// is valid:
1416///
1417/// An expression e can be explicitly converted to a type T using a
1418/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1419TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001420TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001421 Sema::CheckedConversionKind CCK,
1422 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001423 CastKind &Kind, bool ListInitialization) {
Anders Carlssond851b372009-09-07 18:25:47 +00001424 if (DestType->isRecordType()) {
1425 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001426 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman860a3192012-06-16 02:19:17 +00001427 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001428 diag::err_allocation_of_abstract_type)) {
Anders Carlssond851b372009-09-07 18:25:47 +00001429 msg = 0;
1430 return TC_Failed;
1431 }
1432 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001433
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001434 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1435 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001436 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001437 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001438 ListInitialization)
John McCallf85e1932011-06-15 23:02:42 +00001439 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001440 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +00001441 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001442 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00001443 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor8e960432010-11-08 03:40:48 +00001444
1445 // At this point of CheckStaticCast, if the destination is a reference,
1446 // or the expression is an overload expression this has to work.
1447 // There is no other way that works.
1448 // On the other hand, if we're checking a C-style cast, we've still got
1449 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001450 bool CStyle
1451 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001452 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001453 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001454
Benjamin Kramer5354e772012-08-23 23:38:35 +00001455 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001456 if (Result.isInvalid()) {
1457 msg = 0;
1458 return TC_Failed;
1459 }
1460
Douglas Gregord6e44a32010-04-16 22:09:46 +00001461 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001462 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001463 else
John McCall2de56d12010-08-25 11:45:40 +00001464 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001465
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001466 SrcExpr = Result;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001467 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001468}
1469
1470/// TryConstCast - See if a const_cast from source to destination is allowed,
1471/// and perform it if it is.
Richard Smith41cb3d92013-06-14 22:27:52 +00001472static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1473 QualType DestType, bool CStyle,
1474 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001475 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith41cb3d92013-06-14 22:27:52 +00001476 QualType SrcType = SrcExpr.get()->getType();
1477 bool NeedToMaterializeTemporary = false;
1478
Douglas Gregor575d2a32011-01-22 00:19:52 +00001479 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith41cb3d92013-06-14 22:27:52 +00001480 // C++11 5.2.11p4:
1481 // if a pointer to T1 can be explicitly converted to the type "pointer to
1482 // T2" using a const_cast, then the following conversions can also be
1483 // made:
1484 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1485 // type T2 using the cast const_cast<T2&>;
1486 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1487 // type T2 using the cast const_cast<T2&&>; and
1488 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1489 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1490
1491 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001492 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1493 // is C-style, static_cast might find a way, so we simply suggest a
1494 // message and tell the parent to keep searching.
1495 msg = diag::err_bad_cxx_cast_rvalue;
1496 return TC_NotApplicable;
1497 }
1498
Richard Smith41cb3d92013-06-14 22:27:52 +00001499 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1500 if (!SrcType->isRecordType()) {
1501 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1502 // this is C-style, static_cast can do this.
1503 msg = diag::err_bad_cxx_cast_rvalue;
1504 return TC_NotApplicable;
1505 }
1506
1507 // Materialize the class prvalue so that the const_cast can bind a
1508 // reference to it.
1509 NeedToMaterializeTemporary = true;
1510 }
1511
John McCall993f43f2013-05-06 21:39:12 +00001512 // It's not completely clear under the standard whether we can
1513 // const_cast bit-field gl-values. Doing so would not be
1514 // intrinsically complicated, but for now, we say no for
1515 // consistency with other compilers and await the word of the
1516 // committee.
Richard Smith41cb3d92013-06-14 22:27:52 +00001517 if (SrcExpr.get()->refersToBitField()) {
John McCall993f43f2013-05-06 21:39:12 +00001518 msg = diag::err_bad_cxx_cast_bitfield;
1519 return TC_NotApplicable;
1520 }
1521
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001522 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1523 SrcType = Self.Context.getPointerType(SrcType);
1524 }
1525
1526 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1527 // the rules for const_cast are the same as those used for pointers.
1528
John McCalld425d2b2010-05-18 09:35:29 +00001529 if (!DestType->isPointerType() &&
1530 !DestType->isMemberPointerType() &&
1531 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001532 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1533 // was a reference type, we converted it to a pointer above.
1534 // The status of rvalue references isn't entirely clear, but it looks like
1535 // conversion to them is simply invalid.
1536 // C++ 5.2.11p3: For two pointer types [...]
1537 if (!CStyle)
1538 msg = diag::err_bad_const_cast_dest;
1539 return TC_NotApplicable;
1540 }
1541 if (DestType->isFunctionPointerType() ||
1542 DestType->isMemberFunctionPointerType()) {
1543 // Cannot cast direct function pointers.
1544 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1545 // T is the ultimate pointee of source and target type.
1546 if (!CStyle)
1547 msg = diag::err_bad_const_cast_dest;
1548 return TC_NotApplicable;
1549 }
1550 SrcType = Self.Context.getCanonicalType(SrcType);
1551
1552 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1553 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001554 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1555 // in multi-level pointers may change, but the level count must be the same,
1556 // as must be the final pointee type.
1557 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001558 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001559 Qualifiers SrcQuals, DestQuals;
1560 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1561 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1562
1563 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1564 // the other qualifiers (e.g., address spaces) are identical.
1565 SrcQuals.removeCVRQualifiers();
1566 DestQuals.removeCVRQualifiers();
1567 if (SrcQuals != DestQuals)
1568 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001569 }
1570
1571 // Since we're dealing in canonical types, the remainder must be the same.
1572 if (SrcType != DestType)
1573 return TC_NotApplicable;
1574
Richard Smith41cb3d92013-06-14 22:27:52 +00001575 if (NeedToMaterializeTemporary)
1576 // This is a const_cast from a class prvalue to an rvalue reference type.
1577 // Materialize a temporary to store the result of the conversion.
1578 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1579 SrcType, SrcExpr.take(), /*IsLValueReference*/ false,
1580 /*ExtendingDecl*/ 0);
1581
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001582 return TC_Success;
1583}
1584
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001585// Checks for undefined behavior in reinterpret_cast.
1586// The cases that is checked for is:
1587// *reinterpret_cast<T*>(&a)
1588// reinterpret_cast<T&>(a)
1589// where accessing 'a' as type 'T' will result in undefined behavior.
1590void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1591 bool IsDereference,
1592 SourceRange Range) {
1593 unsigned DiagID = IsDereference ?
1594 diag::warn_pointer_indirection_from_incompatible_type :
1595 diag::warn_undefined_reinterpret_cast;
1596
1597 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001598 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001599 return;
1600 }
1601
1602 QualType SrcTy, DestTy;
1603 if (IsDereference) {
1604 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1605 return;
1606 }
1607 SrcTy = SrcType->getPointeeType();
1608 DestTy = DestType->getPointeeType();
1609 } else {
1610 if (!DestType->getAs<ReferenceType>()) {
1611 return;
1612 }
1613 SrcTy = SrcType;
1614 DestTy = DestType->getPointeeType();
1615 }
1616
1617 // Cast is compatible if the types are the same.
1618 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1619 return;
1620 }
1621 // or one of the types is a char or void type
1622 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1623 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1624 return;
1625 }
1626 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001627 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001628 return;
1629 }
1630
Douglas Gregor575a1c92011-05-20 16:38:50 +00001631 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001632 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1633 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1634 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1635 return;
1636 }
1637 }
1638
1639 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1640}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001641
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001642static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1643 QualType DestType) {
1644 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanian0c252fa2012-12-13 00:42:06 +00001645 if (Self.Context.hasSameType(SrcType, DestType))
1646 return;
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001647 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1648 if (SrcPtrTy->isObjCSelType()) {
1649 QualType DT = DestType;
1650 if (isa<PointerType>(DestType))
1651 DT = DestType->getPointeeType();
1652 if (!DT.getUnqualifiedType()->isVoidType())
1653 Self.Diag(SrcExpr.get()->getExprLoc(),
1654 diag::warn_cast_pointer_from_sel)
1655 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1656 }
1657}
1658
David Blaikie9b29f4f2012-10-16 18:53:14 +00001659static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1660 const Expr *SrcExpr, QualType DestType,
1661 Sema &Self) {
1662 QualType SrcType = SrcExpr->getType();
1663
1664 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1665 // are not explicit design choices, but consistent with GCC's behavior.
1666 // Feel free to modify them if you've reason/evidence for an alternative.
1667 if (CStyle && SrcType->isIntegralType(Self.Context)
1668 && !SrcType->isBooleanType()
1669 && !SrcType->isEnumeralType()
1670 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremenek2628b442013-05-29 21:50:46 +00001671 && Self.Context.getTypeSize(DestType) >
1672 Self.Context.getTypeSize(SrcType)) {
1673 // Separate between casts to void* and non-void* pointers.
1674 // Some APIs use (abuse) void* for something like a user context,
1675 // and often that value is an integer even if it isn't a pointer itself.
1676 // Having a separate warning flag allows users to control the warning
1677 // for their workflow.
1678 unsigned Diag = DestType->isVoidPointerType() ?
1679 diag::warn_int_to_void_pointer_cast
1680 : diag::warn_int_to_pointer_cast;
1681 Self.Diag(Loc, Diag) << SrcType << DestType;
1682 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00001683}
1684
John Wiegley429bb272011-04-08 18:41:53 +00001685static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001686 QualType DestType, bool CStyle,
1687 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001688 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001689 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001690 bool IsLValueCast = false;
1691
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001692 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001693 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001694
1695 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001696 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1697 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001698 // ... unless foo<int> resolves to an lvalue unambiguously.
1699 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1700 // like it?
1701 ExprResult SingleFunctionExpr = SrcExpr;
1702 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1703 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001704 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001705 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001706 SrcExpr = SingleFunctionExpr;
John Wiegley429bb272011-04-08 18:41:53 +00001707 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001708 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001709 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001710 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001711 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001712
Ted Kremenek6217b802009-07-29 21:53:49 +00001713 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smith6850faf2012-04-29 08:24:44 +00001714 if (!SrcExpr.get()->isGLValue()) {
1715 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1716 // similar comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001717 msg = diag::err_bad_cxx_cast_rvalue;
1718 return TC_NotApplicable;
1719 }
1720
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001721 if (!CStyle) {
1722 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1723 /*isDereference=*/false, OpRange);
1724 }
1725
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001726 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1727 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1728 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001729
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001730 const char *inappropriate = 0;
1731 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001732 case OK_Ordinary:
1733 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001734 case OK_BitField: inappropriate = "bit-field"; break;
1735 case OK_VectorComponent: inappropriate = "vector element"; break;
1736 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001737 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1738 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001739 }
1740 if (inappropriate) {
1741 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1742 << inappropriate << DestType
1743 << OpRange << SrcExpr.get()->getSourceRange();
1744 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001745 return TC_NotApplicable;
1746 }
1747
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001748 // This code does this transformation for the checked types.
1749 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1750 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001751
Douglas Gregore39a3892010-07-13 23:17:26 +00001752 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001753 }
1754
1755 // Canonicalize source for comparison.
1756 SrcType = Self.Context.getCanonicalType(SrcType);
1757
Ted Kremenek6217b802009-07-29 21:53:49 +00001758 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1759 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001760 if (DestMemPtr && SrcMemPtr) {
1761 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1762 // can be explicitly converted to an rvalue of type "pointer to member
1763 // of Y of type T2" if T1 and T2 are both function types or both object
1764 // types.
1765 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1766 SrcMemPtr->getPointeeType()->isFunctionType())
1767 return TC_NotApplicable;
1768
1769 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1770 // constness.
1771 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1772 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001773 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1774 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001775 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001776 return TC_Failed;
1777 }
1778
Charles Davisf231df32010-08-16 05:30:44 +00001779 // Don't allow casting between member pointers of different sizes.
1780 if (Self.Context.getTypeSize(DestMemPtr) !=
1781 Self.Context.getTypeSize(SrcMemPtr)) {
1782 msg = diag::err_bad_cxx_cast_member_pointer_size;
1783 return TC_Failed;
1784 }
1785
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001786 // A valid member pointer cast.
John McCall4d4e5c12012-02-15 01:22:51 +00001787 assert(!IsLValueCast);
1788 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001789 return TC_Success;
1790 }
1791
1792 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001793 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001794 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1795 // type large enough to hold it. A value of std::nullptr_t can be
1796 // converted to an integral type; the conversion has the same meaning
1797 // and validity as a conversion of (void*)0 to the integral type.
1798 if (Self.Context.getTypeSize(SrcType) >
1799 Self.Context.getTypeSize(DestType)) {
1800 msg = diag::err_bad_reinterpret_cast_small_int;
1801 return TC_Failed;
1802 }
John McCall2de56d12010-08-25 11:45:40 +00001803 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001804 return TC_Success;
1805 }
1806
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001807 bool destIsVector = DestType->isVectorType();
1808 bool srcIsVector = SrcType->isVectorType();
1809 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001810 // FIXME: Should this also apply to floating point types?
1811 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1812 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001813
1814 // Check if this is a cast between a vector and something else.
1815 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1816 !(srcIsVector && destIsVector))
1817 return TC_NotApplicable;
1818
1819 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001820 if (Self.Context.getTypeSize(SrcType)
1821 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001822 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001823 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001824 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001825
1826 if (destIsScalar)
1827 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1828 else if (srcIsScalar)
1829 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1830 else
1831 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1832
1833 return TC_Failed;
1834 }
Chad Rosier41f44312012-02-03 02:54:37 +00001835
1836 if (SrcType == DestType) {
1837 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1838 // restrictions, a cast to the same type is allowed so long as it does not
1839 // cast away constness. In C++98, the intent was not entirely clear here,
1840 // since all other paragraphs explicitly forbid casts to the same type.
1841 // C++11 clarifies this case with p2.
1842 //
1843 // The only allowed types are: integral, enumeration, pointer, or
1844 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1845 Kind = CK_NoOp;
1846 TryCastResult Result = TC_NotApplicable;
1847 if (SrcType->isIntegralOrEnumerationType() ||
1848 SrcType->isAnyPointerType() ||
1849 SrcType->isMemberPointerType() ||
1850 SrcType->isBlockPointerType()) {
1851 Result = TC_Success;
1852 }
1853 return Result;
1854 }
1855
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001856 bool destIsPtr = DestType->isAnyPointerType() ||
1857 DestType->isBlockPointerType();
1858 bool srcIsPtr = SrcType->isAnyPointerType() ||
1859 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001860 if (!destIsPtr && !srcIsPtr) {
1861 // Except for std::nullptr_t->integer and lvalue->reference, which are
1862 // handled above, at least one of the two arguments must be a pointer.
1863 return TC_NotApplicable;
1864 }
1865
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001866 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001867 assert(srcIsPtr && "One type must be a pointer");
1868 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001869 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg649c6c52013-06-06 09:16:36 +00001870 // integral type size doesn't matter (except we don't allow bool).
1871 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1872 !DestType->isBooleanType();
Francois Pichet30aff5b2011-05-11 22:13:54 +00001873 if ((Self.Context.getTypeSize(SrcType) >
1874 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg649c6c52013-06-06 09:16:36 +00001875 !MicrosoftException) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001876 msg = diag::err_bad_reinterpret_cast_small_int;
1877 return TC_Failed;
1878 }
John McCall2de56d12010-08-25 11:45:40 +00001879 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001880 return TC_Success;
1881 }
1882
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001883 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001884 assert(destIsPtr && "One type must be a pointer");
David Blaikie9b29f4f2012-10-16 18:53:14 +00001885 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1886 Self);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001887 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1888 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001889 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1890 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001891 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001892 return TC_Success;
1893 }
1894
1895 if (!destIsPtr || !srcIsPtr) {
1896 // With the valid non-pointer conversions out of the way, we can be even
1897 // more stringent.
1898 return TC_NotApplicable;
1899 }
1900
1901 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1902 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001903 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1904 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001905 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001906 return TC_Failed;
1907 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001908
1909 // Cannot convert between block pointers and Objective-C object pointers.
1910 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1911 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1912 return TC_NotApplicable;
1913
John McCall1d9b3b22011-09-09 05:25:32 +00001914 if (IsLValueCast) {
1915 Kind = CK_LValueBitCast;
1916 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001917 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001918 } else if (DestType->isBlockPointerType()) {
1919 if (!SrcType->isBlockPointerType()) {
1920 Kind = CK_AnyPointerToBlockPointerCast;
1921 } else {
1922 Kind = CK_BitCast;
1923 }
1924 } else {
1925 Kind = CK_BitCast;
1926 }
1927
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001928 // Any pointer can be cast to an Objective-C pointer type with a C-style
1929 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001930 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001931 return TC_Success;
1932 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001933 if (CStyle)
1934 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1935
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001936 // Not casting away constness, so the only remaining check is for compatible
1937 // pointer categories.
1938
1939 if (SrcType->isFunctionPointerType()) {
1940 if (DestType->isFunctionPointerType()) {
1941 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1942 // a pointer to a function of a different type.
1943 return TC_Success;
1944 }
1945
1946 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1947 // an object type or vice versa is conditionally-supported.
1948 // Compilers support it in C++03 too, though, because it's necessary for
1949 // casting the return value of dlsym() and GetProcAddress().
1950 // FIXME: Conditionally-supported behavior should be configurable in the
1951 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001952 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001953 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001954 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1955 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001956 return TC_Success;
1957 }
1958
1959 if (DestType->isFunctionPointerType()) {
1960 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001961 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001962 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001963 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1964 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001965 return TC_Success;
1966 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001967
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001968 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1969 // a pointer to an object of different type.
1970 // Void pointers are not specified, but supported by every compiler out there.
1971 // So we finish by allowing everything that remains - it's got to be two
1972 // object pointers.
1973 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001974}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001975
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001976void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1977 bool ListInitialization) {
John McCalla180f042011-10-06 23:25:11 +00001978 // Handle placeholders.
1979 if (isPlaceholder()) {
1980 // C-style casts can resolve __unknown_any types.
1981 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1982 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1983 SrcExpr.get(), Kind,
1984 ValueKind, BasePath);
1985 return;
1986 }
John McCallb45ae252011-10-05 07:41:44 +00001987
John McCalla180f042011-10-06 23:25:11 +00001988 checkNonOverloadPlaceholders();
1989 if (SrcExpr.isInvalid())
1990 return;
John McCall4919dfd2011-10-17 17:42:19 +00001991 }
John McCalla180f042011-10-06 23:25:11 +00001992
1993 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001994 // This test is outside everything else because it's the only case where
1995 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001996 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001997 Kind = CK_ToVoid;
1998
John McCalla180f042011-10-06 23:25:11 +00001999 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00002000 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2001 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00002002 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00002003 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00002004 if (SrcExpr.isInvalid())
2005 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002006 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002007
John McCalla180f042011-10-06 23:25:11 +00002008 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
John McCallb45ae252011-10-05 07:41:44 +00002009 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00002010 }
2011
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002012 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedmanf91e86c2013-09-19 01:12:33 +00002013 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2014 SrcExpr.get()->isValueDependent()) {
John McCallb45ae252011-10-05 07:41:44 +00002015 assert(Kind == CK_Dependent);
2016 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00002017 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00002018
John McCall6dbba4f2011-10-11 23:14:30 +00002019 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2020 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00002021 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2022 if (SrcExpr.isInvalid())
2023 return;
John Wiegley429bb272011-04-08 18:41:53 +00002024 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002025
John McCallfb8721c2011-04-10 19:13:55 +00002026 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00002027 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00002028 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00002029 && (SrcExpr.get()->getType()->isIntegerType()
2030 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00002031 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00002032 return;
John McCallfb8721c2011-04-10 19:13:55 +00002033 }
2034
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002035 // C++ [expr.cast]p5: The conversions performed by
2036 // - a const_cast,
2037 // - a static_cast,
2038 // - a static_cast followed by a const_cast,
2039 // - a reinterpret_cast, or
2040 // - a reinterpret_cast followed by a const_cast,
2041 // can be performed using the cast notation of explicit type conversion.
2042 // [...] If a conversion can be interpreted in more than one of the ways
2043 // listed above, the interpretation that appears first in the list is used,
2044 // even if a cast resulting from that interpretation is ill-formed.
2045 // In plain language, this means trying a const_cast ...
2046 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith41cb3d92013-06-14 22:27:52 +00002047 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb45ae252011-10-05 07:41:44 +00002048 /*CStyle*/true, msg);
Richard Smith41cb3d92013-06-14 22:27:52 +00002049 if (SrcExpr.isInvalid())
2050 return;
Anders Carlssonda921fd2009-10-19 18:14:28 +00002051 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00002052 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00002053
John McCallf85e1932011-06-15 23:02:42 +00002054 Sema::CheckedConversionKind CCK
2055 = FunctionalStyle? Sema::CCK_FunctionalCast
2056 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002057 if (tcr == TC_NotApplicable) {
2058 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00002059 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002060 msg, Kind, BasePath, ListInitialization);
John McCallb45ae252011-10-05 07:41:44 +00002061 if (SrcExpr.isInvalid())
2062 return;
2063
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002064 if (tcr == TC_NotApplicable) {
2065 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00002066 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2067 OpRange, msg, Kind);
2068 if (SrcExpr.isInvalid())
2069 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002070 }
2071 }
2072
David Blaikie4e4d0842012-03-11 07:00:24 +00002073 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002074 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00002075
Nick Lewycky43328e92010-11-09 00:19:31 +00002076 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00002077 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00002078 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00002079 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2080 DestType,
2081 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00002082 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002083
Richard Trieu32ac00d2011-04-16 01:09:30 +00002084 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00002085 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00002086
Nick Lewycky43328e92010-11-09 00:19:31 +00002087 } else {
John McCallb45ae252011-10-05 07:41:44 +00002088 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002089 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregor8e960432010-11-08 03:40:48 +00002090 }
John McCallb45ae252011-10-05 07:41:44 +00002091 } else if (Kind == CK_BitCast) {
2092 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00002093 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002094
John McCallb45ae252011-10-05 07:41:44 +00002095 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00002096 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002097 SrcExpr = ExprError();
2098}
2099
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002100/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2101/// non-matching type. Such as enum function call to int, int call to
2102/// pointer; etc. Cast to 'void' is an exception.
2103static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2104 QualType DestType) {
2105 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2106 SrcExpr.get()->getExprLoc())
2107 == DiagnosticsEngine::Ignored)
2108 return;
2109
2110 if (!isa<CallExpr>(SrcExpr.get()))
2111 return;
2112
2113 QualType SrcType = SrcExpr.get()->getType();
2114 if (DestType.getUnqualifiedType()->isVoidType())
2115 return;
2116 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2117 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2118 return;
2119 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2120 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2121 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2122 return;
2123 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2124 return;
2125 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2126 return;
2127 if (SrcType->isComplexType() && DestType->isComplexType())
2128 return;
2129 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2130 return;
2131
2132 Self.Diag(SrcExpr.get()->getExprLoc(),
2133 diag::warn_bad_function_cast)
2134 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2135}
2136
John McCalla180f042011-10-06 23:25:11 +00002137/// Check the semantics of a C-style cast operation, in C.
2138void CastOperation::CheckCStyleCast() {
David Blaikie4e4d0842012-03-11 07:00:24 +00002139 assert(!Self.getLangOpts().CPlusPlus);
John McCalla180f042011-10-06 23:25:11 +00002140
John McCall5acb0c92011-10-17 18:40:02 +00002141 // C-style casts can resolve __unknown_any types.
2142 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2143 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2144 SrcExpr.get(), Kind,
2145 ValueKind, BasePath);
2146 return;
2147 }
John McCalla180f042011-10-06 23:25:11 +00002148
2149 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2150 // type needs to be scalar.
2151 if (DestType->isVoidType()) {
2152 // We don't necessarily do lvalue-to-rvalue conversions on this.
2153 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2154 if (SrcExpr.isInvalid())
2155 return;
2156
2157 // Cast to void allows any expr type.
2158 Kind = CK_ToVoid;
2159 return;
2160 }
2161
2162 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2163 if (SrcExpr.isInvalid())
2164 return;
2165 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00002166
John McCall5acb0c92011-10-17 18:40:02 +00002167 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00002168
2169 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2170 diag::err_typecheck_cast_to_incomplete)) {
2171 SrcExpr = ExprError();
2172 return;
2173 }
2174
2175 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2176 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2177
2178 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2179 // GCC struct/union extension: allow cast to self.
2180 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2181 << DestType << SrcExpr.get()->getSourceRange();
2182 Kind = CK_NoOp;
2183 return;
2184 }
2185
2186 // GCC's cast to union extension.
2187 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2188 RecordDecl *RD = DestRecordTy->getDecl();
2189 RecordDecl::field_iterator Field, FieldEnd;
2190 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2191 Field != FieldEnd; ++Field) {
2192 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2193 !Field->isUnnamedBitfield()) {
2194 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2195 << SrcExpr.get()->getSourceRange();
2196 break;
2197 }
2198 }
2199 if (Field == FieldEnd) {
2200 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2201 << SrcType << SrcExpr.get()->getSourceRange();
2202 SrcExpr = ExprError();
2203 return;
2204 }
2205 Kind = CK_ToUnion;
2206 return;
2207 }
2208
2209 // Reject any other conversions to non-scalar types.
2210 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2211 << DestType << SrcExpr.get()->getSourceRange();
2212 SrcExpr = ExprError();
2213 return;
2214 }
2215
2216 // The type we're casting to is known to be a scalar or vector.
2217
2218 // Require the operand to be a scalar or vector.
2219 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2220 Self.Diag(SrcExpr.get()->getExprLoc(),
2221 diag::err_typecheck_expect_scalar_operand)
2222 << SrcType << SrcExpr.get()->getSourceRange();
2223 SrcExpr = ExprError();
2224 return;
2225 }
2226
2227 if (DestType->isExtVectorType()) {
2228 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2229 return;
2230 }
2231
2232 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2233 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2234 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2235 Kind = CK_VectorSplat;
2236 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2237 SrcExpr = ExprError();
2238 }
2239 return;
2240 }
2241
2242 if (SrcType->isVectorType()) {
2243 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2244 SrcExpr = ExprError();
2245 return;
2246 }
2247
2248 // The source and target types are both scalars, i.e.
2249 // - arithmetic types (fundamental, enum, and complex)
2250 // - all kinds of pointers
2251 // Note that member pointers were filtered out with C++, above.
2252
2253 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2254 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2255 SrcExpr = ExprError();
2256 return;
2257 }
2258
2259 // If either type is a pointer, the other type has to be either an
2260 // integer or a pointer.
2261 if (!DestType->isArithmeticType()) {
2262 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2263 Self.Diag(SrcExpr.get()->getExprLoc(),
2264 diag::err_cast_pointer_from_non_pointer_int)
2265 << SrcType << SrcExpr.get()->getSourceRange();
2266 SrcExpr = ExprError();
2267 return;
2268 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00002269 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2270 DestType, Self);
John McCalla180f042011-10-06 23:25:11 +00002271 } else if (!SrcType->isArithmeticType()) {
2272 if (!DestType->isIntegralType(Self.Context) &&
2273 DestType->isArithmeticType()) {
2274 Self.Diag(SrcExpr.get()->getLocStart(),
2275 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002276 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002277 SrcExpr = ExprError();
2278 return;
2279 }
2280 }
2281
Joey Gouly19dbb202013-01-23 11:56:20 +00002282 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2283 if (DestType->isHalfType()) {
2284 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2285 << DestType << SrcExpr.get()->getSourceRange();
2286 SrcExpr = ExprError();
2287 return;
2288 }
Joey Gouly19dbb202013-01-23 11:56:20 +00002289 }
2290
John McCalla180f042011-10-06 23:25:11 +00002291 // ARC imposes extra restrictions on casts.
David Blaikie4e4d0842012-03-11 07:00:24 +00002292 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCalla180f042011-10-06 23:25:11 +00002293 checkObjCARCConversion(Sema::CCK_CStyleCast);
2294 if (SrcExpr.isInvalid())
2295 return;
2296
2297 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2298 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2299 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2300 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2301 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2302 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2303 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2304 Self.Diag(SrcExpr.get()->getLocStart(),
2305 diag::err_typecheck_incompatible_ownership)
2306 << SrcType << DestType << Sema::AA_Casting
2307 << SrcExpr.get()->getSourceRange();
2308 return;
2309 }
2310 }
2311 }
2312 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2313 Self.Diag(SrcExpr.get()->getLocStart(),
2314 diag::err_arc_convesion_of_weak_unavailable)
2315 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2316 SrcExpr = ExprError();
2317 return;
2318 }
2319 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00002320 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002321 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCalla180f042011-10-06 23:25:11 +00002322 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2323 if (SrcExpr.isInvalid())
2324 return;
2325
2326 if (Kind == CK_BitCast)
2327 checkCastAlign();
2328}
2329
2330ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2331 TypeSourceInfo *CastTypeInfo,
2332 SourceLocation RPLoc,
2333 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002334 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2335 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2336 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2337
David Blaikie4e4d0842012-03-11 07:00:24 +00002338 if (getLangOpts().CPlusPlus) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002339 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2340 isa<InitListExpr>(CastExpr));
John McCalla180f042011-10-06 23:25:11 +00002341 } else {
2342 Op.CheckCStyleCast();
2343 }
2344
John McCallb45ae252011-10-05 07:41:44 +00002345 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002346 return ExprError();
2347
John McCall5acb0c92011-10-17 18:40:02 +00002348 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2349 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2350 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002351}
2352
2353ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2354 SourceLocation LPLoc,
2355 Expr *CastExpr,
2356 SourceLocation RPLoc) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002357 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb45ae252011-10-05 07:41:44 +00002358 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2359 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2360 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2361
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002362 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb45ae252011-10-05 07:41:44 +00002363 if (Op.SrcExpr.isInvalid())
2364 return ExprError();
Daniel Jaspera770a4d2012-07-16 08:05:07 +00002365
2366 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
Enea Zaffanella1245a542013-09-07 05:49:53 +00002367 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002368
John McCall5acb0c92011-10-17 18:40:02 +00002369 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedmancdd4b782013-08-15 22:02:56 +00002370 Op.ValueKind, CastTypeInfo, Op.Kind,
2371 Op.SrcExpr.take(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002372}