blob: dff06b7f0a24f9af1bec0c50811e653b2b8934b4 [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?
John Wiegley429bb272011-04-08 18:41:53 +0000246 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000247
John McCallb45ae252011-10-05 07:41:44 +0000248 CastOperation Op(*this, DestType, E);
249 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
250 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000251
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000253 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000254
255 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000256 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000257 Op.CheckConstCast();
258 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000259 return ExprError();
260 }
John McCall5acb0c92011-10-17 18:40:02 +0000261 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
262 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000263 OpLoc, Parens.getEnd(),
264 AngleBrackets));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000265
Anders Carlsson714179b2009-08-02 19:07:59 +0000266 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000267 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000268 Op.CheckDynamicCast();
269 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000270 return ExprError();
271 }
John McCall5acb0c92011-10-17 18:40:02 +0000272 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
273 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
274 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000275 OpLoc, Parens.getEnd(),
276 AngleBrackets));
Anders Carlsson714179b2009-08-02 19:07:59 +0000277 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000278 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000279 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000280 Op.CheckReinterpretCast();
281 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000282 return ExprError();
283 }
John McCall5acb0c92011-10-17 18:40:02 +0000284 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
285 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
286 0, DestTInfo, OpLoc,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000287 Parens.getEnd(),
288 AngleBrackets));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000289 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000290 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000291 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000292 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000293 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000294 return ExprError();
295 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000296
John McCall5acb0c92011-10-17 18:40:02 +0000297 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
298 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
299 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000300 OpLoc, Parens.getEnd(),
301 AngleBrackets));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000302 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000303 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000304}
305
John McCall79ab2c82011-02-14 18:34:10 +0000306/// Try to diagnose a failed overloaded cast. Returns true if
307/// diagnostics were emitted.
308static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
309 SourceRange range, Expr *src,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000310 QualType destType,
311 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000312 switch (CT) {
313 // These cast kinds don't consider user-defined conversions.
314 case CT_Const:
315 case CT_Reinterpret:
316 case CT_Dynamic:
317 return false;
318
319 // These do.
320 case CT_Static:
321 case CT_CStyle:
322 case CT_Functional:
323 break;
324 }
325
326 QualType srcType = src->getType();
327 if (!destType->isRecordType() && !srcType->isRecordType())
328 return false;
329
330 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
331 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000332 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000333 range, listInitialization)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000334 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000335 listInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +0000336 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000337 InitializationSequence sequence(S, entity, initKind, src);
John McCall79ab2c82011-02-14 18:34:10 +0000338
Sebastian Redl383616c2011-06-05 12:23:28 +0000339 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000340 switch (sequence.getFailureKind()) {
341 default: return false;
342
343 case InitializationSequence::FK_ConstructorOverloadFailed:
344 case InitializationSequence::FK_UserConversionOverloadFailed:
345 break;
346 }
347
348 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
349
350 unsigned msg = 0;
351 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
352
353 switch (sequence.getFailedOverloadResult()) {
354 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000355 case OR_No_Viable_Function:
356 if (candidates.empty())
357 msg = diag::err_ovl_no_conversion_in_cast;
358 else
359 msg = diag::err_ovl_no_viable_conversion_in_cast;
360 howManyCandidates = OCD_AllCandidates;
361 break;
362
363 case OR_Ambiguous:
364 msg = diag::err_ovl_ambiguous_conversion_in_cast;
365 howManyCandidates = OCD_ViableCandidates;
366 break;
367
368 case OR_Deleted:
369 msg = diag::err_ovl_deleted_conversion_in_cast;
370 howManyCandidates = OCD_ViableCandidates;
371 break;
372 }
373
374 S.Diag(range.getBegin(), msg)
375 << CT << srcType << destType
376 << range << src->getSourceRange();
377
Ahmed Charles13a140c2012-02-25 11:00:22 +0000378 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall79ab2c82011-02-14 18:34:10 +0000379
380 return true;
381}
382
383/// Diagnose a failed cast.
384static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000385 SourceRange opRange, Expr *src, QualType destType,
386 bool listInitialization) {
John McCall864c0412011-04-26 20:42:42 +0000387 if (src->getType() == S.Context.BoundMemberTy) {
388 (void) S.CheckPlaceholderExpr(src); // will always fail
389 return;
390 }
391
John McCall79ab2c82011-02-14 18:34:10 +0000392 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000393 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
394 listInitialization))
John McCall79ab2c82011-02-14 18:34:10 +0000395 return;
396
397 S.Diag(opRange.getBegin(), msg) << castType
398 << src->getType() << destType << opRange << src->getSourceRange();
399}
400
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000401/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
402/// this removes one level of indirection from both types, provided that they're
403/// the same kind of pointer (plain or to-member). Unlike the Sema function,
404/// this one doesn't care if the two pointers-to-member don't point into the
405/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000406static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000407 const PointerType *T1PtrType = T1->getAs<PointerType>(),
408 *T2PtrType = T2->getAs<PointerType>();
409 if (T1PtrType && T2PtrType) {
410 T1 = T1PtrType->getPointeeType();
411 T2 = T2PtrType->getPointeeType();
412 return true;
413 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000414 const ObjCObjectPointerType *T1ObjCPtrType =
415 T1->getAs<ObjCObjectPointerType>(),
416 *T2ObjCPtrType =
417 T2->getAs<ObjCObjectPointerType>();
418 if (T1ObjCPtrType) {
419 if (T2ObjCPtrType) {
420 T1 = T1ObjCPtrType->getPointeeType();
421 T2 = T2ObjCPtrType->getPointeeType();
422 return true;
423 }
424 else if (T2PtrType) {
425 T1 = T1ObjCPtrType->getPointeeType();
426 T2 = T2PtrType->getPointeeType();
427 return true;
428 }
429 }
430 else if (T2ObjCPtrType) {
431 if (T1PtrType) {
432 T2 = T2ObjCPtrType->getPointeeType();
433 T1 = T1PtrType->getPointeeType();
434 return true;
435 }
436 }
437
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000438 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
439 *T2MPType = T2->getAs<MemberPointerType>();
440 if (T1MPType && T2MPType) {
441 T1 = T1MPType->getPointeeType();
442 T2 = T2MPType->getPointeeType();
443 return true;
444 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000445
446 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
447 *T2BPType = T2->getAs<BlockPointerType>();
448 if (T1BPType && T2BPType) {
449 T1 = T1BPType->getPointeeType();
450 T2 = T2BPType->getPointeeType();
451 return true;
452 }
453
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000454 return false;
455}
456
Sebastian Redldb647282009-01-27 23:18:31 +0000457/// CastsAwayConstness - Check if the pointer conversion from SrcType to
458/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
459/// the cast checkers. Both arguments must denote pointer (possibly to member)
460/// types.
John McCallf85e1932011-06-15 23:02:42 +0000461///
462/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
463///
464/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000465static bool
John McCallf85e1932011-06-15 23:02:42 +0000466CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
467 bool CheckCVR, bool CheckObjCLifetime) {
468 // If the only checking we care about is for Objective-C lifetime qualifiers,
469 // and we're not in ARC mode, there's nothing to check.
470 if (!CheckCVR && CheckObjCLifetime &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000471 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000472 return false;
473
Sebastian Redldb647282009-01-27 23:18:31 +0000474 // Casting away constness is defined in C++ 5.2.11p8 with reference to
475 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
476 // the rules are non-trivial. So first we construct Tcv *...cv* as described
477 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000478 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
479 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000480 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000481 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
482 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000483 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000484
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000485 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
486 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000488
Douglas Gregord4c5f842011-04-15 17:59:54 +0000489 // Find the qualifiers. We only care about cvr-qualifiers for the
490 // purpose of this check, because other qualifiers (address spaces,
491 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000492 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000493 // Determine the relevant qualifiers at this level.
494 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000495 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000496 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000497
498 Qualifiers RetainedSrcQuals, RetainedDestQuals;
499 if (CheckCVR) {
500 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
501 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
502 }
503
504 if (CheckObjCLifetime &&
505 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
506 return true;
507
508 cv1.push_back(RetainedSrcQuals);
509 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000510 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000511 if (cv1.empty())
512 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000513
514 // Construct void pointers with those qualifiers (in reverse order of
515 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000516 QualType SrcConstruct = Self.Context.VoidTy;
517 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000518 ASTContext &Context = Self.Context;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000519 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall0953e762009-09-24 19:53:00 +0000520 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000521 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000522 SrcConstruct
523 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
524 DestConstruct
525 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000526 }
527
528 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000529 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000530 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000531 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
532 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000533}
534
Sebastian Redl26d85b12008-11-05 21:50:06 +0000535/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
536/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
537/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000538void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000539 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000540 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000541 else if (isPlaceholder())
542 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
543 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
544 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000545
John McCallb45ae252011-10-05 07:41:44 +0000546 QualType OrigSrcType = SrcExpr.get()->getType();
547 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000548
549 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
550 // or "pointer to cv void".
551
552 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000553 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000554 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000555 if (DestPointer) {
556 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000557 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000558 DestPointee = DestReference->getPointeeType();
559 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000560 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000561 << this->DestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000562 return;
563 }
564
Ted Kremenek6217b802009-07-29 21:53:49 +0000565 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000566 if (DestPointee->isVoidType()) {
567 assert(DestPointer && "Reference to void is not possible");
568 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000569 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000570 diag::err_bad_dynamic_cast_incomplete,
571 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000572 return;
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;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000576 return;
577 }
578
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000579 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
580 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000581 // an lvalue of a complete class type, [...]. If T is an rvalue reference
582 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000583 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000584 QualType SrcPointee;
585 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000586 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000587 SrcPointee = SrcPointer->getPointeeType();
588 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000589 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000590 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000591 return;
592 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000593 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000594 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000595 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000596 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000597 }
598 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000599 } else {
600 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000601 }
602
Ted Kremenek6217b802009-07-29 21:53:49 +0000603 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000604 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000605 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000606 diag::err_bad_dynamic_cast_incomplete,
607 SrcExpr.get()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000608 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000609 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000610 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000611 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000612 return;
613 }
614
615 assert((DestPointer || DestReference) &&
616 "Bad destination non-ptr/ref slipped through.");
617 assert((DestRecord || DestPointee->isVoidType()) &&
618 "Bad destination pointee slipped through.");
619 assert(SrcRecord && "Bad source pointee slipped through.");
620
621 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
622 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000623 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000624 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000625 return;
626 }
627
628 // C++ 5.2.7p3: If the type of v is the same as the required result type,
629 // [except for cv].
630 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000631 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000632 return;
633 }
634
635 // C++ 5.2.7p5
636 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000637 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000638 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
639 OpRange.getBegin(), OpRange,
640 &BasePath))
641 return;
642
John McCall2de56d12010-08-25 11:45:40 +0000643 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000644
645 // If we are casting to or through a virtual base class, we need a
646 // vtable.
647 if (Self.BasePathInvolvesVirtualBase(BasePath))
648 Self.MarkVTableUsed(OpRange.getBegin(),
649 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000650 return;
651 }
652
653 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000654 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000655 assert(SrcDecl && "Definition missing");
656 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000657 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000658 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000659 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000660 Self.MarkVTableUsed(OpRange.getBegin(),
661 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000662
663 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000664 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000665}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000666
667/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
668/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
669/// like this:
670/// const char *str = "literal";
671/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000672void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000673 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000674 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000675 else if (isPlaceholder())
676 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
677 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
678 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679
680 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith41cb3d92013-06-14 22:27:52 +0000681 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000682 && msg != 0)
683 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000684 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000685}
686
John McCall437da052013-03-22 02:58:14 +0000687/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
688/// or downcast between respective pointers or references.
689static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
690 QualType DestType,
691 SourceRange OpRange) {
692 QualType SrcType = SrcExpr->getType();
693 // When casting from pointer or reference, get pointee type; use original
694 // type otherwise.
695 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
696 const CXXRecordDecl *SrcRD =
697 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
698
John McCallfdb468f2013-03-27 00:03:48 +0000699 // Examining subobjects for records is only possible if the complete and
700 // valid definition is available. Also, template instantiation is not
701 // allowed here.
702 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCall437da052013-03-22 02:58:14 +0000703 return;
704
705 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
706
John McCallfdb468f2013-03-27 00:03:48 +0000707 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCall437da052013-03-22 02:58:14 +0000708 return;
709
710 enum {
711 ReinterpretUpcast,
712 ReinterpretDowncast
713 } ReinterpretKind;
714
715 CXXBasePaths BasePaths;
716
717 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
718 ReinterpretKind = ReinterpretUpcast;
719 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
720 ReinterpretKind = ReinterpretDowncast;
721 else
722 return;
723
724 bool VirtualBase = true;
725 bool NonZeroOffset = false;
John McCallfdb468f2013-03-27 00:03:48 +0000726 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCall437da052013-03-22 02:58:14 +0000727 E = BasePaths.end();
728 I != E; ++I) {
729 const CXXBasePath &Path = *I;
730 CharUnits Offset = CharUnits::Zero();
731 bool IsVirtual = false;
732 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
733 IElem != EElem; ++IElem) {
734 IsVirtual = IElem->Base->isVirtual();
735 if (IsVirtual)
736 break;
737 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
738 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallfdb468f2013-03-27 00:03:48 +0000739 // Don't check if any base has invalid declaration or has no definition
740 // since it has no layout info.
741 const CXXRecordDecl *Class = IElem->Class,
742 *ClassDefinition = Class->getDefinition();
743 if (Class->isInvalidDecl() || !ClassDefinition ||
744 !ClassDefinition->isCompleteDefinition())
745 return;
746
John McCall437da052013-03-22 02:58:14 +0000747 const ASTRecordLayout &DerivedLayout =
John McCallfdb468f2013-03-27 00:03:48 +0000748 Self.Context.getASTRecordLayout(Class);
John McCall437da052013-03-22 02:58:14 +0000749 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
750 }
751 if (!IsVirtual) {
752 // Don't warn if any path is a non-virtually derived base at offset zero.
753 if (Offset.isZero())
754 return;
755 // Offset makes sense only for non-virtual bases.
756 else
757 NonZeroOffset = true;
758 }
759 VirtualBase = VirtualBase && IsVirtual;
760 }
761
Andy Gibbsde7afe02013-06-19 13:33:37 +0000762 (void) NonZeroOffset; // Silence set but not used warning.
John McCall437da052013-03-22 02:58:14 +0000763 assert((VirtualBase || NonZeroOffset) &&
764 "Should have returned if has non-virtual base with zero offset");
765
766 QualType BaseType =
767 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
768 QualType DerivedType =
769 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
770
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000771 SourceLocation BeginLoc = OpRange.getBegin();
772 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
773 << DerivedType << BaseType << !VirtualBase << ReinterpretKind
774 << OpRange;
775 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
776 << ReinterpretKind
777 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCall437da052013-03-22 02:58:14 +0000778}
779
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000780/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
781/// valid.
782/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
783/// like this:
784/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000785void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000786 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000787 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000788 else
789 checkNonOverloadPlaceholders();
790 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
791 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000792
793 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000794 TryCastResult tcr =
795 TryReinterpretCast(Self, SrcExpr, DestType,
796 /*CStyle*/false, OpRange, msg, Kind);
797 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000798 {
John Wiegley429bb272011-04-08 18:41:53 +0000799 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
800 return;
801 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000802 //FIXME: &f<int>; is overloaded and resolvable
803 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000804 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000805 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000806 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000807
John McCall79ab2c82011-02-14 18:34:10 +0000808 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000809 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
810 DestType, /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000811 }
John McCall437da052013-03-22 02:58:14 +0000812 } else if (tcr == TC_Success) {
813 if (Self.getLangOpts().ObjCAutoRefCount)
814 checkObjCARCConversion(Sema::CCK_OtherCast);
815 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCallf85e1932011-06-15 23:02:42 +0000816 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000817}
818
819
820/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
821/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
822/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000823void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000824 if (isPlaceholder()) {
825 checkNonOverloadPlaceholders();
826 if (SrcExpr.isInvalid())
827 return;
828 }
829
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000830 // This test is outside everything else because it's the only case where
831 // a non-lvalue-reference target type does not lead to decay.
832 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000833 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000834 Kind = CK_ToVoid;
835
836 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000837 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000838 false, // Decay Function to ptr
839 true, // Complain
840 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000841 if (SrcExpr.isInvalid())
842 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000843 }
John McCalla180f042011-10-06 23:25:11 +0000844
845 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000846 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000847 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000848
John McCall6dbba4f2011-10-11 23:14:30 +0000849 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
850 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000851 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
852 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
853 return;
854 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000855
856 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000857 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000858 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000859 Kind, BasePath, /*ListInitialization=*/false);
John McCallf85e1932011-06-15 23:02:42 +0000860 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000861 if (SrcExpr.isInvalid())
862 return;
863 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
864 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000865 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000866 << oe->getName() << DestType << OpRange
867 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000868 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000869 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000870 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
871 /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000872 }
John McCallf85e1932011-06-15 23:02:42 +0000873 } else if (tcr == TC_Success) {
874 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000875 checkCastAlign();
David Blaikie4e4d0842012-03-11 07:00:24 +0000876 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000877 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000878 } else if (Kind == CK_BitCast) {
879 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000880 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000881}
882
883/// TryStaticCast - Check if a static cast can be performed, and do so if
884/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
885/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000886static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000887 QualType DestType,
888 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000889 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000890 CastKind &Kind, CXXCastPath &BasePath,
891 bool ListInitialization) {
John McCallf85e1932011-06-15 23:02:42 +0000892 // Determine whether we have the semantics of a C-style cast.
893 bool CStyle
894 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
895
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000896 // The order the tests is not entirely arbitrary. There is one conversion
897 // that can be handled in two different ways. Given:
898 // struct A {};
899 // struct B : public A {
900 // B(); B(const A&);
901 // };
902 // const A &a = B();
903 // the cast static_cast<const B&>(a) could be seen as either a static
904 // reference downcast, or an explicit invocation of the user-defined
905 // conversion using B's conversion constructor.
906 // DR 427 specifies that the downcast is to be applied here.
907
908 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
909 // Done outside this function.
910
911 TryCastResult tcr;
912
913 // C++ 5.2.9p5, reference downcast.
914 // See the function for details.
915 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000916 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
917 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000918 if (tcr != TC_NotApplicable)
919 return tcr;
920
Douglas Gregordc843f22011-01-22 00:06:57 +0000921 // C++0x [expr.static.cast]p3:
922 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
923 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000924 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
925 BasePath, msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000926 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000927 return tcr;
928
929 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
930 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000931 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000932 Kind, ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000933 if (SrcExpr.isInvalid())
934 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000935 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000936 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000937
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000938 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
939 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
940 // conversions, subject to further restrictions.
941 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
942 // of qualification conversions impossible.
943 // In the CStyle case, the earlier attempt to const_cast should have taken
944 // care of reverse qualification conversions.
945
John Wiegley429bb272011-04-08 18:41:53 +0000946 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000947
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000948 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000949 // converted to an integral type. [...] A value of a scoped enumeration type
950 // can also be explicitly converted to a floating-point type [...].
951 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
952 if (Enum->getDecl()->isScoped()) {
953 if (DestType->isBooleanType()) {
954 Kind = CK_IntegralToBoolean;
955 return TC_Success;
956 } else if (DestType->isIntegralType(Self.Context)) {
957 Kind = CK_IntegralCast;
958 return TC_Success;
959 } else if (DestType->isRealFloatingType()) {
960 Kind = CK_IntegralToFloating;
961 return TC_Success;
962 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000963 }
964 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000965
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000966 // Reverse integral promotion/conversion. All such conversions are themselves
967 // again integral promotions or conversions and are thus already handled by
968 // p2 (TryDirectInitialization above).
969 // (Note: any data loss warnings should be suppressed.)
970 // The exception is the reverse of enum->integer, i.e. integer->enum (and
971 // enum->enum). See also C++ 5.2.9p7.
972 // The same goes for reverse floating point promotion/conversion and
973 // floating-integral conversions. Again, only floating->enum is relevant.
974 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000975 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000976 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000977 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000978 } else if (SrcType->isRealFloatingType()) {
979 Kind = CK_FloatingToIntegral;
980 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000981 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000982 }
983
984 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
985 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000986 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000987 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000988 if (tcr != TC_NotApplicable)
989 return tcr;
990
991 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
992 // conversion. C++ 5.2.9p9 has additional information.
993 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000994 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000995 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000996 if (tcr != TC_NotApplicable)
997 return tcr;
998
999 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1000 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1001 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +00001002 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001003 QualType SrcPointee = SrcPointer->getPointeeType();
1004 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001005 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001006 QualType DestPointee = DestPointer->getPointeeType();
1007 if (DestPointee->isIncompleteOrObjectType()) {
1008 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +00001009 // to a qualifier violation. Note that we permit Objective-C lifetime
1010 // and GC qualifier mismatches here.
1011 if (!CStyle) {
1012 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1013 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1014 DestPointeeQuals.removeObjCGCAttr();
1015 DestPointeeQuals.removeObjCLifetime();
1016 SrcPointeeQuals.removeObjCGCAttr();
1017 SrcPointeeQuals.removeObjCLifetime();
1018 if (DestPointeeQuals != SrcPointeeQuals &&
1019 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1020 msg = diag::err_bad_cxx_cast_qualifiers_away;
1021 return TC_Failed;
1022 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001023 }
John McCall2de56d12010-08-25 11:45:40 +00001024 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001025 return TC_Success;
1026 }
1027 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +00001028 else if (DestType->isObjCObjectPointerType()) {
1029 // allow both c-style cast and static_cast of objective-c pointers as
1030 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +00001031 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001032 return TC_Success;
1033 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001034 else if (CStyle && DestType->isBlockPointerType()) {
1035 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +00001036 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001037 return TC_Success;
1038 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001039 }
1040 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001041 // Allow arbitray objective-c pointer conversion with static casts.
1042 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001043 DestType->isObjCObjectPointerType()) {
1044 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001045 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +00001046 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001047
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048 // We tried everything. Everything! Nothing works! :-(
1049 return TC_NotApplicable;
1050}
1051
1052/// Tests whether a conversion according to N2844 is valid.
1053TryCastResult
1054TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001055 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1056 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +00001057 // C++0x [expr.static.cast]p3:
1058 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1059 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001061 if (!R)
1062 return TC_NotApplicable;
1063
Douglas Gregordc843f22011-01-22 00:06:57 +00001064 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001065 return TC_NotApplicable;
1066
1067 // Because we try the reference downcast before this function, from now on
1068 // this is the only cast possibility, so we issue an error if we fail now.
1069 // FIXME: Should allow casting away constness if CStyle.
1070 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00001071 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00001072 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001073 QualType FromType = SrcExpr->getType();
1074 QualType ToType = R->getPointeeType();
1075 if (CStyle) {
1076 FromType = FromType.getUnqualifiedType();
1077 ToType = ToType.getUnqualifiedType();
1078 }
1079
Douglas Gregor393896f2009-11-05 13:06:35 +00001080 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001081 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +00001082 DerivedToBase, ObjCConversion,
1083 ObjCLifetimeConversion)
1084 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001085 msg = diag::err_bad_lvalue_to_rvalue_cast;
1086 return TC_Failed;
1087 }
1088
Douglas Gregor88b22a42011-01-25 16:13:26 +00001089 if (DerivedToBase) {
1090 Kind = CK_DerivedToBase;
1091 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1092 /*DetectVirtual=*/true);
1093 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1094 return TC_NotApplicable;
1095
1096 Self.BuildBasePathArray(Paths, BasePath);
1097 } else
1098 Kind = CK_NoOp;
1099
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001100 return TC_Success;
1101}
1102
1103/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1104TryCastResult
1105TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1106 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001107 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001108 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001109 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1110 // cast to type "reference to cv2 D", where D is a class derived from B,
1111 // if a valid standard conversion from "pointer to D" to "pointer to B"
1112 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1113 // In addition, DR54 clarifies that the base must be accessible in the
1114 // current context. Although the wording of DR54 only applies to the pointer
1115 // variant of this rule, the intent is clearly for it to apply to the this
1116 // conversion as well.
1117
Ted Kremenek6217b802009-07-29 21:53:49 +00001118 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001119 if (!DestReference) {
1120 return TC_NotApplicable;
1121 }
1122 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001123 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001124 // We know the left side is an lvalue reference, so we can suggest a reason.
1125 msg = diag::err_bad_cxx_cast_rvalue;
1126 return TC_NotApplicable;
1127 }
1128
1129 QualType DestPointee = DestReference->getPointeeType();
1130
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001131 return TryStaticDowncast(Self,
1132 Self.Context.getCanonicalType(SrcExpr->getType()),
1133 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001134 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1135 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001136}
1137
1138/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1139TryCastResult
1140TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001141 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001142 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001143 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001144 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1145 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1146 // is a class derived from B, if a valid standard conversion from "pointer
1147 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1148 // class of D.
1149 // In addition, DR54 clarifies that the base must be accessible in the
1150 // current context.
1151
Ted Kremenek6217b802009-07-29 21:53:49 +00001152 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001153 if (!DestPointer) {
1154 return TC_NotApplicable;
1155 }
1156
Ted Kremenek6217b802009-07-29 21:53:49 +00001157 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001158 if (!SrcPointer) {
1159 msg = diag::err_bad_static_cast_pointer_nonpointer;
1160 return TC_NotApplicable;
1161 }
1162
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001163 return TryStaticDowncast(Self,
1164 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1165 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001166 CStyle, OpRange, SrcType, DestType, msg, Kind,
1167 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001168}
1169
1170/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1171/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001172/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001173TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001174TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001175 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001176 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001177 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001178 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregord10099e2012-05-04 16:32:21 +00001179 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1180 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001181 return TC_NotApplicable;
1182
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001183 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001184 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001185 return TC_NotApplicable;
1186 }
1187
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001188 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001189 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001190 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1191 return TC_NotApplicable;
1192 }
1193
1194 // Target type does derive from source type. Now we're serious. If an error
1195 // appears now, it's not ignored.
1196 // This may not be entirely in line with the standard. Take for example:
1197 // struct A {};
1198 // struct B : virtual A {
1199 // B(A&);
1200 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001201 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001202 // void f()
1203 // {
1204 // (void)static_cast<const B&>(*((A*)0));
1205 // }
1206 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1207 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1208 // However, both GCC and Comeau reject this example, and accepting it would
1209 // mean more complex code if we're to preserve the nice error message.
1210 // FIXME: Being 100% compliant here would be nice to have.
1211
1212 // Must preserve cv, as always, unless we're in C-style mode.
1213 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001214 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001215 return TC_Failed;
1216 }
1217
1218 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1219 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1220 // that it builds the paths in reverse order.
1221 // To sum up: record all paths to the base and build a nice string from
1222 // them. Use it to spice up the error message.
1223 if (!Paths.isRecordingPaths()) {
1224 Paths.clear();
1225 Paths.setRecordingPaths(true);
1226 Self.IsDerivedFrom(DestType, SrcType, Paths);
1227 }
1228 std::string PathDisplayStr;
1229 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001230 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001231 PI != PE; ++PI) {
1232 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1233 // We haven't displayed a path to this particular base
1234 // class subobject yet.
1235 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001236 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1237 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001238 EI != EE; ++EI)
1239 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001240 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001241 }
1242 }
1243
1244 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001245 << QualType(SrcType).getUnqualifiedType()
1246 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001247 << PathDisplayStr << OpRange;
1248 msg = 0;
1249 return TC_Failed;
1250 }
1251
1252 if (Paths.getDetectedVirtual() != 0) {
1253 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1254 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1255 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1256 msg = 0;
1257 return TC_Failed;
1258 }
1259
John McCall417d39f2011-02-14 23:21:33 +00001260 if (!CStyle) {
1261 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1262 SrcType, DestType,
1263 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001264 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001265 case Sema::AR_accessible:
1266 case Sema::AR_delayed: // be optimistic
1267 case Sema::AR_dependent: // be optimistic
1268 break;
1269
1270 case Sema::AR_inaccessible:
1271 msg = 0;
1272 return TC_Failed;
1273 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001274 }
1275
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001276 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001277 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001278 return TC_Success;
1279}
1280
1281/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1282/// C++ 5.2.9p9 is valid:
1283///
1284/// An rvalue of type "pointer to member of D of type cv1 T" can be
1285/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1286/// where B is a base class of D [...].
1287///
1288TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001289TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001290 QualType DestType, bool CStyle,
1291 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001292 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001293 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001294 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001295 if (!DestMemPtr)
1296 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001297
1298 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001299 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001300 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001301 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001302 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001303 FoundOverload)) {
1304 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1305 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1306 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1307 WasOverloadedFunction = true;
1308 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001309 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001310
Ted Kremenek6217b802009-07-29 21:53:49 +00001311 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001312 if (!SrcMemPtr) {
1313 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1314 return TC_NotApplicable;
1315 }
1316
1317 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001318 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1319 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001320 return TC_NotApplicable;
1321
1322 // B base of D
1323 QualType SrcClass(SrcMemPtr->getClass(), 0);
1324 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001325 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001326 /*DetectVirtual=*/true);
1327 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1328 return TC_NotApplicable;
1329 }
1330
1331 // 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 +00001332 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001333 Paths.clear();
1334 Paths.setRecordingPaths(true);
1335 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1336 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001337 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001338 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1339 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1340 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1341 msg = 0;
1342 return TC_Failed;
1343 }
1344
1345 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1346 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1347 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1348 msg = 0;
1349 return TC_Failed;
1350 }
1351
John McCall417d39f2011-02-14 23:21:33 +00001352 if (!CStyle) {
1353 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1354 DestClass, SrcClass,
1355 Paths.front(),
1356 diag::err_upcast_to_inaccessible_base)) {
1357 case Sema::AR_accessible:
1358 case Sema::AR_delayed:
1359 case Sema::AR_dependent:
1360 // Optimistically assume that the delayed and dependent cases
1361 // will work out.
1362 break;
1363
1364 case Sema::AR_inaccessible:
1365 msg = 0;
1366 return TC_Failed;
1367 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001368 }
1369
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001370 if (WasOverloadedFunction) {
1371 // Resolve the address of the overloaded function again, this time
1372 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001373 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001374 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001375 true,
1376 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001377 if (!Fn) {
1378 msg = 0;
1379 return TC_Failed;
1380 }
1381
John McCall6bb80172010-03-30 21:47:33 +00001382 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001383 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001384 msg = 0;
1385 return TC_Failed;
1386 }
1387 }
1388
Anders Carlssoncee22422010-04-24 19:22:20 +00001389 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001390 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001391 return TC_Success;
1392}
1393
1394/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1395/// is valid:
1396///
1397/// An expression e can be explicitly converted to a type T using a
1398/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1399TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001400TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001401 Sema::CheckedConversionKind CCK,
1402 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001403 CastKind &Kind, bool ListInitialization) {
Anders Carlssond851b372009-09-07 18:25:47 +00001404 if (DestType->isRecordType()) {
1405 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001406 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman860a3192012-06-16 02:19:17 +00001407 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001408 diag::err_allocation_of_abstract_type)) {
Anders Carlssond851b372009-09-07 18:25:47 +00001409 msg = 0;
1410 return TC_Failed;
1411 }
1412 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001413
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001414 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1415 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001416 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001417 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001418 ListInitialization)
John McCallf85e1932011-06-15 23:02:42 +00001419 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001420 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +00001421 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001422 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00001423 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor8e960432010-11-08 03:40:48 +00001424
1425 // At this point of CheckStaticCast, if the destination is a reference,
1426 // or the expression is an overload expression this has to work.
1427 // There is no other way that works.
1428 // On the other hand, if we're checking a C-style cast, we've still got
1429 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001430 bool CStyle
1431 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001432 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001433 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001434
Benjamin Kramer5354e772012-08-23 23:38:35 +00001435 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001436 if (Result.isInvalid()) {
1437 msg = 0;
1438 return TC_Failed;
1439 }
1440
Douglas Gregord6e44a32010-04-16 22:09:46 +00001441 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001442 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001443 else
John McCall2de56d12010-08-25 11:45:40 +00001444 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001445
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001446 SrcExpr = Result;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001447 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001448}
1449
1450/// TryConstCast - See if a const_cast from source to destination is allowed,
1451/// and perform it if it is.
Richard Smith41cb3d92013-06-14 22:27:52 +00001452static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1453 QualType DestType, bool CStyle,
1454 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001455 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith41cb3d92013-06-14 22:27:52 +00001456 QualType SrcType = SrcExpr.get()->getType();
1457 bool NeedToMaterializeTemporary = false;
1458
Douglas Gregor575d2a32011-01-22 00:19:52 +00001459 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith41cb3d92013-06-14 22:27:52 +00001460 // C++11 5.2.11p4:
1461 // if a pointer to T1 can be explicitly converted to the type "pointer to
1462 // T2" using a const_cast, then the following conversions can also be
1463 // made:
1464 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1465 // type T2 using the cast const_cast<T2&>;
1466 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1467 // type T2 using the cast const_cast<T2&&>; and
1468 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1469 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1470
1471 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001472 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1473 // is C-style, static_cast might find a way, so we simply suggest a
1474 // message and tell the parent to keep searching.
1475 msg = diag::err_bad_cxx_cast_rvalue;
1476 return TC_NotApplicable;
1477 }
1478
Richard Smith41cb3d92013-06-14 22:27:52 +00001479 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1480 if (!SrcType->isRecordType()) {
1481 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1482 // this is C-style, static_cast can do this.
1483 msg = diag::err_bad_cxx_cast_rvalue;
1484 return TC_NotApplicable;
1485 }
1486
1487 // Materialize the class prvalue so that the const_cast can bind a
1488 // reference to it.
1489 NeedToMaterializeTemporary = true;
1490 }
1491
John McCall993f43f2013-05-06 21:39:12 +00001492 // It's not completely clear under the standard whether we can
1493 // const_cast bit-field gl-values. Doing so would not be
1494 // intrinsically complicated, but for now, we say no for
1495 // consistency with other compilers and await the word of the
1496 // committee.
Richard Smith41cb3d92013-06-14 22:27:52 +00001497 if (SrcExpr.get()->refersToBitField()) {
John McCall993f43f2013-05-06 21:39:12 +00001498 msg = diag::err_bad_cxx_cast_bitfield;
1499 return TC_NotApplicable;
1500 }
1501
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001502 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1503 SrcType = Self.Context.getPointerType(SrcType);
1504 }
1505
1506 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1507 // the rules for const_cast are the same as those used for pointers.
1508
John McCalld425d2b2010-05-18 09:35:29 +00001509 if (!DestType->isPointerType() &&
1510 !DestType->isMemberPointerType() &&
1511 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001512 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1513 // was a reference type, we converted it to a pointer above.
1514 // The status of rvalue references isn't entirely clear, but it looks like
1515 // conversion to them is simply invalid.
1516 // C++ 5.2.11p3: For two pointer types [...]
1517 if (!CStyle)
1518 msg = diag::err_bad_const_cast_dest;
1519 return TC_NotApplicable;
1520 }
1521 if (DestType->isFunctionPointerType() ||
1522 DestType->isMemberFunctionPointerType()) {
1523 // Cannot cast direct function pointers.
1524 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1525 // T is the ultimate pointee of source and target type.
1526 if (!CStyle)
1527 msg = diag::err_bad_const_cast_dest;
1528 return TC_NotApplicable;
1529 }
1530 SrcType = Self.Context.getCanonicalType(SrcType);
1531
1532 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1533 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001534 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1535 // in multi-level pointers may change, but the level count must be the same,
1536 // as must be the final pointee type.
1537 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001538 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001539 Qualifiers SrcQuals, DestQuals;
1540 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1541 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1542
1543 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1544 // the other qualifiers (e.g., address spaces) are identical.
1545 SrcQuals.removeCVRQualifiers();
1546 DestQuals.removeCVRQualifiers();
1547 if (SrcQuals != DestQuals)
1548 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001549 }
1550
1551 // Since we're dealing in canonical types, the remainder must be the same.
1552 if (SrcType != DestType)
1553 return TC_NotApplicable;
1554
Richard Smith41cb3d92013-06-14 22:27:52 +00001555 if (NeedToMaterializeTemporary)
1556 // This is a const_cast from a class prvalue to an rvalue reference type.
1557 // Materialize a temporary to store the result of the conversion.
1558 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1559 SrcType, SrcExpr.take(), /*IsLValueReference*/ false,
1560 /*ExtendingDecl*/ 0);
1561
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001562 return TC_Success;
1563}
1564
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001565// Checks for undefined behavior in reinterpret_cast.
1566// The cases that is checked for is:
1567// *reinterpret_cast<T*>(&a)
1568// reinterpret_cast<T&>(a)
1569// where accessing 'a' as type 'T' will result in undefined behavior.
1570void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1571 bool IsDereference,
1572 SourceRange Range) {
1573 unsigned DiagID = IsDereference ?
1574 diag::warn_pointer_indirection_from_incompatible_type :
1575 diag::warn_undefined_reinterpret_cast;
1576
1577 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001578 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001579 return;
1580 }
1581
1582 QualType SrcTy, DestTy;
1583 if (IsDereference) {
1584 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1585 return;
1586 }
1587 SrcTy = SrcType->getPointeeType();
1588 DestTy = DestType->getPointeeType();
1589 } else {
1590 if (!DestType->getAs<ReferenceType>()) {
1591 return;
1592 }
1593 SrcTy = SrcType;
1594 DestTy = DestType->getPointeeType();
1595 }
1596
1597 // Cast is compatible if the types are the same.
1598 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1599 return;
1600 }
1601 // or one of the types is a char or void type
1602 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1603 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1604 return;
1605 }
1606 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001607 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001608 return;
1609 }
1610
Douglas Gregor575a1c92011-05-20 16:38:50 +00001611 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001612 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1613 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1614 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1615 return;
1616 }
1617 }
1618
1619 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1620}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001621
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001622static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1623 QualType DestType) {
1624 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanian0c252fa2012-12-13 00:42:06 +00001625 if (Self.Context.hasSameType(SrcType, DestType))
1626 return;
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001627 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1628 if (SrcPtrTy->isObjCSelType()) {
1629 QualType DT = DestType;
1630 if (isa<PointerType>(DestType))
1631 DT = DestType->getPointeeType();
1632 if (!DT.getUnqualifiedType()->isVoidType())
1633 Self.Diag(SrcExpr.get()->getExprLoc(),
1634 diag::warn_cast_pointer_from_sel)
1635 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1636 }
1637}
1638
David Blaikie9b29f4f2012-10-16 18:53:14 +00001639static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1640 const Expr *SrcExpr, QualType DestType,
1641 Sema &Self) {
1642 QualType SrcType = SrcExpr->getType();
1643
1644 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1645 // are not explicit design choices, but consistent with GCC's behavior.
1646 // Feel free to modify them if you've reason/evidence for an alternative.
1647 if (CStyle && SrcType->isIntegralType(Self.Context)
1648 && !SrcType->isBooleanType()
1649 && !SrcType->isEnumeralType()
1650 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremenek2628b442013-05-29 21:50:46 +00001651 && Self.Context.getTypeSize(DestType) >
1652 Self.Context.getTypeSize(SrcType)) {
1653 // Separate between casts to void* and non-void* pointers.
1654 // Some APIs use (abuse) void* for something like a user context,
1655 // and often that value is an integer even if it isn't a pointer itself.
1656 // Having a separate warning flag allows users to control the warning
1657 // for their workflow.
1658 unsigned Diag = DestType->isVoidPointerType() ?
1659 diag::warn_int_to_void_pointer_cast
1660 : diag::warn_int_to_pointer_cast;
1661 Self.Diag(Loc, Diag) << SrcType << DestType;
1662 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00001663}
1664
John Wiegley429bb272011-04-08 18:41:53 +00001665static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001666 QualType DestType, bool CStyle,
1667 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001668 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001669 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001670 bool IsLValueCast = false;
1671
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001672 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001673 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001674
1675 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001676 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1677 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001678 // ... unless foo<int> resolves to an lvalue unambiguously.
1679 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1680 // like it?
1681 ExprResult SingleFunctionExpr = SrcExpr;
1682 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1683 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001684 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001685 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001686 SrcExpr = SingleFunctionExpr;
John Wiegley429bb272011-04-08 18:41:53 +00001687 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001688 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001689 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001690 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001691 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001692
Ted Kremenek6217b802009-07-29 21:53:49 +00001693 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smith6850faf2012-04-29 08:24:44 +00001694 if (!SrcExpr.get()->isGLValue()) {
1695 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1696 // similar comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001697 msg = diag::err_bad_cxx_cast_rvalue;
1698 return TC_NotApplicable;
1699 }
1700
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001701 if (!CStyle) {
1702 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1703 /*isDereference=*/false, OpRange);
1704 }
1705
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001706 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1707 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1708 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001709
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001710 const char *inappropriate = 0;
1711 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001712 case OK_Ordinary:
1713 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001714 case OK_BitField: inappropriate = "bit-field"; break;
1715 case OK_VectorComponent: inappropriate = "vector element"; break;
1716 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001717 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1718 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001719 }
1720 if (inappropriate) {
1721 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1722 << inappropriate << DestType
1723 << OpRange << SrcExpr.get()->getSourceRange();
1724 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001725 return TC_NotApplicable;
1726 }
1727
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001728 // This code does this transformation for the checked types.
1729 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1730 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001731
Douglas Gregore39a3892010-07-13 23:17:26 +00001732 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001733 }
1734
1735 // Canonicalize source for comparison.
1736 SrcType = Self.Context.getCanonicalType(SrcType);
1737
Ted Kremenek6217b802009-07-29 21:53:49 +00001738 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1739 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001740 if (DestMemPtr && SrcMemPtr) {
1741 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1742 // can be explicitly converted to an rvalue of type "pointer to member
1743 // of Y of type T2" if T1 and T2 are both function types or both object
1744 // types.
1745 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1746 SrcMemPtr->getPointeeType()->isFunctionType())
1747 return TC_NotApplicable;
1748
1749 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1750 // constness.
1751 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1752 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001753 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1754 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001755 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001756 return TC_Failed;
1757 }
1758
Charles Davisf231df32010-08-16 05:30:44 +00001759 // Don't allow casting between member pointers of different sizes.
1760 if (Self.Context.getTypeSize(DestMemPtr) !=
1761 Self.Context.getTypeSize(SrcMemPtr)) {
1762 msg = diag::err_bad_cxx_cast_member_pointer_size;
1763 return TC_Failed;
1764 }
1765
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001766 // A valid member pointer cast.
John McCall4d4e5c12012-02-15 01:22:51 +00001767 assert(!IsLValueCast);
1768 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001769 return TC_Success;
1770 }
1771
1772 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001773 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001774 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1775 // type large enough to hold it. A value of std::nullptr_t can be
1776 // converted to an integral type; the conversion has the same meaning
1777 // and validity as a conversion of (void*)0 to the integral type.
1778 if (Self.Context.getTypeSize(SrcType) >
1779 Self.Context.getTypeSize(DestType)) {
1780 msg = diag::err_bad_reinterpret_cast_small_int;
1781 return TC_Failed;
1782 }
John McCall2de56d12010-08-25 11:45:40 +00001783 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001784 return TC_Success;
1785 }
1786
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001787 bool destIsVector = DestType->isVectorType();
1788 bool srcIsVector = SrcType->isVectorType();
1789 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001790 // FIXME: Should this also apply to floating point types?
1791 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1792 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001793
1794 // Check if this is a cast between a vector and something else.
1795 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1796 !(srcIsVector && destIsVector))
1797 return TC_NotApplicable;
1798
1799 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001800 if (Self.Context.getTypeSize(SrcType)
1801 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001802 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001803 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001804 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001805
1806 if (destIsScalar)
1807 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1808 else if (srcIsScalar)
1809 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1810 else
1811 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1812
1813 return TC_Failed;
1814 }
Chad Rosier41f44312012-02-03 02:54:37 +00001815
1816 if (SrcType == DestType) {
1817 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1818 // restrictions, a cast to the same type is allowed so long as it does not
1819 // cast away constness. In C++98, the intent was not entirely clear here,
1820 // since all other paragraphs explicitly forbid casts to the same type.
1821 // C++11 clarifies this case with p2.
1822 //
1823 // The only allowed types are: integral, enumeration, pointer, or
1824 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1825 Kind = CK_NoOp;
1826 TryCastResult Result = TC_NotApplicable;
1827 if (SrcType->isIntegralOrEnumerationType() ||
1828 SrcType->isAnyPointerType() ||
1829 SrcType->isMemberPointerType() ||
1830 SrcType->isBlockPointerType()) {
1831 Result = TC_Success;
1832 }
1833 return Result;
1834 }
1835
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001836 bool destIsPtr = DestType->isAnyPointerType() ||
1837 DestType->isBlockPointerType();
1838 bool srcIsPtr = SrcType->isAnyPointerType() ||
1839 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001840 if (!destIsPtr && !srcIsPtr) {
1841 // Except for std::nullptr_t->integer and lvalue->reference, which are
1842 // handled above, at least one of the two arguments must be a pointer.
1843 return TC_NotApplicable;
1844 }
1845
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001846 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001847 assert(srcIsPtr && "One type must be a pointer");
1848 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001849 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg649c6c52013-06-06 09:16:36 +00001850 // integral type size doesn't matter (except we don't allow bool).
1851 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1852 !DestType->isBooleanType();
Francois Pichet30aff5b2011-05-11 22:13:54 +00001853 if ((Self.Context.getTypeSize(SrcType) >
1854 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg649c6c52013-06-06 09:16:36 +00001855 !MicrosoftException) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001856 msg = diag::err_bad_reinterpret_cast_small_int;
1857 return TC_Failed;
1858 }
John McCall2de56d12010-08-25 11:45:40 +00001859 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001860 return TC_Success;
1861 }
1862
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001863 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001864 assert(destIsPtr && "One type must be a pointer");
David Blaikie9b29f4f2012-10-16 18:53:14 +00001865 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1866 Self);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001867 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1868 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001869 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1870 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001871 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001872 return TC_Success;
1873 }
1874
1875 if (!destIsPtr || !srcIsPtr) {
1876 // With the valid non-pointer conversions out of the way, we can be even
1877 // more stringent.
1878 return TC_NotApplicable;
1879 }
1880
1881 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1882 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001883 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1884 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001885 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001886 return TC_Failed;
1887 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001888
1889 // Cannot convert between block pointers and Objective-C object pointers.
1890 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1891 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1892 return TC_NotApplicable;
1893
John McCall1d9b3b22011-09-09 05:25:32 +00001894 if (IsLValueCast) {
1895 Kind = CK_LValueBitCast;
1896 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001897 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001898 } else if (DestType->isBlockPointerType()) {
1899 if (!SrcType->isBlockPointerType()) {
1900 Kind = CK_AnyPointerToBlockPointerCast;
1901 } else {
1902 Kind = CK_BitCast;
1903 }
1904 } else {
1905 Kind = CK_BitCast;
1906 }
1907
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001908 // Any pointer can be cast to an Objective-C pointer type with a C-style
1909 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001910 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001911 return TC_Success;
1912 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001913 if (CStyle)
1914 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1915
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001916 // Not casting away constness, so the only remaining check is for compatible
1917 // pointer categories.
1918
1919 if (SrcType->isFunctionPointerType()) {
1920 if (DestType->isFunctionPointerType()) {
1921 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1922 // a pointer to a function of a different type.
1923 return TC_Success;
1924 }
1925
1926 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1927 // an object type or vice versa is conditionally-supported.
1928 // Compilers support it in C++03 too, though, because it's necessary for
1929 // casting the return value of dlsym() and GetProcAddress().
1930 // FIXME: Conditionally-supported behavior should be configurable in the
1931 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001932 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001933 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001934 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1935 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001936 return TC_Success;
1937 }
1938
1939 if (DestType->isFunctionPointerType()) {
1940 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001941 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001942 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001943 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1944 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001945 return TC_Success;
1946 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001947
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001948 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1949 // a pointer to an object of different type.
1950 // Void pointers are not specified, but supported by every compiler out there.
1951 // So we finish by allowing everything that remains - it's got to be two
1952 // object pointers.
1953 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001954}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001955
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001956void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1957 bool ListInitialization) {
John McCalla180f042011-10-06 23:25:11 +00001958 // Handle placeholders.
1959 if (isPlaceholder()) {
1960 // C-style casts can resolve __unknown_any types.
1961 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1962 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1963 SrcExpr.get(), Kind,
1964 ValueKind, BasePath);
1965 return;
1966 }
John McCallb45ae252011-10-05 07:41:44 +00001967
John McCalla180f042011-10-06 23:25:11 +00001968 checkNonOverloadPlaceholders();
1969 if (SrcExpr.isInvalid())
1970 return;
John McCall4919dfd2011-10-17 17:42:19 +00001971 }
John McCalla180f042011-10-06 23:25:11 +00001972
1973 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001974 // This test is outside everything else because it's the only case where
1975 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001976 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001977 Kind = CK_ToVoid;
1978
John McCalla180f042011-10-06 23:25:11 +00001979 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001980 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1981 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00001982 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001983 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00001984 if (SrcExpr.isInvalid())
1985 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001986 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001987
John McCalla180f042011-10-06 23:25:11 +00001988 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1989 if (SrcExpr.isInvalid())
John McCallb45ae252011-10-05 07:41:44 +00001990 return;
John McCallb45ae252011-10-05 07:41:44 +00001991
1992 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00001993 }
1994
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001995 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb45ae252011-10-05 07:41:44 +00001996 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1997 assert(Kind == CK_Dependent);
1998 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00001999 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00002000
John McCall6dbba4f2011-10-11 23:14:30 +00002001 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2002 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00002003 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2004 if (SrcExpr.isInvalid())
2005 return;
John Wiegley429bb272011-04-08 18:41:53 +00002006 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002007
John McCallfb8721c2011-04-10 19:13:55 +00002008 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00002009 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00002010 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00002011 && (SrcExpr.get()->getType()->isIntegerType()
2012 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00002013 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00002014 return;
John McCallfb8721c2011-04-10 19:13:55 +00002015 }
2016
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002017 // C++ [expr.cast]p5: The conversions performed by
2018 // - a const_cast,
2019 // - a static_cast,
2020 // - a static_cast followed by a const_cast,
2021 // - a reinterpret_cast, or
2022 // - a reinterpret_cast followed by a const_cast,
2023 // can be performed using the cast notation of explicit type conversion.
2024 // [...] If a conversion can be interpreted in more than one of the ways
2025 // listed above, the interpretation that appears first in the list is used,
2026 // even if a cast resulting from that interpretation is ill-formed.
2027 // In plain language, this means trying a const_cast ...
2028 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith41cb3d92013-06-14 22:27:52 +00002029 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb45ae252011-10-05 07:41:44 +00002030 /*CStyle*/true, msg);
Richard Smith41cb3d92013-06-14 22:27:52 +00002031 if (SrcExpr.isInvalid())
2032 return;
Anders Carlssonda921fd2009-10-19 18:14:28 +00002033 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00002034 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00002035
John McCallf85e1932011-06-15 23:02:42 +00002036 Sema::CheckedConversionKind CCK
2037 = FunctionalStyle? Sema::CCK_FunctionalCast
2038 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002039 if (tcr == TC_NotApplicable) {
2040 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00002041 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002042 msg, Kind, BasePath, ListInitialization);
John McCallb45ae252011-10-05 07:41:44 +00002043 if (SrcExpr.isInvalid())
2044 return;
2045
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002046 if (tcr == TC_NotApplicable) {
2047 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00002048 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2049 OpRange, msg, Kind);
2050 if (SrcExpr.isInvalid())
2051 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002052 }
2053 }
2054
David Blaikie4e4d0842012-03-11 07:00:24 +00002055 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002056 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00002057
Nick Lewycky43328e92010-11-09 00:19:31 +00002058 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00002059 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00002060 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00002061 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2062 DestType,
2063 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00002064 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002065
Richard Trieu32ac00d2011-04-16 01:09:30 +00002066 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00002067 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00002068
Nick Lewycky43328e92010-11-09 00:19:31 +00002069 } else {
John McCallb45ae252011-10-05 07:41:44 +00002070 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002071 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregor8e960432010-11-08 03:40:48 +00002072 }
John McCallb45ae252011-10-05 07:41:44 +00002073 } else if (Kind == CK_BitCast) {
2074 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00002075 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002076
John McCallb45ae252011-10-05 07:41:44 +00002077 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00002078 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002079 SrcExpr = ExprError();
2080}
2081
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002082/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2083/// non-matching type. Such as enum function call to int, int call to
2084/// pointer; etc. Cast to 'void' is an exception.
2085static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2086 QualType DestType) {
2087 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2088 SrcExpr.get()->getExprLoc())
2089 == DiagnosticsEngine::Ignored)
2090 return;
2091
2092 if (!isa<CallExpr>(SrcExpr.get()))
2093 return;
2094
2095 QualType SrcType = SrcExpr.get()->getType();
2096 if (DestType.getUnqualifiedType()->isVoidType())
2097 return;
2098 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2099 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2100 return;
2101 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2102 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2103 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2104 return;
2105 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2106 return;
2107 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2108 return;
2109 if (SrcType->isComplexType() && DestType->isComplexType())
2110 return;
2111 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2112 return;
2113
2114 Self.Diag(SrcExpr.get()->getExprLoc(),
2115 diag::warn_bad_function_cast)
2116 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2117}
2118
John McCalla180f042011-10-06 23:25:11 +00002119/// Check the semantics of a C-style cast operation, in C.
2120void CastOperation::CheckCStyleCast() {
David Blaikie4e4d0842012-03-11 07:00:24 +00002121 assert(!Self.getLangOpts().CPlusPlus);
John McCalla180f042011-10-06 23:25:11 +00002122
John McCall5acb0c92011-10-17 18:40:02 +00002123 // C-style casts can resolve __unknown_any types.
2124 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2125 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2126 SrcExpr.get(), Kind,
2127 ValueKind, BasePath);
2128 return;
2129 }
John McCalla180f042011-10-06 23:25:11 +00002130
2131 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2132 // type needs to be scalar.
2133 if (DestType->isVoidType()) {
2134 // We don't necessarily do lvalue-to-rvalue conversions on this.
2135 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2136 if (SrcExpr.isInvalid())
2137 return;
2138
2139 // Cast to void allows any expr type.
2140 Kind = CK_ToVoid;
2141 return;
2142 }
2143
2144 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2145 if (SrcExpr.isInvalid())
2146 return;
2147 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00002148
John McCall5acb0c92011-10-17 18:40:02 +00002149 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00002150
2151 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2152 diag::err_typecheck_cast_to_incomplete)) {
2153 SrcExpr = ExprError();
2154 return;
2155 }
2156
2157 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2158 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2159
2160 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2161 // GCC struct/union extension: allow cast to self.
2162 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2163 << DestType << SrcExpr.get()->getSourceRange();
2164 Kind = CK_NoOp;
2165 return;
2166 }
2167
2168 // GCC's cast to union extension.
2169 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2170 RecordDecl *RD = DestRecordTy->getDecl();
2171 RecordDecl::field_iterator Field, FieldEnd;
2172 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2173 Field != FieldEnd; ++Field) {
2174 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2175 !Field->isUnnamedBitfield()) {
2176 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2177 << SrcExpr.get()->getSourceRange();
2178 break;
2179 }
2180 }
2181 if (Field == FieldEnd) {
2182 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2183 << SrcType << SrcExpr.get()->getSourceRange();
2184 SrcExpr = ExprError();
2185 return;
2186 }
2187 Kind = CK_ToUnion;
2188 return;
2189 }
2190
2191 // Reject any other conversions to non-scalar types.
2192 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2193 << DestType << SrcExpr.get()->getSourceRange();
2194 SrcExpr = ExprError();
2195 return;
2196 }
2197
2198 // The type we're casting to is known to be a scalar or vector.
2199
2200 // Require the operand to be a scalar or vector.
2201 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2202 Self.Diag(SrcExpr.get()->getExprLoc(),
2203 diag::err_typecheck_expect_scalar_operand)
2204 << SrcType << SrcExpr.get()->getSourceRange();
2205 SrcExpr = ExprError();
2206 return;
2207 }
2208
2209 if (DestType->isExtVectorType()) {
2210 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2211 return;
2212 }
2213
2214 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2215 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2216 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2217 Kind = CK_VectorSplat;
2218 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2219 SrcExpr = ExprError();
2220 }
2221 return;
2222 }
2223
2224 if (SrcType->isVectorType()) {
2225 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2226 SrcExpr = ExprError();
2227 return;
2228 }
2229
2230 // The source and target types are both scalars, i.e.
2231 // - arithmetic types (fundamental, enum, and complex)
2232 // - all kinds of pointers
2233 // Note that member pointers were filtered out with C++, above.
2234
2235 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2236 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2237 SrcExpr = ExprError();
2238 return;
2239 }
2240
2241 // If either type is a pointer, the other type has to be either an
2242 // integer or a pointer.
2243 if (!DestType->isArithmeticType()) {
2244 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2245 Self.Diag(SrcExpr.get()->getExprLoc(),
2246 diag::err_cast_pointer_from_non_pointer_int)
2247 << SrcType << SrcExpr.get()->getSourceRange();
2248 SrcExpr = ExprError();
2249 return;
2250 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00002251 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2252 DestType, Self);
John McCalla180f042011-10-06 23:25:11 +00002253 } else if (!SrcType->isArithmeticType()) {
2254 if (!DestType->isIntegralType(Self.Context) &&
2255 DestType->isArithmeticType()) {
2256 Self.Diag(SrcExpr.get()->getLocStart(),
2257 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002258 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002259 SrcExpr = ExprError();
2260 return;
2261 }
2262 }
2263
Joey Gouly19dbb202013-01-23 11:56:20 +00002264 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2265 if (DestType->isHalfType()) {
2266 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2267 << DestType << SrcExpr.get()->getSourceRange();
2268 SrcExpr = ExprError();
2269 return;
2270 }
Joey Gouly19dbb202013-01-23 11:56:20 +00002271 }
2272
John McCalla180f042011-10-06 23:25:11 +00002273 // ARC imposes extra restrictions on casts.
David Blaikie4e4d0842012-03-11 07:00:24 +00002274 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCalla180f042011-10-06 23:25:11 +00002275 checkObjCARCConversion(Sema::CCK_CStyleCast);
2276 if (SrcExpr.isInvalid())
2277 return;
2278
2279 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2280 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2281 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2282 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2283 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2284 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2285 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2286 Self.Diag(SrcExpr.get()->getLocStart(),
2287 diag::err_typecheck_incompatible_ownership)
2288 << SrcType << DestType << Sema::AA_Casting
2289 << SrcExpr.get()->getSourceRange();
2290 return;
2291 }
2292 }
2293 }
2294 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2295 Self.Diag(SrcExpr.get()->getLocStart(),
2296 diag::err_arc_convesion_of_weak_unavailable)
2297 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2298 SrcExpr = ExprError();
2299 return;
2300 }
2301 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00002302 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002303 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCalla180f042011-10-06 23:25:11 +00002304 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2305 if (SrcExpr.isInvalid())
2306 return;
2307
2308 if (Kind == CK_BitCast)
2309 checkCastAlign();
2310}
2311
2312ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2313 TypeSourceInfo *CastTypeInfo,
2314 SourceLocation RPLoc,
2315 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002316 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2317 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2318 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2319
David Blaikie4e4d0842012-03-11 07:00:24 +00002320 if (getLangOpts().CPlusPlus) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002321 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2322 isa<InitListExpr>(CastExpr));
John McCalla180f042011-10-06 23:25:11 +00002323 } else {
2324 Op.CheckCStyleCast();
2325 }
2326
John McCallb45ae252011-10-05 07:41:44 +00002327 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002328 return ExprError();
2329
John McCall5acb0c92011-10-17 18:40:02 +00002330 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2331 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2332 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002333}
2334
2335ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2336 SourceLocation LPLoc,
2337 Expr *CastExpr,
2338 SourceLocation RPLoc) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002339 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb45ae252011-10-05 07:41:44 +00002340 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2341 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2342 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2343
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002344 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb45ae252011-10-05 07:41:44 +00002345 if (Op.SrcExpr.isInvalid())
2346 return ExprError();
Daniel Jaspera770a4d2012-07-16 08:05:07 +00002347
2348 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2349 ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002350
John McCall5acb0c92011-10-17 18:40:02 +00002351 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2352 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2353 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002354}