blob: 63cb15db52905a1c5a3cfbf2c3dd99ff10617756 [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCall3cec19f2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCallcda80832013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000025#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000026#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000027using namespace clang;
28
Douglas Gregore81f58e2010-11-08 03:40:48 +000029
Douglas Gregore81f58e2010-11-08 03:40:48 +000030
Sebastian Redl9f831db2009-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 Redl842ef522008-11-08 13:00:26 +000045};
46
John McCallb50451a2011-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 McCall4124c492011-10-17 18:40:02 +000053 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-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 Gregore81f58e2010-11-08 03:40:48 +000062
John McCallb50451a2011-10-05 07:41:44 +000063 Sema &Self;
64 ExprResult SrcExpr;
65 QualType DestType;
66 QualType ResultType;
67 ExprValueKind ValueKind;
68 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000069 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000070 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000071 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000072
John McCallb50451a2011-10-05 07:41:44 +000073 SourceRange OpRange;
74 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000075
John McCall9776e432011-10-06 23:25:11 +000076 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000077 void CheckConstCast();
78 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000079 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000080 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000081 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000082 void CheckCStyleCast();
83
John McCall4124c492011-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 McCall9776e432011-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 McCallb50451a2011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000122 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall4124c492011-10-17 18:40:02 +0000123
John McCallb50451a2011-10-05 07:41:44 +0000124 Expr *src = SrcExpr.get();
John McCall4124c492011-10-17 18:40:02 +0000125 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
126 Sema::ACR_unbridged)
127 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000128 SrcExpr = src;
129 }
John McCall9776e432011-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 McCallb50451a2011-10-05 07:41:44 +0000141 };
142}
Sebastian Redl842ef522008-11-08 13:00:26 +0000143
John McCall31168b02011-06-15 23:02:42 +0000144static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-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 Gregorce950842011-01-26 21:04:06 +0000159 QualType DestType, bool CStyle,
160 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000161 CXXCastPath &BasePath,
162 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000163static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000164 QualType DestType, bool CStyle,
165 const SourceRange &OpRange,
166 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000167 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000168 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000169static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170 QualType DestType, bool CStyle,
171 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000172 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000173 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000174 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000175static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000177 const SourceRange &OpRange,
178 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000179 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000180 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000181 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000182static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000183 QualType SrcType,
184 QualType DestType,bool CStyle,
185 const SourceRange &OpRange,
186 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000187 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000188 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000189
John Wiegley01296292011-04-08 18:41:53 +0000190static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000191 QualType DestType,
192 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000193 const SourceRange &OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000194 unsigned &msg, CastKind &Kind,
195 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000196static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000197 QualType DestType,
198 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000199 const SourceRange &OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000200 unsigned &msg, CastKind &Kind,
201 CXXCastPath &BasePath,
202 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000203static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
204 QualType DestType, bool CStyle,
205 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000206static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000207 QualType DestType, bool CStyle,
208 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000209 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000210 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000211
Douglas Gregorb491ed32011-02-19 21:32:49 +0000212
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000213/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000214ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000216 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000217 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000218 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000219 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000220
Argyrios Kyrtzidis7451d1c2011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000227 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000228 // Check that there are no default arguments (C++ only).
229 CheckExtraCXXDefaultArguments(D);
230 }
231
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000232 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000233 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
234 SourceRange(LParenLoc, RParenLoc));
235}
236
John McCalldadc5752010-08-24 06:29:42 +0000237ExprResult
John McCalld377e042010-01-15 19:13:16 +0000238Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000239 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000240 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000241 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000242 QualType DestType = DestTInfo->getType();
243
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000244 // If the type is dependent, we won't do the semantic analysis now.
245 // FIXME: should we check this in a more fine-grained manner?
Eli Friedman71271082013-09-19 01:12:33 +0000246 bool TypeDependent = DestType->isDependentType() ||
247 Ex.get()->isTypeDependent() ||
248 Ex.get()->isValueDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000249
John McCallb50451a2011-10-05 07:41:44 +0000250 CastOperation Op(*this, DestType, E);
251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000253
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000254 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000255 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000256
257 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000258 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000259 Op.CheckConstCast();
260 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000261 return ExprError();
262 }
John McCall4124c492011-10-17 18:40:02 +0000263 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
264 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000265 OpLoc, Parens.getEnd(),
266 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000267
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000268 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000269 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000270 Op.CheckDynamicCast();
271 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000272 return ExprError();
273 }
John McCall4124c492011-10-17 18:40:02 +0000274 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
275 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
276 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000277 OpLoc, Parens.getEnd(),
278 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000279 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000280 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000281 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000282 Op.CheckReinterpretCast();
283 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000284 return ExprError();
285 }
John McCall4124c492011-10-17 18:40:02 +0000286 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
287 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
288 0, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000289 Parens.getEnd(),
290 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000291 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000292 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000293 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000294 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000295 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000296 return ExprError();
297 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000298
John McCall4124c492011-10-17 18:40:02 +0000299 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
300 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
301 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000302 OpLoc, Parens.getEnd(),
303 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000304 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000305 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000306}
307
John McCall909acf82011-02-14 18:34:10 +0000308/// Try to diagnose a failed overloaded cast. Returns true if
309/// diagnostics were emitted.
310static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
311 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000312 QualType destType,
313 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000314 switch (CT) {
315 // These cast kinds don't consider user-defined conversions.
316 case CT_Const:
317 case CT_Reinterpret:
318 case CT_Dynamic:
319 return false;
320
321 // These do.
322 case CT_Static:
323 case CT_CStyle:
324 case CT_Functional:
325 break;
326 }
327
328 QualType srcType = src->getType();
329 if (!destType->isRecordType() && !srcType->isRecordType())
330 return false;
331
332 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
333 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000334 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000335 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000336 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000337 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000338 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000339 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000340
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000341 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000342 switch (sequence.getFailureKind()) {
343 default: return false;
344
345 case InitializationSequence::FK_ConstructorOverloadFailed:
346 case InitializationSequence::FK_UserConversionOverloadFailed:
347 break;
348 }
349
350 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
351
352 unsigned msg = 0;
353 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
354
355 switch (sequence.getFailedOverloadResult()) {
356 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000357 case OR_No_Viable_Function:
358 if (candidates.empty())
359 msg = diag::err_ovl_no_conversion_in_cast;
360 else
361 msg = diag::err_ovl_no_viable_conversion_in_cast;
362 howManyCandidates = OCD_AllCandidates;
363 break;
364
365 case OR_Ambiguous:
366 msg = diag::err_ovl_ambiguous_conversion_in_cast;
367 howManyCandidates = OCD_ViableCandidates;
368 break;
369
370 case OR_Deleted:
371 msg = diag::err_ovl_deleted_conversion_in_cast;
372 howManyCandidates = OCD_ViableCandidates;
373 break;
374 }
375
376 S.Diag(range.getBegin(), msg)
377 << CT << srcType << destType
378 << range << src->getSourceRange();
379
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000380 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000381
382 return true;
383}
384
385/// Diagnose a failed cast.
386static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000387 SourceRange opRange, Expr *src, QualType destType,
388 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000389 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000390 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
391 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000392 return;
393
394 S.Diag(opRange.getBegin(), msg) << castType
395 << src->getType() << destType << opRange << src->getSourceRange();
396}
397
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000398/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
399/// this removes one level of indirection from both types, provided that they're
400/// the same kind of pointer (plain or to-member). Unlike the Sema function,
401/// this one doesn't care if the two pointers-to-member don't point into the
402/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000403static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000404 const PointerType *T1PtrType = T1->getAs<PointerType>(),
405 *T2PtrType = T2->getAs<PointerType>();
406 if (T1PtrType && T2PtrType) {
407 T1 = T1PtrType->getPointeeType();
408 T2 = T2PtrType->getPointeeType();
409 return true;
410 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000411 const ObjCObjectPointerType *T1ObjCPtrType =
412 T1->getAs<ObjCObjectPointerType>(),
413 *T2ObjCPtrType =
414 T2->getAs<ObjCObjectPointerType>();
415 if (T1ObjCPtrType) {
416 if (T2ObjCPtrType) {
417 T1 = T1ObjCPtrType->getPointeeType();
418 T2 = T2ObjCPtrType->getPointeeType();
419 return true;
420 }
421 else if (T2PtrType) {
422 T1 = T1ObjCPtrType->getPointeeType();
423 T2 = T2PtrType->getPointeeType();
424 return true;
425 }
426 }
427 else if (T2ObjCPtrType) {
428 if (T1PtrType) {
429 T2 = T2ObjCPtrType->getPointeeType();
430 T1 = T1PtrType->getPointeeType();
431 return true;
432 }
433 }
434
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000435 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
436 *T2MPType = T2->getAs<MemberPointerType>();
437 if (T1MPType && T2MPType) {
438 T1 = T1MPType->getPointeeType();
439 T2 = T2MPType->getPointeeType();
440 return true;
441 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000442
443 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
444 *T2BPType = T2->getAs<BlockPointerType>();
445 if (T1BPType && T2BPType) {
446 T1 = T1BPType->getPointeeType();
447 T2 = T2BPType->getPointeeType();
448 return true;
449 }
450
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000451 return false;
452}
453
Sebastian Redla5a77a62009-01-27 23:18:31 +0000454/// CastsAwayConstness - Check if the pointer conversion from SrcType to
455/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
456/// the cast checkers. Both arguments must denote pointer (possibly to member)
457/// types.
John McCall31168b02011-06-15 23:02:42 +0000458///
459/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
460///
461/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000462static bool
John McCall31168b02011-06-15 23:02:42 +0000463CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
464 bool CheckCVR, bool CheckObjCLifetime) {
465 // If the only checking we care about is for Objective-C lifetime qualifiers,
466 // and we're not in ARC mode, there's nothing to check.
467 if (!CheckCVR && CheckObjCLifetime &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000468 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000469 return false;
470
Sebastian Redla5a77a62009-01-27 23:18:31 +0000471 // Casting away constness is defined in C++ 5.2.11p8 with reference to
472 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
473 // the rules are non-trivial. So first we construct Tcv *...cv* as described
474 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000475 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
476 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000477 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000478 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
479 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000480 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000481
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000482 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
483 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000485
Douglas Gregorb472e932011-04-15 17:59:54 +0000486 // Find the qualifiers. We only care about cvr-qualifiers for the
487 // purpose of this check, because other qualifiers (address spaces,
488 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000489 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000490 // Determine the relevant qualifiers at this level.
491 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000492 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000493 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000494
495 Qualifiers RetainedSrcQuals, RetainedDestQuals;
496 if (CheckCVR) {
497 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
498 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
499 }
500
501 if (CheckObjCLifetime &&
502 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
503 return true;
504
505 cv1.push_back(RetainedSrcQuals);
506 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000507 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000508 if (cv1.empty())
509 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000510
511 // Construct void pointers with those qualifiers (in reverse order of
512 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000513 QualType SrcConstruct = Self.Context.VoidTy;
514 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000515 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000516 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
517 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000518 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000519 SrcConstruct
520 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
521 DestConstruct
522 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000523 }
524
525 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000526 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000527 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000528 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
529 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000530}
531
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000532/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
533/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
534/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000535void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000536 if (ValueKind == VK_RValue)
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000537 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedman42b199c2012-01-12 00:44:34 +0000538 else if (isPlaceholder())
539 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
540 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
541 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000542
John McCallb50451a2011-10-05 07:41:44 +0000543 QualType OrigSrcType = SrcExpr.get()->getType();
544 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000545
546 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
547 // or "pointer to cv void".
548
549 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000550 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000551 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000552 if (DestPointer) {
553 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000554 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000555 DestPointee = DestReference->getPointeeType();
556 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000557 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000558 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000559 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000560 return;
561 }
562
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000563 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000564 if (DestPointee->isVoidType()) {
565 assert(DestPointer && "Reference to void is not possible");
566 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000567 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000568 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000569 DestRange)) {
570 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000571 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000572 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000573 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000574 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000575 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000576 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000577 return;
578 }
579
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000580 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
581 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000582 // an lvalue of a complete class type, [...]. If T is an rvalue reference
583 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000584 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000585 QualType SrcPointee;
586 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000587 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000588 SrcPointee = SrcPointer->getPointeeType();
589 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000590 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000591 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000592 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000593 return;
594 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000595 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000596 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000597 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000598 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000599 }
600 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000601 } else {
602 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000603 }
604
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000605 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000606 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000607 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000608 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000609 SrcExpr.get())) {
610 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000611 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000612 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000613 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000614 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000615 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000616 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000617 return;
618 }
619
620 assert((DestPointer || DestReference) &&
621 "Bad destination non-ptr/ref slipped through.");
622 assert((DestRecord || DestPointee->isVoidType()) &&
623 "Bad destination pointee slipped through.");
624 assert(SrcRecord && "Bad source pointee slipped through.");
625
626 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
627 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000628 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000629 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000630 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000631 return;
632 }
633
634 // C++ 5.2.7p3: If the type of v is the same as the required result type,
635 // [except for cv].
636 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000637 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000638 return;
639 }
640
641 // C++ 5.2.7p5
642 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000643 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000644 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
645 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000646 &BasePath)) {
647 SrcExpr = ExprError();
648 return;
649 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000650
John McCalle3027922010-08-25 11:45:40 +0000651 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000652
653 // If we are casting to or through a virtual base class, we need a
654 // vtable.
655 if (Self.BasePathInvolvesVirtualBase(BasePath))
656 Self.MarkVTableUsed(OpRange.getBegin(),
657 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000658 return;
659 }
660
661 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000662 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000663 assert(SrcDecl && "Definition missing");
664 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000665 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000666 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000667 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000668 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000669 Self.MarkVTableUsed(OpRange.getBegin(),
670 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000671
Eli Friedman3ce27102013-09-24 23:21:41 +0000672 // dynamic_cast is not available with -fno-rtti.
673 // As an exception, dynamic_cast to void* is available because it doesn't
674 // use RTTI.
675 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000676 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
677 SrcExpr = ExprError();
678 return;
679 }
680
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000681 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000682 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000683}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000684
685/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
686/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
687/// like this:
688/// const char *str = "literal";
689/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000690void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000691 if (ValueKind == VK_RValue)
John Wiegley01296292011-04-08 18:41:53 +0000692 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedman42b199c2012-01-12 00:44:34 +0000693 else if (isPlaceholder())
694 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
695 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
696 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000697
698 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000699 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000700 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000701 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000702 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000703 SrcExpr = ExprError();
704 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000705}
706
John McCallcda80832013-03-22 02:58:14 +0000707/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
708/// or downcast between respective pointers or references.
709static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
710 QualType DestType,
711 SourceRange OpRange) {
712 QualType SrcType = SrcExpr->getType();
713 // When casting from pointer or reference, get pointee type; use original
714 // type otherwise.
715 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
716 const CXXRecordDecl *SrcRD =
717 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
718
John McCallf2abe192013-03-27 00:03:48 +0000719 // Examining subobjects for records is only possible if the complete and
720 // valid definition is available. Also, template instantiation is not
721 // allowed here.
722 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000723 return;
724
725 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
726
John McCallf2abe192013-03-27 00:03:48 +0000727 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000728 return;
729
730 enum {
731 ReinterpretUpcast,
732 ReinterpretDowncast
733 } ReinterpretKind;
734
735 CXXBasePaths BasePaths;
736
737 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
738 ReinterpretKind = ReinterpretUpcast;
739 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
740 ReinterpretKind = ReinterpretDowncast;
741 else
742 return;
743
744 bool VirtualBase = true;
745 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000746 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000747 E = BasePaths.end();
748 I != E; ++I) {
749 const CXXBasePath &Path = *I;
750 CharUnits Offset = CharUnits::Zero();
751 bool IsVirtual = false;
752 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
753 IElem != EElem; ++IElem) {
754 IsVirtual = IElem->Base->isVirtual();
755 if (IsVirtual)
756 break;
757 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
758 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000759 // Don't check if any base has invalid declaration or has no definition
760 // since it has no layout info.
761 const CXXRecordDecl *Class = IElem->Class,
762 *ClassDefinition = Class->getDefinition();
763 if (Class->isInvalidDecl() || !ClassDefinition ||
764 !ClassDefinition->isCompleteDefinition())
765 return;
766
John McCallcda80832013-03-22 02:58:14 +0000767 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000768 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000769 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
770 }
771 if (!IsVirtual) {
772 // Don't warn if any path is a non-virtually derived base at offset zero.
773 if (Offset.isZero())
774 return;
775 // Offset makes sense only for non-virtual bases.
776 else
777 NonZeroOffset = true;
778 }
779 VirtualBase = VirtualBase && IsVirtual;
780 }
781
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000782 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000783 assert((VirtualBase || NonZeroOffset) &&
784 "Should have returned if has non-virtual base with zero offset");
785
786 QualType BaseType =
787 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
788 QualType DerivedType =
789 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
790
Jordan Rose04a94d12013-03-28 19:09:40 +0000791 SourceLocation BeginLoc = OpRange.getBegin();
792 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000793 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000794 << OpRange;
795 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000796 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000797 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000798}
799
Sebastian Redl9f831db2009-07-25 15:41:38 +0000800/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
801/// valid.
802/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
803/// like this:
804/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000805void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000806 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley01296292011-04-08 18:41:53 +0000807 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedman42b199c2012-01-12 00:44:34 +0000808 else
809 checkNonOverloadPlaceholders();
810 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
811 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000812
813 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000814 TryCastResult tcr =
815 TryReinterpretCast(Self, SrcExpr, DestType,
816 /*CStyle*/false, OpRange, msg, Kind);
817 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000818 {
John Wiegley01296292011-04-08 18:41:53 +0000819 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
820 return;
821 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000822 //FIXME: &f<int>; is overloaded and resolvable
823 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000824 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000825 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000826 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000827
John McCall909acf82011-02-14 18:34:10 +0000828 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000829 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
830 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000831 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000832 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000833 } else if (tcr == TC_Success) {
834 if (Self.getLangOpts().ObjCAutoRefCount)
835 checkObjCARCConversion(Sema::CCK_OtherCast);
836 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000837 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000838}
839
840
841/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
842/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
843/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000844void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000845 if (isPlaceholder()) {
846 checkNonOverloadPlaceholders();
847 if (SrcExpr.isInvalid())
848 return;
849 }
850
Sebastian Redl9f831db2009-07-25 15:41:38 +0000851 // This test is outside everything else because it's the only case where
852 // a non-lvalue-reference target type does not lead to decay.
853 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000854 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000855 Kind = CK_ToVoid;
856
857 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000858 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000859 false, // Decay Function to ptr
860 true, // Complain
861 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000862 if (SrcExpr.isInvalid())
863 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000864 }
John McCall9776e432011-10-06 23:25:11 +0000865
866 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000867 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000868 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000869
John McCall50a2c2c2011-10-11 23:14:30 +0000870 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
871 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000872 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
873 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
874 return;
875 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000876
877 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000878 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000879 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000880 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000881 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000882 if (SrcExpr.isInvalid())
883 return;
884 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
885 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000886 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000887 << oe->getName() << DestType << OpRange
888 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000889 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000890 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000891 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
892 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000893 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000894 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000895 } else if (tcr == TC_Success) {
896 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000897 checkCastAlign();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000898 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smith507840d2011-11-29 22:48:16 +0000899 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000900 } else if (Kind == CK_BitCast) {
901 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000902 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000903}
904
905/// TryStaticCast - Check if a static cast can be performed, and do so if
906/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
907/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000908static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000909 QualType DestType,
910 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000911 const SourceRange &OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000912 CastKind &Kind, CXXCastPath &BasePath,
913 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000914 // Determine whether we have the semantics of a C-style cast.
915 bool CStyle
916 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
917
Sebastian Redl9f831db2009-07-25 15:41:38 +0000918 // The order the tests is not entirely arbitrary. There is one conversion
919 // that can be handled in two different ways. Given:
920 // struct A {};
921 // struct B : public A {
922 // B(); B(const A&);
923 // };
924 // const A &a = B();
925 // the cast static_cast<const B&>(a) could be seen as either a static
926 // reference downcast, or an explicit invocation of the user-defined
927 // conversion using B's conversion constructor.
928 // DR 427 specifies that the downcast is to be applied here.
929
930 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
931 // Done outside this function.
932
933 TryCastResult tcr;
934
935 // C++ 5.2.9p5, reference downcast.
936 // See the function for details.
937 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +0000938 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
939 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000940 if (tcr != TC_NotApplicable)
941 return tcr;
942
Douglas Gregor465184a2011-01-22 00:06:57 +0000943 // C++0x [expr.static.cast]p3:
944 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
945 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redld74dd492012-02-12 18:41:05 +0000946 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
947 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000948 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000949 return tcr;
950
951 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
952 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000953 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000954 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000955 if (SrcExpr.isInvalid())
956 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000957 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000958 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000959
Sebastian Redl9f831db2009-07-25 15:41:38 +0000960 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
961 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
962 // conversions, subject to further restrictions.
963 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
964 // of qualification conversions impossible.
965 // In the CStyle case, the earlier attempt to const_cast should have taken
966 // care of reverse qualification conversions.
967
John Wiegley01296292011-04-08 18:41:53 +0000968 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000969
Douglas Gregor0bf31402010-10-08 23:50:27 +0000970 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000971 // converted to an integral type. [...] A value of a scoped enumeration type
972 // can also be explicitly converted to a floating-point type [...].
973 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
974 if (Enum->getDecl()->isScoped()) {
975 if (DestType->isBooleanType()) {
976 Kind = CK_IntegralToBoolean;
977 return TC_Success;
978 } else if (DestType->isIntegralType(Self.Context)) {
979 Kind = CK_IntegralCast;
980 return TC_Success;
981 } else if (DestType->isRealFloatingType()) {
982 Kind = CK_IntegralToFloating;
983 return TC_Success;
984 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000985 }
986 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000987
Sebastian Redl9f831db2009-07-25 15:41:38 +0000988 // Reverse integral promotion/conversion. All such conversions are themselves
989 // again integral promotions or conversions and are thus already handled by
990 // p2 (TryDirectInitialization above).
991 // (Note: any data loss warnings should be suppressed.)
992 // The exception is the reverse of enum->integer, i.e. integer->enum (and
993 // enum->enum). See also C++ 5.2.9p7.
994 // The same goes for reverse floating point promotion/conversion and
995 // floating-integral conversions. Again, only floating->enum is relevant.
996 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +0000997 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +0000998 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000999 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001000 } else if (SrcType->isRealFloatingType()) {
1001 Kind = CK_FloatingToIntegral;
1002 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001003 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001004 }
1005
1006 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1007 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001008 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001009 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001010 if (tcr != TC_NotApplicable)
1011 return tcr;
1012
1013 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1014 // conversion. C++ 5.2.9p9 has additional information.
1015 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001016 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001017 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001018 if (tcr != TC_NotApplicable)
1019 return tcr;
1020
1021 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1022 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1023 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001024 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 QualType SrcPointee = SrcPointer->getPointeeType();
1026 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001027 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001028 QualType DestPointee = DestPointer->getPointeeType();
1029 if (DestPointee->isIncompleteOrObjectType()) {
1030 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001031 // to a qualifier violation. Note that we permit Objective-C lifetime
1032 // and GC qualifier mismatches here.
1033 if (!CStyle) {
1034 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1035 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1036 DestPointeeQuals.removeObjCGCAttr();
1037 DestPointeeQuals.removeObjCLifetime();
1038 SrcPointeeQuals.removeObjCGCAttr();
1039 SrcPointeeQuals.removeObjCLifetime();
1040 if (DestPointeeQuals != SrcPointeeQuals &&
1041 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1042 msg = diag::err_bad_cxx_cast_qualifiers_away;
1043 return TC_Failed;
1044 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045 }
John McCalle3027922010-08-25 11:45:40 +00001046 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001047 return TC_Success;
1048 }
1049 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001050 else if (DestType->isObjCObjectPointerType()) {
1051 // allow both c-style cast and static_cast of objective-c pointers as
1052 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001053 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001054 return TC_Success;
1055 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001056 else if (CStyle && DestType->isBlockPointerType()) {
1057 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001058 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001059 return TC_Success;
1060 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001061 }
1062 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001063 // Allow arbitray objective-c pointer conversion with static casts.
1064 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001065 DestType->isObjCObjectPointerType()) {
1066 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001067 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001068 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001069
Sebastian Redl9f831db2009-07-25 15:41:38 +00001070 // We tried everything. Everything! Nothing works! :-(
1071 return TC_NotApplicable;
1072}
1073
1074/// Tests whether a conversion according to N2844 is valid.
1075TryCastResult
1076TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +00001077 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1078 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +00001079 // C++0x [expr.static.cast]p3:
1080 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1081 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001082 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001083 if (!R)
1084 return TC_NotApplicable;
1085
Douglas Gregor465184a2011-01-22 00:06:57 +00001086 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001087 return TC_NotApplicable;
1088
1089 // Because we try the reference downcast before this function, from now on
1090 // this is the only cast possibility, so we issue an error if we fail now.
1091 // FIXME: Should allow casting away constness if CStyle.
1092 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001093 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001094 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001095 QualType FromType = SrcExpr->getType();
1096 QualType ToType = R->getPointeeType();
1097 if (CStyle) {
1098 FromType = FromType.getUnqualifiedType();
1099 ToType = ToType.getUnqualifiedType();
1100 }
1101
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001102 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +00001103 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +00001104 DerivedToBase, ObjCConversion,
1105 ObjCLifetimeConversion)
1106 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001107 msg = diag::err_bad_lvalue_to_rvalue_cast;
1108 return TC_Failed;
1109 }
1110
Douglas Gregorba278e22011-01-25 16:13:26 +00001111 if (DerivedToBase) {
1112 Kind = CK_DerivedToBase;
1113 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1114 /*DetectVirtual=*/true);
1115 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1116 return TC_NotApplicable;
1117
1118 Self.BuildBasePathArray(Paths, BasePath);
1119 } else
1120 Kind = CK_NoOp;
1121
Sebastian Redl9f831db2009-07-25 15:41:38 +00001122 return TC_Success;
1123}
1124
1125/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1126TryCastResult
1127TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1128 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001129 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001130 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001131 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1132 // cast to type "reference to cv2 D", where D is a class derived from B,
1133 // if a valid standard conversion from "pointer to D" to "pointer to B"
1134 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1135 // In addition, DR54 clarifies that the base must be accessible in the
1136 // current context. Although the wording of DR54 only applies to the pointer
1137 // variant of this rule, the intent is clearly for it to apply to the this
1138 // conversion as well.
1139
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001140 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001141 if (!DestReference) {
1142 return TC_NotApplicable;
1143 }
1144 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001145 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001146 // We know the left side is an lvalue reference, so we can suggest a reason.
1147 msg = diag::err_bad_cxx_cast_rvalue;
1148 return TC_NotApplicable;
1149 }
1150
1151 QualType DestPointee = DestReference->getPointeeType();
1152
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001153 return TryStaticDowncast(Self,
1154 Self.Context.getCanonicalType(SrcExpr->getType()),
1155 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001156 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1157 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001158}
1159
1160/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1161TryCastResult
1162TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001163 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001164 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001165 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001166 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1167 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1168 // is a class derived from B, if a valid standard conversion from "pointer
1169 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1170 // class of D.
1171 // In addition, DR54 clarifies that the base must be accessible in the
1172 // current context.
1173
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001174 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001175 if (!DestPointer) {
1176 return TC_NotApplicable;
1177 }
1178
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001179 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001180 if (!SrcPointer) {
1181 msg = diag::err_bad_static_cast_pointer_nonpointer;
1182 return TC_NotApplicable;
1183 }
1184
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001185 return TryStaticDowncast(Self,
1186 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1187 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001188 CStyle, OpRange, SrcType, DestType, msg, Kind,
1189 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001190}
1191
1192/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1193/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001194/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001195TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001196TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001197 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001198 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001199 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001200 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001201 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1202 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001203 return TC_NotApplicable;
1204
Sebastian Redl9f831db2009-07-25 15:41:38 +00001205 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001206 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001207 return TC_NotApplicable;
1208 }
1209
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001210 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001211 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001212 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1213 return TC_NotApplicable;
1214 }
1215
1216 // Target type does derive from source type. Now we're serious. If an error
1217 // appears now, it's not ignored.
1218 // This may not be entirely in line with the standard. Take for example:
1219 // struct A {};
1220 // struct B : virtual A {
1221 // B(A&);
1222 // };
Mike Stump11289f42009-09-09 15:08:12 +00001223 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001224 // void f()
1225 // {
1226 // (void)static_cast<const B&>(*((A*)0));
1227 // }
1228 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1229 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1230 // However, both GCC and Comeau reject this example, and accepting it would
1231 // mean more complex code if we're to preserve the nice error message.
1232 // FIXME: Being 100% compliant here would be nice to have.
1233
1234 // Must preserve cv, as always, unless we're in C-style mode.
1235 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001236 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001237 return TC_Failed;
1238 }
1239
1240 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1241 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1242 // that it builds the paths in reverse order.
1243 // To sum up: record all paths to the base and build a nice string from
1244 // them. Use it to spice up the error message.
1245 if (!Paths.isRecordingPaths()) {
1246 Paths.clear();
1247 Paths.setRecordingPaths(true);
1248 Self.IsDerivedFrom(DestType, SrcType, Paths);
1249 }
1250 std::string PathDisplayStr;
1251 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001252 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001253 PI != PE; ++PI) {
1254 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1255 // We haven't displayed a path to this particular base
1256 // class subobject yet.
1257 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001258 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1259 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001260 EI != EE; ++EI)
1261 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001262 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001263 }
1264 }
1265
1266 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001267 << QualType(SrcType).getUnqualifiedType()
1268 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001269 << PathDisplayStr << OpRange;
1270 msg = 0;
1271 return TC_Failed;
1272 }
1273
1274 if (Paths.getDetectedVirtual() != 0) {
1275 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1276 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1277 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1278 msg = 0;
1279 return TC_Failed;
1280 }
1281
John McCallfe9cf0a2011-02-14 23:21:33 +00001282 if (!CStyle) {
1283 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1284 SrcType, DestType,
1285 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001286 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001287 case Sema::AR_accessible:
1288 case Sema::AR_delayed: // be optimistic
1289 case Sema::AR_dependent: // be optimistic
1290 break;
1291
1292 case Sema::AR_inaccessible:
1293 msg = 0;
1294 return TC_Failed;
1295 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001296 }
1297
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001298 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001299 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001300 return TC_Success;
1301}
1302
1303/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1304/// C++ 5.2.9p9 is valid:
1305///
1306/// An rvalue of type "pointer to member of D of type cv1 T" can be
1307/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1308/// where B is a base class of D [...].
1309///
1310TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001311TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001312 QualType DestType, bool CStyle,
1313 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001314 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001315 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001316 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001317 if (!DestMemPtr)
1318 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001319
1320 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001321 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001322 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001323 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001324 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001325 FoundOverload)) {
1326 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1327 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1328 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1329 WasOverloadedFunction = true;
1330 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001331 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001332
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001333 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001334 if (!SrcMemPtr) {
1335 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1336 return TC_NotApplicable;
1337 }
1338
1339 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001340 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1341 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001342 return TC_NotApplicable;
1343
1344 // B base of D
1345 QualType SrcClass(SrcMemPtr->getClass(), 0);
1346 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001347 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001348 /*DetectVirtual=*/true);
David Majnemerf5b93792014-01-16 12:02:55 +00001349 if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
1350 !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001351 return TC_NotApplicable;
1352 }
1353
1354 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +00001355 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001356 Paths.clear();
1357 Paths.setRecordingPaths(true);
1358 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1359 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001360 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001361 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1362 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1363 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1364 msg = 0;
1365 return TC_Failed;
1366 }
1367
1368 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1369 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1370 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1371 msg = 0;
1372 return TC_Failed;
1373 }
1374
John McCallfe9cf0a2011-02-14 23:21:33 +00001375 if (!CStyle) {
1376 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1377 DestClass, SrcClass,
1378 Paths.front(),
1379 diag::err_upcast_to_inaccessible_base)) {
1380 case Sema::AR_accessible:
1381 case Sema::AR_delayed:
1382 case Sema::AR_dependent:
1383 // Optimistically assume that the delayed and dependent cases
1384 // will work out.
1385 break;
1386
1387 case Sema::AR_inaccessible:
1388 msg = 0;
1389 return TC_Failed;
1390 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001391 }
1392
Douglas Gregorc934bc82010-03-07 23:24:59 +00001393 if (WasOverloadedFunction) {
1394 // Resolve the address of the overloaded function again, this time
1395 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001396 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001397 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001398 true,
1399 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001400 if (!Fn) {
1401 msg = 0;
1402 return TC_Failed;
1403 }
1404
John McCall16df1e52010-03-30 21:47:33 +00001405 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001406 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001407 msg = 0;
1408 return TC_Failed;
1409 }
1410 }
1411
Anders Carlssonb78feca2010-04-24 19:22:20 +00001412 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001413 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001414 return TC_Success;
1415}
1416
1417/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1418/// is valid:
1419///
1420/// An expression e can be explicitly converted to a type T using a
1421/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1422TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001423TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001424 Sema::CheckedConversionKind CCK,
1425 const SourceRange &OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001426 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001427 if (DestType->isRecordType()) {
1428 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001429 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001430 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001431 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001432 msg = 0;
1433 return TC_Failed;
1434 }
1435 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001436
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001437 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1438 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001439 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001440 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001441 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001442 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001443 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001444 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001445 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001446 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001447
1448 // At this point of CheckStaticCast, if the destination is a reference,
1449 // or the expression is an overload expression this has to work.
1450 // There is no other way that works.
1451 // On the other hand, if we're checking a C-style cast, we've still got
1452 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001453 bool CStyle
1454 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001455 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001456 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001457
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001458 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001459 if (Result.isInvalid()) {
1460 msg = 0;
1461 return TC_Failed;
1462 }
1463
Douglas Gregorb33eed02010-04-16 22:09:46 +00001464 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001465 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001466 else
John McCalle3027922010-08-25 11:45:40 +00001467 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001468
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001469 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001470 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001471}
1472
1473/// TryConstCast - See if a const_cast from source to destination is allowed,
1474/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001475static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1476 QualType DestType, bool CStyle,
1477 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001478 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001479 QualType SrcType = SrcExpr.get()->getType();
1480 bool NeedToMaterializeTemporary = false;
1481
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001482 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001483 // C++11 5.2.11p4:
1484 // if a pointer to T1 can be explicitly converted to the type "pointer to
1485 // T2" using a const_cast, then the following conversions can also be
1486 // made:
1487 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1488 // type T2 using the cast const_cast<T2&>;
1489 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1490 // type T2 using the cast const_cast<T2&&>; and
1491 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1492 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1493
1494 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001495 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1496 // is C-style, static_cast might find a way, so we simply suggest a
1497 // message and tell the parent to keep searching.
1498 msg = diag::err_bad_cxx_cast_rvalue;
1499 return TC_NotApplicable;
1500 }
1501
Richard Smith82c9b512013-06-14 22:27:52 +00001502 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1503 if (!SrcType->isRecordType()) {
1504 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1505 // this is C-style, static_cast can do this.
1506 msg = diag::err_bad_cxx_cast_rvalue;
1507 return TC_NotApplicable;
1508 }
1509
1510 // Materialize the class prvalue so that the const_cast can bind a
1511 // reference to it.
1512 NeedToMaterializeTemporary = true;
1513 }
1514
John McCalld25db7e2013-05-06 21:39:12 +00001515 // It's not completely clear under the standard whether we can
1516 // const_cast bit-field gl-values. Doing so would not be
1517 // intrinsically complicated, but for now, we say no for
1518 // consistency with other compilers and await the word of the
1519 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001520 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001521 msg = diag::err_bad_cxx_cast_bitfield;
1522 return TC_NotApplicable;
1523 }
1524
Sebastian Redl9f831db2009-07-25 15:41:38 +00001525 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1526 SrcType = Self.Context.getPointerType(SrcType);
1527 }
1528
1529 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1530 // the rules for const_cast are the same as those used for pointers.
1531
John McCall0e704f72010-05-18 09:35:29 +00001532 if (!DestType->isPointerType() &&
1533 !DestType->isMemberPointerType() &&
1534 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001535 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1536 // was a reference type, we converted it to a pointer above.
1537 // The status of rvalue references isn't entirely clear, but it looks like
1538 // conversion to them is simply invalid.
1539 // C++ 5.2.11p3: For two pointer types [...]
1540 if (!CStyle)
1541 msg = diag::err_bad_const_cast_dest;
1542 return TC_NotApplicable;
1543 }
1544 if (DestType->isFunctionPointerType() ||
1545 DestType->isMemberFunctionPointerType()) {
1546 // Cannot cast direct function pointers.
1547 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1548 // T is the ultimate pointee of source and target type.
1549 if (!CStyle)
1550 msg = diag::err_bad_const_cast_dest;
1551 return TC_NotApplicable;
1552 }
1553 SrcType = Self.Context.getCanonicalType(SrcType);
1554
1555 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1556 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001557 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1558 // in multi-level pointers may change, but the level count must be the same,
1559 // as must be the final pointee type.
1560 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001561 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001562 Qualifiers SrcQuals, DestQuals;
1563 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1564 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1565
1566 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1567 // the other qualifiers (e.g., address spaces) are identical.
1568 SrcQuals.removeCVRQualifiers();
1569 DestQuals.removeCVRQualifiers();
1570 if (SrcQuals != DestQuals)
1571 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001572 }
1573
1574 // Since we're dealing in canonical types, the remainder must be the same.
1575 if (SrcType != DestType)
1576 return TC_NotApplicable;
1577
Richard Smith82c9b512013-06-14 22:27:52 +00001578 if (NeedToMaterializeTemporary)
1579 // This is a const_cast from a class prvalue to an rvalue reference type.
1580 // Materialize a temporary to store the result of the conversion.
1581 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1582 SrcType, SrcExpr.take(), /*IsLValueReference*/ false,
1583 /*ExtendingDecl*/ 0);
1584
Sebastian Redl9f831db2009-07-25 15:41:38 +00001585 return TC_Success;
1586}
1587
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001588// Checks for undefined behavior in reinterpret_cast.
1589// The cases that is checked for is:
1590// *reinterpret_cast<T*>(&a)
1591// reinterpret_cast<T&>(a)
1592// where accessing 'a' as type 'T' will result in undefined behavior.
1593void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1594 bool IsDereference,
1595 SourceRange Range) {
1596 unsigned DiagID = IsDereference ?
1597 diag::warn_pointer_indirection_from_incompatible_type :
1598 diag::warn_undefined_reinterpret_cast;
1599
1600 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00001601 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001602 return;
1603 }
1604
1605 QualType SrcTy, DestTy;
1606 if (IsDereference) {
1607 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1608 return;
1609 }
1610 SrcTy = SrcType->getPointeeType();
1611 DestTy = DestType->getPointeeType();
1612 } else {
1613 if (!DestType->getAs<ReferenceType>()) {
1614 return;
1615 }
1616 SrcTy = SrcType;
1617 DestTy = DestType->getPointeeType();
1618 }
1619
1620 // Cast is compatible if the types are the same.
1621 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1622 return;
1623 }
1624 // or one of the types is a char or void type
1625 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1626 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1627 return;
1628 }
1629 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001630 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001631 return;
1632 }
1633
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001634 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001635 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1636 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1637 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1638 return;
1639 }
1640 }
1641
1642 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1643}
Douglas Gregor1beec452011-03-12 01:48:56 +00001644
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001645static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1646 QualType DestType) {
1647 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001648 if (Self.Context.hasSameType(SrcType, DestType))
1649 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001650 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1651 if (SrcPtrTy->isObjCSelType()) {
1652 QualType DT = DestType;
1653 if (isa<PointerType>(DestType))
1654 DT = DestType->getPointeeType();
1655 if (!DT.getUnqualifiedType()->isVoidType())
1656 Self.Diag(SrcExpr.get()->getExprLoc(),
1657 diag::warn_cast_pointer_from_sel)
1658 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1659 }
1660}
1661
David Blaikie282ad872012-10-16 18:53:14 +00001662static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1663 const Expr *SrcExpr, QualType DestType,
1664 Sema &Self) {
1665 QualType SrcType = SrcExpr->getType();
1666
1667 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1668 // are not explicit design choices, but consistent with GCC's behavior.
1669 // Feel free to modify them if you've reason/evidence for an alternative.
1670 if (CStyle && SrcType->isIntegralType(Self.Context)
1671 && !SrcType->isBooleanType()
1672 && !SrcType->isEnumeralType()
1673 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001674 && Self.Context.getTypeSize(DestType) >
1675 Self.Context.getTypeSize(SrcType)) {
1676 // Separate between casts to void* and non-void* pointers.
1677 // Some APIs use (abuse) void* for something like a user context,
1678 // and often that value is an integer even if it isn't a pointer itself.
1679 // Having a separate warning flag allows users to control the warning
1680 // for their workflow.
1681 unsigned Diag = DestType->isVoidPointerType() ?
1682 diag::warn_int_to_void_pointer_cast
1683 : diag::warn_int_to_pointer_cast;
1684 Self.Diag(Loc, Diag) << SrcType << DestType;
1685 }
David Blaikie282ad872012-10-16 18:53:14 +00001686}
1687
John Wiegley01296292011-04-08 18:41:53 +00001688static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001689 QualType DestType, bool CStyle,
1690 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001691 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001692 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001693 bool IsLValueCast = false;
1694
Sebastian Redl9f831db2009-07-25 15:41:38 +00001695 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001696 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001697
1698 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001699 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1700 if (SrcType == Self.Context.OverloadTy) {
John McCall50a2c2c2011-10-11 23:14:30 +00001701 // ... unless foo<int> resolves to an lvalue unambiguously.
1702 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1703 // like it?
1704 ExprResult SingleFunctionExpr = SrcExpr;
1705 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1706 SingleFunctionExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001707 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall50a2c2c2011-10-11 23:14:30 +00001708 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001709 SrcExpr = SingleFunctionExpr;
John Wiegley01296292011-04-08 18:41:53 +00001710 SrcType = SrcExpr.get()->getType();
John McCall50a2c2c2011-10-11 23:14:30 +00001711 } else {
Douglas Gregorb491ed32011-02-19 21:32:49 +00001712 return TC_NotApplicable;
John McCall50a2c2c2011-10-11 23:14:30 +00001713 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001714 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001715
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001716 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001717 if (!SrcExpr.get()->isGLValue()) {
1718 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1719 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001720 msg = diag::err_bad_cxx_cast_rvalue;
1721 return TC_NotApplicable;
1722 }
1723
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001724 if (!CStyle) {
1725 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1726 /*isDereference=*/false, OpRange);
1727 }
1728
Sebastian Redl9f831db2009-07-25 15:41:38 +00001729 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1730 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1731 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001732
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001733 const char *inappropriate = 0;
1734 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001735 case OK_Ordinary:
1736 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001737 case OK_BitField: inappropriate = "bit-field"; break;
1738 case OK_VectorComponent: inappropriate = "vector element"; break;
1739 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001740 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1741 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001742 }
1743 if (inappropriate) {
1744 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1745 << inappropriate << DestType
1746 << OpRange << SrcExpr.get()->getSourceRange();
1747 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001748 return TC_NotApplicable;
1749 }
1750
Sebastian Redl9f831db2009-07-25 15:41:38 +00001751 // This code does this transformation for the checked types.
1752 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1753 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001754
Douglas Gregor51954272010-07-13 23:17:26 +00001755 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001756 }
1757
1758 // Canonicalize source for comparison.
1759 SrcType = Self.Context.getCanonicalType(SrcType);
1760
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001761 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1762 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001763 if (DestMemPtr && SrcMemPtr) {
1764 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1765 // can be explicitly converted to an rvalue of type "pointer to member
1766 // of Y of type T2" if T1 and T2 are both function types or both object
1767 // types.
1768 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1769 SrcMemPtr->getPointeeType()->isFunctionType())
1770 return TC_NotApplicable;
1771
1772 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1773 // constness.
1774 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1775 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001776 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1777 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001778 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001779 return TC_Failed;
1780 }
1781
Charles Davisebab1ed2010-08-16 05:30:44 +00001782 // Don't allow casting between member pointers of different sizes.
1783 if (Self.Context.getTypeSize(DestMemPtr) !=
1784 Self.Context.getTypeSize(SrcMemPtr)) {
1785 msg = diag::err_bad_cxx_cast_member_pointer_size;
1786 return TC_Failed;
1787 }
1788
Sebastian Redl9f831db2009-07-25 15:41:38 +00001789 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00001790 assert(!IsLValueCast);
1791 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001792 return TC_Success;
1793 }
1794
1795 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001796 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001797 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1798 // type large enough to hold it. A value of std::nullptr_t can be
1799 // converted to an integral type; the conversion has the same meaning
1800 // and validity as a conversion of (void*)0 to the integral type.
1801 if (Self.Context.getTypeSize(SrcType) >
1802 Self.Context.getTypeSize(DestType)) {
1803 msg = diag::err_bad_reinterpret_cast_small_int;
1804 return TC_Failed;
1805 }
John McCalle3027922010-08-25 11:45:40 +00001806 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001807 return TC_Success;
1808 }
1809
Anders Carlsson570af5d2009-09-16 19:19:43 +00001810 bool destIsVector = DestType->isVectorType();
1811 bool srcIsVector = SrcType->isVectorType();
1812 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001813 // FIXME: Should this also apply to floating point types?
1814 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1815 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001816
1817 // Check if this is a cast between a vector and something else.
1818 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1819 !(srcIsVector && destIsVector))
1820 return TC_NotApplicable;
1821
1822 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001823 if (Self.Context.getTypeSize(SrcType)
1824 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001825 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001826 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001827 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001828
1829 if (destIsScalar)
1830 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1831 else if (srcIsScalar)
1832 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1833 else
1834 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1835
1836 return TC_Failed;
1837 }
Chad Rosier96c755d12012-02-03 02:54:37 +00001838
1839 if (SrcType == DestType) {
1840 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1841 // restrictions, a cast to the same type is allowed so long as it does not
1842 // cast away constness. In C++98, the intent was not entirely clear here,
1843 // since all other paragraphs explicitly forbid casts to the same type.
1844 // C++11 clarifies this case with p2.
1845 //
1846 // The only allowed types are: integral, enumeration, pointer, or
1847 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1848 Kind = CK_NoOp;
1849 TryCastResult Result = TC_NotApplicable;
1850 if (SrcType->isIntegralOrEnumerationType() ||
1851 SrcType->isAnyPointerType() ||
1852 SrcType->isMemberPointerType() ||
1853 SrcType->isBlockPointerType()) {
1854 Result = TC_Success;
1855 }
1856 return Result;
1857 }
1858
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001859 bool destIsPtr = DestType->isAnyPointerType() ||
1860 DestType->isBlockPointerType();
1861 bool srcIsPtr = SrcType->isAnyPointerType() ||
1862 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001863 if (!destIsPtr && !srcIsPtr) {
1864 // Except for std::nullptr_t->integer and lvalue->reference, which are
1865 // handled above, at least one of the two arguments must be a pointer.
1866 return TC_NotApplicable;
1867 }
1868
Douglas Gregor6972a622010-06-16 00:35:25 +00001869 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001870 assert(srcIsPtr && "One type must be a pointer");
1871 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001872 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00001873 // integral type size doesn't matter (except we don't allow bool).
1874 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1875 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00001876 if ((Self.Context.getTypeSize(SrcType) >
1877 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00001878 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001879 msg = diag::err_bad_reinterpret_cast_small_int;
1880 return TC_Failed;
1881 }
John McCalle3027922010-08-25 11:45:40 +00001882 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001883 return TC_Success;
1884 }
1885
Douglas Gregorb90df602010-06-16 00:17:44 +00001886 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001887 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00001888 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1889 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001890 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1891 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001892 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1893 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001894 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001895 return TC_Success;
1896 }
1897
1898 if (!destIsPtr || !srcIsPtr) {
1899 // With the valid non-pointer conversions out of the way, we can be even
1900 // more stringent.
1901 return TC_NotApplicable;
1902 }
1903
1904 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1905 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001906 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1907 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001908 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001909 return TC_Failed;
1910 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001911
1912 // Cannot convert between block pointers and Objective-C object pointers.
1913 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1914 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1915 return TC_NotApplicable;
1916
John McCall9320b872011-09-09 05:25:32 +00001917 if (IsLValueCast) {
1918 Kind = CK_LValueBitCast;
1919 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001920 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001921 } else if (DestType->isBlockPointerType()) {
1922 if (!SrcType->isBlockPointerType()) {
1923 Kind = CK_AnyPointerToBlockPointerCast;
1924 } else {
1925 Kind = CK_BitCast;
1926 }
1927 } else {
1928 Kind = CK_BitCast;
1929 }
1930
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001931 // Any pointer can be cast to an Objective-C pointer type with a C-style
1932 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001933 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001934 return TC_Success;
1935 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001936 if (CStyle)
1937 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1938
Sebastian Redl9f831db2009-07-25 15:41:38 +00001939 // Not casting away constness, so the only remaining check is for compatible
1940 // pointer categories.
1941
1942 if (SrcType->isFunctionPointerType()) {
1943 if (DestType->isFunctionPointerType()) {
1944 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1945 // a pointer to a function of a different type.
1946 return TC_Success;
1947 }
1948
1949 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1950 // an object type or vice versa is conditionally-supported.
1951 // Compilers support it in C++03 too, though, because it's necessary for
1952 // casting the return value of dlsym() and GetProcAddress().
1953 // FIXME: Conditionally-supported behavior should be configurable in the
1954 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00001955 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001956 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001957 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1958 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001959 return TC_Success;
1960 }
1961
1962 if (DestType->isFunctionPointerType()) {
1963 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00001964 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001965 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001966 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1967 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001968 return TC_Success;
1969 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001970
Sebastian Redl9f831db2009-07-25 15:41:38 +00001971 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1972 // a pointer to an object of different type.
1973 // Void pointers are not specified, but supported by every compiler out there.
1974 // So we finish by allowing everything that remains - it's got to be two
1975 // object pointers.
1976 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001977}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001978
Sebastian Redld74dd492012-02-12 18:41:05 +00001979void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1980 bool ListInitialization) {
John McCall9776e432011-10-06 23:25:11 +00001981 // Handle placeholders.
1982 if (isPlaceholder()) {
1983 // C-style casts can resolve __unknown_any types.
1984 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1985 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1986 SrcExpr.get(), Kind,
1987 ValueKind, BasePath);
1988 return;
1989 }
John McCallb50451a2011-10-05 07:41:44 +00001990
John McCall9776e432011-10-06 23:25:11 +00001991 checkNonOverloadPlaceholders();
1992 if (SrcExpr.isInvalid())
1993 return;
John McCalla072f5d2011-10-17 17:42:19 +00001994 }
John McCall9776e432011-10-06 23:25:11 +00001995
1996 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00001997 // This test is outside everything else because it's the only case where
1998 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00001999 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002000 Kind = CK_ToVoid;
2001
John McCall9776e432011-10-06 23:25:11 +00002002 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002003 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2004 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002005 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002006 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002007 if (SrcExpr.isInvalid())
2008 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002009 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002010
John McCall9776e432011-10-06 23:25:11 +00002011 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
John McCallb50451a2011-10-05 07:41:44 +00002012 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002013 }
2014
Sebastian Redl9f831db2009-07-25 15:41:38 +00002015 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002016 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2017 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002018 assert(Kind == CK_Dependent);
2019 return;
John McCall8cb679e2010-11-15 09:13:47 +00002020 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002021
John McCall50a2c2c2011-10-11 23:14:30 +00002022 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2023 !isPlaceholder(BuiltinType::Overload)) {
John McCallb50451a2011-10-05 07:41:44 +00002024 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2025 if (SrcExpr.isInvalid())
2026 return;
John Wiegley01296292011-04-08 18:41:53 +00002027 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002028
John McCall3aef3d82011-04-10 19:13:55 +00002029 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002030 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002031 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002032 && (SrcExpr.get()->getType()->isIntegerType()
2033 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002034 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00002035 return;
John McCall3aef3d82011-04-10 19:13:55 +00002036 }
2037
Sebastian Redl9f831db2009-07-25 15:41:38 +00002038 // C++ [expr.cast]p5: The conversions performed by
2039 // - a const_cast,
2040 // - a static_cast,
2041 // - a static_cast followed by a const_cast,
2042 // - a reinterpret_cast, or
2043 // - a reinterpret_cast followed by a const_cast,
2044 // can be performed using the cast notation of explicit type conversion.
2045 // [...] If a conversion can be interpreted in more than one of the ways
2046 // listed above, the interpretation that appears first in the list is used,
2047 // even if a cast resulting from that interpretation is ill-formed.
2048 // In plain language, this means trying a const_cast ...
2049 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002050 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002051 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002052 if (SrcExpr.isInvalid())
2053 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002054 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002055 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002056
John McCall31168b02011-06-15 23:02:42 +00002057 Sema::CheckedConversionKind CCK
2058 = FunctionalStyle? Sema::CCK_FunctionalCast
2059 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002060 if (tcr == TC_NotApplicable) {
2061 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002062 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002063 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002064 if (SrcExpr.isInvalid())
2065 return;
2066
Sebastian Redl9f831db2009-07-25 15:41:38 +00002067 if (tcr == TC_NotApplicable) {
2068 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002069 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2070 OpRange, msg, Kind);
2071 if (SrcExpr.isInvalid())
2072 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002073 }
2074 }
2075
David Blaikiebbafb8a2012-03-11 07:00:24 +00002076 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002077 checkObjCARCConversion(CCK);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002078 else if (Self.getLangOpts().ObjC1 && tcr == TC_Success)
2079 Self.CheckTollFreeBridgeCast(DestType, SrcExpr.get());
John McCall31168b02011-06-15 23:02:42 +00002080
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002081 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002082 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002083 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002084 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2085 DestType,
2086 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002087 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00002088
Richard Trieu70d14f52011-04-16 01:09:30 +00002089 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002090 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00002091
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002092 } else {
John McCallb50451a2011-10-05 07:41:44 +00002093 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002094 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002095 }
John McCallb50451a2011-10-05 07:41:44 +00002096 } else if (Kind == CK_BitCast) {
2097 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002098 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002099
John McCallb50451a2011-10-05 07:41:44 +00002100 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002101 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002102 SrcExpr = ExprError();
2103}
2104
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002105/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2106/// non-matching type. Such as enum function call to int, int call to
2107/// pointer; etc. Cast to 'void' is an exception.
2108static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2109 QualType DestType) {
2110 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2111 SrcExpr.get()->getExprLoc())
2112 == DiagnosticsEngine::Ignored)
2113 return;
2114
2115 if (!isa<CallExpr>(SrcExpr.get()))
2116 return;
2117
2118 QualType SrcType = SrcExpr.get()->getType();
2119 if (DestType.getUnqualifiedType()->isVoidType())
2120 return;
2121 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2122 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2123 return;
2124 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2125 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2126 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2127 return;
2128 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2129 return;
2130 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2131 return;
2132 if (SrcType->isComplexType() && DestType->isComplexType())
2133 return;
2134 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2135 return;
2136
2137 Self.Diag(SrcExpr.get()->getExprLoc(),
2138 diag::warn_bad_function_cast)
2139 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2140}
2141
John McCall9776e432011-10-06 23:25:11 +00002142/// Check the semantics of a C-style cast operation, in C.
2143void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002144 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002145
John McCall4124c492011-10-17 18:40:02 +00002146 // C-style casts can resolve __unknown_any types.
2147 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2148 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2149 SrcExpr.get(), Kind,
2150 ValueKind, BasePath);
2151 return;
2152 }
John McCall9776e432011-10-06 23:25:11 +00002153
2154 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2155 // type needs to be scalar.
2156 if (DestType->isVoidType()) {
2157 // We don't necessarily do lvalue-to-rvalue conversions on this.
2158 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2159 if (SrcExpr.isInvalid())
2160 return;
2161
2162 // Cast to void allows any expr type.
2163 Kind = CK_ToVoid;
2164 return;
2165 }
2166
2167 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2168 if (SrcExpr.isInvalid())
2169 return;
2170 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002171
John McCall4124c492011-10-17 18:40:02 +00002172 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002173
Joey Gouly8fc32f02014-01-14 12:47:29 +00002174 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2175 // address space B is illegal.
2176 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2177 SrcType->isPointerType()) {
2178 if (DestType->getPointeeType().getAddressSpace() !=
2179 SrcType->getPointeeType().getAddressSpace()) {
2180 Self.Diag(OpRange.getBegin(),
2181 diag::err_typecheck_incompatible_address_space)
2182 << SrcType << DestType << Sema::AA_Casting
2183 << SrcExpr.get()->getSourceRange();
2184 SrcExpr = ExprError();
2185 return;
2186 }
2187 }
2188
John McCall9776e432011-10-06 23:25:11 +00002189 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2190 diag::err_typecheck_cast_to_incomplete)) {
2191 SrcExpr = ExprError();
2192 return;
2193 }
2194
2195 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2196 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2197
2198 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2199 // GCC struct/union extension: allow cast to self.
2200 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2201 << DestType << SrcExpr.get()->getSourceRange();
2202 Kind = CK_NoOp;
2203 return;
2204 }
2205
2206 // GCC's cast to union extension.
2207 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2208 RecordDecl *RD = DestRecordTy->getDecl();
2209 RecordDecl::field_iterator Field, FieldEnd;
2210 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2211 Field != FieldEnd; ++Field) {
2212 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2213 !Field->isUnnamedBitfield()) {
2214 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2215 << SrcExpr.get()->getSourceRange();
2216 break;
2217 }
2218 }
2219 if (Field == FieldEnd) {
2220 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2221 << SrcType << SrcExpr.get()->getSourceRange();
2222 SrcExpr = ExprError();
2223 return;
2224 }
2225 Kind = CK_ToUnion;
2226 return;
2227 }
2228
2229 // Reject any other conversions to non-scalar types.
2230 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2231 << DestType << SrcExpr.get()->getSourceRange();
2232 SrcExpr = ExprError();
2233 return;
2234 }
2235
2236 // The type we're casting to is known to be a scalar or vector.
2237
2238 // Require the operand to be a scalar or vector.
2239 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2240 Self.Diag(SrcExpr.get()->getExprLoc(),
2241 diag::err_typecheck_expect_scalar_operand)
2242 << SrcType << SrcExpr.get()->getSourceRange();
2243 SrcExpr = ExprError();
2244 return;
2245 }
2246
2247 if (DestType->isExtVectorType()) {
2248 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2249 return;
2250 }
2251
2252 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2253 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2254 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2255 Kind = CK_VectorSplat;
2256 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2257 SrcExpr = ExprError();
2258 }
2259 return;
2260 }
2261
2262 if (SrcType->isVectorType()) {
2263 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2264 SrcExpr = ExprError();
2265 return;
2266 }
2267
2268 // The source and target types are both scalars, i.e.
2269 // - arithmetic types (fundamental, enum, and complex)
2270 // - all kinds of pointers
2271 // Note that member pointers were filtered out with C++, above.
2272
2273 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2274 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2275 SrcExpr = ExprError();
2276 return;
2277 }
2278
2279 // If either type is a pointer, the other type has to be either an
2280 // integer or a pointer.
2281 if (!DestType->isArithmeticType()) {
2282 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2283 Self.Diag(SrcExpr.get()->getExprLoc(),
2284 diag::err_cast_pointer_from_non_pointer_int)
2285 << SrcType << SrcExpr.get()->getSourceRange();
2286 SrcExpr = ExprError();
2287 return;
2288 }
David Blaikie282ad872012-10-16 18:53:14 +00002289 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2290 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002291 } else if (!SrcType->isArithmeticType()) {
2292 if (!DestType->isIntegralType(Self.Context) &&
2293 DestType->isArithmeticType()) {
2294 Self.Diag(SrcExpr.get()->getLocStart(),
2295 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002296 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002297 SrcExpr = ExprError();
2298 return;
2299 }
2300 }
2301
Joey Goulydd7f4562013-01-23 11:56:20 +00002302 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2303 if (DestType->isHalfType()) {
2304 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2305 << DestType << SrcExpr.get()->getSourceRange();
2306 SrcExpr = ExprError();
2307 return;
2308 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002309 }
2310
John McCall9776e432011-10-06 23:25:11 +00002311 // ARC imposes extra restrictions on casts.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002312 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCall9776e432011-10-06 23:25:11 +00002313 checkObjCARCConversion(Sema::CCK_CStyleCast);
2314 if (SrcExpr.isInvalid())
2315 return;
2316
2317 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2318 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2319 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2320 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2321 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2322 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2323 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2324 Self.Diag(SrcExpr.get()->getLocStart(),
2325 diag::err_typecheck_incompatible_ownership)
2326 << SrcType << DestType << Sema::AA_Casting
2327 << SrcExpr.get()->getSourceRange();
2328 return;
2329 }
2330 }
2331 }
2332 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2333 Self.Diag(SrcExpr.get()->getLocStart(),
2334 diag::err_arc_convesion_of_weak_unavailable)
2335 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2336 SrcExpr = ExprError();
2337 return;
2338 }
2339 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002340 else if (Self.getLangOpts().ObjC1)
2341 Self.CheckTollFreeBridgeCast(DestType, SrcExpr.get());
2342
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002343 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002344 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002345 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2346 if (SrcExpr.isInvalid())
2347 return;
2348
2349 if (Kind == CK_BitCast)
2350 checkCastAlign();
2351}
2352
2353ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2354 TypeSourceInfo *CastTypeInfo,
2355 SourceLocation RPLoc,
2356 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002357 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2358 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2359 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2360
David Blaikiebbafb8a2012-03-11 07:00:24 +00002361 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002362 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2363 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002364 } else {
2365 Op.CheckCStyleCast();
2366 }
2367
John McCallb50451a2011-10-05 07:41:44 +00002368 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002369 return ExprError();
2370
John McCall4124c492011-10-17 18:40:02 +00002371 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2372 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2373 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002374}
2375
2376ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2377 SourceLocation LPLoc,
2378 Expr *CastExpr,
2379 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002380 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb50451a2011-10-05 07:41:44 +00002381 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2382 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2383 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2384
Sebastian Redl2b80af42012-02-13 19:55:43 +00002385 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002386 if (Op.SrcExpr.isInvalid())
2387 return ExprError();
Daniel Jasper3e1a9cf2012-07-16 08:05:07 +00002388
2389 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002390 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002391
John McCall4124c492011-10-17 18:40:02 +00002392 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002393 Op.ValueKind, CastTypeInfo, Op.Kind,
2394 Op.SrcExpr.take(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002395}