blob: 7207d04158a9854c50891d94fd340e71c7c22c05 [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"
David Majnemer1cdd96d2014-01-17 09:01:00 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000027#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000028using namespace clang;
29
Douglas Gregore81f58e2010-11-08 03:40:48 +000030
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Sebastian Redl9f831db2009-07-25 15:41:38 +000032enum TryCastResult {
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
35 TC_Failed ///< The cast method is appropriate, but failed. A
36 ///< diagnostic has been emitted.
37};
38
39enum CastType {
40 CT_Const, ///< const_cast
41 CT_Static, ///< static_cast
42 CT_Reinterpret, ///< reinterpret_cast
43 CT_Dynamic, ///< dynamic_cast
44 CT_CStyle, ///< (Type)expr
45 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000046};
47
John McCallb50451a2011-10-05 07:41:44 +000048namespace {
49 struct CastOperation {
50 CastOperation(Sema &S, QualType destType, ExprResult src)
51 : Self(S), SrcExpr(src), DestType(destType),
52 ResultType(destType.getNonLValueExprType(S.Context)),
53 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000054 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000055
56 if (const BuiltinType *placeholder =
57 src.get()->getType()->getAsPlaceholderType()) {
58 PlaceholderKind = placeholder->getKind();
59 } else {
60 PlaceholderKind = (BuiltinType::Kind) 0;
61 }
62 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000063
John McCallb50451a2011-10-05 07:41:44 +000064 Sema &Self;
65 ExprResult SrcExpr;
66 QualType DestType;
67 QualType ResultType;
68 ExprValueKind ValueKind;
69 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000070 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000071 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000072 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000073
John McCallb50451a2011-10-05 07:41:44 +000074 SourceRange OpRange;
75 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000076
John McCall9776e432011-10-06 23:25:11 +000077 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000078 void CheckConstCast();
79 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000080 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000081 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000082 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000083 void CheckCStyleCast();
84
John McCall4124c492011-10-17 18:40:02 +000085 /// Complete an apparently-successful cast operation that yields
86 /// the given expression.
87 ExprResult complete(CastExpr *castExpr) {
88 // If this is an unbridged cast, wrap the result in an implicit
89 // cast that yields the unbridged-cast placeholder type.
90 if (IsARCUnbridgedCast) {
91 castExpr = ImplicitCastExpr::Create(Self.Context,
92 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000093 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +000094 castExpr->getValueKind());
95 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000096 return castExpr;
John McCall4124c492011-10-17 18:40:02 +000097 }
98
John McCall9776e432011-10-06 23:25:11 +000099 // Internal convenience methods.
100
101 /// Try to handle the given placeholder expression kind. Return
102 /// true if the source expression has the appropriate placeholder
103 /// kind. A placeholder can only be claimed once.
104 bool claimPlaceholder(BuiltinType::Kind K) {
105 if (PlaceholderKind != K) return false;
106
107 PlaceholderKind = (BuiltinType::Kind) 0;
108 return true;
109 }
110
111 bool isPlaceholder() const {
112 return PlaceholderKind != 0;
113 }
114 bool isPlaceholder(BuiltinType::Kind K) const {
115 return PlaceholderKind == K;
116 }
John McCallb50451a2011-10-05 07:41:44 +0000117
118 void checkCastAlign() {
119 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
120 }
121
122 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000123 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall4124c492011-10-17 18:40:02 +0000124
John McCallb50451a2011-10-05 07:41:44 +0000125 Expr *src = SrcExpr.get();
John McCall4124c492011-10-17 18:40:02 +0000126 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127 Sema::ACR_unbridged)
128 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000129 SrcExpr = src;
130 }
John McCall9776e432011-10-06 23:25:11 +0000131
132 /// Check for and handle non-overload placeholder expressions.
133 void checkNonOverloadPlaceholders() {
134 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
135 return;
136
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000137 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000138 if (SrcExpr.isInvalid())
139 return;
140 PlaceholderKind = (BuiltinType::Kind) 0;
141 }
John McCallb50451a2011-10-05 07:41:44 +0000142 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000143}
Sebastian Redl842ef522008-11-08 13:00:26 +0000144
Sebastian Redl9f831db2009-07-25 15:41:38 +0000145// The Try functions attempt a specific way of casting. If they succeed, they
146// return TC_Success. If their way of casting is not appropriate for the given
147// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
148// to emit if no other way succeeds. If their way of casting is appropriate but
149// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
150// they emit a specialized diagnostic.
151// All diagnostics returned by these functions must expect the same three
152// arguments:
153// %0: Cast Type (a value from the CastType enumeration)
154// %1: Source Type
155// %2: Destination Type
156static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000157 QualType DestType, bool CStyle,
158 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000159 CXXCastPath &BasePath,
160 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000161static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000162 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000163 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000164 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000165 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000166 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000167static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
168 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000169 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000170 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000171 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000172 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000173static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
174 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000175 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000176 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000177 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000178 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000179 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000180static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000181 QualType SrcType,
182 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000183 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000184 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000185 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000186 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000187
John Wiegley01296292011-04-08 18:41:53 +0000188static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000189 QualType DestType,
190 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000191 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000192 unsigned &msg, CastKind &Kind,
193 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000194static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000195 QualType DestType,
196 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000197 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000198 unsigned &msg, CastKind &Kind,
199 CXXCastPath &BasePath,
200 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000201static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
202 QualType DestType, bool CStyle,
203 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000205 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000206 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000207 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000208 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000209
Douglas Gregorb491ed32011-02-19 21:32:49 +0000210
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000212ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000214 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000216 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000217 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000218
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000219 assert(!D.isInvalidType());
220
221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
222 if (D.isInvalidType())
223 return ExprError();
224
David Blaikiebbafb8a2012-03-11 07:00:24 +0000225 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000226 // Check that there are no default arguments (C++ only).
227 CheckExtraCXXDefaultArguments(D);
228 }
229
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
233}
234
John McCalldadc5752010-08-24 06:29:42 +0000235ExprResult
John McCalld377e042010-01-15 19:13:16 +0000236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000237 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000238 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000239 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000240 QualType DestType = DestTInfo->getType();
241
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000242 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000243 bool TypeDependent =
244 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000245
John McCallb50451a2011-10-05 07:41:44 +0000246 CastOperation Op(*this, DestType, E);
247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000249
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000250 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000251 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000252
253 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000254 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000255 Op.CheckConstCast();
256 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000257 return ExprError();
258 }
John McCall4124c492011-10-17 18:40:02 +0000259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000260 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000261 OpLoc, Parens.getEnd(),
262 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000263
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000264 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000265 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000266 Op.CheckDynamicCast();
267 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000268 return ExprError();
269 }
John McCall4124c492011-10-17 18:40:02 +0000270 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000272 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000273 OpLoc, Parens.getEnd(),
274 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000275 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000276 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000277 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000278 Op.CheckReinterpretCast();
279 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000280 return ExprError();
281 }
John McCall4124c492011-10-17 18:40:02 +0000282 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000283 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000284 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000285 Parens.getEnd(),
286 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000287 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000288 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000289 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000290 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000291 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000292 return ExprError();
293 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000294
John McCall4124c492011-10-17 18:40:02 +0000295 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000296 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000297 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000298 OpLoc, Parens.getEnd(),
299 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000300 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000301 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000302}
303
John McCall909acf82011-02-14 18:34:10 +0000304/// Try to diagnose a failed overloaded cast. Returns true if
305/// diagnostics were emitted.
306static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
307 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000308 QualType destType,
309 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000310 switch (CT) {
311 // These cast kinds don't consider user-defined conversions.
312 case CT_Const:
313 case CT_Reinterpret:
314 case CT_Dynamic:
315 return false;
316
317 // These do.
318 case CT_Static:
319 case CT_CStyle:
320 case CT_Functional:
321 break;
322 }
323
324 QualType srcType = src->getType();
325 if (!destType->isRecordType() && !srcType->isRecordType())
326 return false;
327
328 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
329 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000330 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000331 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000332 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000333 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000334 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000335 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000336
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000337 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000338 switch (sequence.getFailureKind()) {
339 default: return false;
340
341 case InitializationSequence::FK_ConstructorOverloadFailed:
342 case InitializationSequence::FK_UserConversionOverloadFailed:
343 break;
344 }
345
346 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
347
348 unsigned msg = 0;
349 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
350
351 switch (sequence.getFailedOverloadResult()) {
352 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000353 case OR_No_Viable_Function:
354 if (candidates.empty())
355 msg = diag::err_ovl_no_conversion_in_cast;
356 else
357 msg = diag::err_ovl_no_viable_conversion_in_cast;
358 howManyCandidates = OCD_AllCandidates;
359 break;
360
361 case OR_Ambiguous:
362 msg = diag::err_ovl_ambiguous_conversion_in_cast;
363 howManyCandidates = OCD_ViableCandidates;
364 break;
365
366 case OR_Deleted:
367 msg = diag::err_ovl_deleted_conversion_in_cast;
368 howManyCandidates = OCD_ViableCandidates;
369 break;
370 }
371
372 S.Diag(range.getBegin(), msg)
373 << CT << srcType << destType
374 << range << src->getSourceRange();
375
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000376 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000377
378 return true;
379}
380
381/// Diagnose a failed cast.
382static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000383 SourceRange opRange, Expr *src, QualType destType,
384 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000385 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000386 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
387 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000388 return;
389
390 S.Diag(opRange.getBegin(), msg) << castType
391 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000392
393 // Detect if both types are (ptr to) class, and note any incompleteness.
394 int DifferentPtrness = 0;
395 QualType From = destType;
396 if (auto Ptr = From->getAs<PointerType>()) {
397 From = Ptr->getPointeeType();
398 DifferentPtrness++;
399 }
400 QualType To = src->getType();
401 if (auto Ptr = To->getAs<PointerType>()) {
402 To = Ptr->getPointeeType();
403 DifferentPtrness--;
404 }
405 if (!DifferentPtrness) {
406 auto RecFrom = From->getAs<RecordType>();
407 auto RecTo = To->getAs<RecordType>();
408 if (RecFrom && RecTo) {
409 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
410 if (!DeclFrom->isCompleteDefinition())
411 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
412 << DeclFrom->getDeclName();
413 auto DeclTo = RecTo->getAsCXXRecordDecl();
414 if (!DeclTo->isCompleteDefinition())
415 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
416 << DeclTo->getDeclName();
417 }
418 }
John McCall909acf82011-02-14 18:34:10 +0000419}
420
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000421/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
422/// this removes one level of indirection from both types, provided that they're
423/// the same kind of pointer (plain or to-member). Unlike the Sema function,
424/// this one doesn't care if the two pointers-to-member don't point into the
425/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000426static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000427 const PointerType *T1PtrType = T1->getAs<PointerType>(),
428 *T2PtrType = T2->getAs<PointerType>();
429 if (T1PtrType && T2PtrType) {
430 T1 = T1PtrType->getPointeeType();
431 T2 = T2PtrType->getPointeeType();
432 return true;
433 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000434 const ObjCObjectPointerType *T1ObjCPtrType =
435 T1->getAs<ObjCObjectPointerType>(),
436 *T2ObjCPtrType =
437 T2->getAs<ObjCObjectPointerType>();
438 if (T1ObjCPtrType) {
439 if (T2ObjCPtrType) {
440 T1 = T1ObjCPtrType->getPointeeType();
441 T2 = T2ObjCPtrType->getPointeeType();
442 return true;
443 }
444 else if (T2PtrType) {
445 T1 = T1ObjCPtrType->getPointeeType();
446 T2 = T2PtrType->getPointeeType();
447 return true;
448 }
449 }
450 else if (T2ObjCPtrType) {
451 if (T1PtrType) {
452 T2 = T2ObjCPtrType->getPointeeType();
453 T1 = T1PtrType->getPointeeType();
454 return true;
455 }
456 }
457
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000458 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
459 *T2MPType = T2->getAs<MemberPointerType>();
460 if (T1MPType && T2MPType) {
461 T1 = T1MPType->getPointeeType();
462 T2 = T2MPType->getPointeeType();
463 return true;
464 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000465
466 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
467 *T2BPType = T2->getAs<BlockPointerType>();
468 if (T1BPType && T2BPType) {
469 T1 = T1BPType->getPointeeType();
470 T2 = T2BPType->getPointeeType();
471 return true;
472 }
473
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000474 return false;
475}
476
Sebastian Redla5a77a62009-01-27 23:18:31 +0000477/// CastsAwayConstness - Check if the pointer conversion from SrcType to
478/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
479/// the cast checkers. Both arguments must denote pointer (possibly to member)
480/// types.
John McCall31168b02011-06-15 23:02:42 +0000481///
482/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
483///
484/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000485static bool
John McCall31168b02011-06-15 23:02:42 +0000486CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000487 bool CheckCVR, bool CheckObjCLifetime,
488 QualType *TheOffendingSrcType = nullptr,
489 QualType *TheOffendingDestType = nullptr,
490 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000491 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000492 // and we're not in ObjC mode, there's nothing to check.
John McCall31168b02011-06-15 23:02:42 +0000493 if (!CheckCVR && CheckObjCLifetime &&
John McCall460ce582015-10-22 18:38:17 +0000494 !Self.Context.getLangOpts().ObjC1)
John McCall31168b02011-06-15 23:02:42 +0000495 return false;
496
Sebastian Redla5a77a62009-01-27 23:18:31 +0000497 // Casting away constness is defined in C++ 5.2.11p8 with reference to
498 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
499 // the rules are non-trivial. So first we construct Tcv *...cv* as described
500 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000501 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
502 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000503 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000504 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
505 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000506 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000507
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000508 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
509 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000511
Douglas Gregorb472e932011-04-15 17:59:54 +0000512 // Find the qualifiers. We only care about cvr-qualifiers for the
513 // purpose of this check, because other qualifiers (address spaces,
514 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000515 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
516 QualType PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000517 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000518 // Determine the relevant qualifiers at this level.
519 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000520 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000521 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000522
523 Qualifiers RetainedSrcQuals, RetainedDestQuals;
524 if (CheckCVR) {
525 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
526 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000527
528 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
529 TheOffendingDestType && CastAwayQualifiers) {
530 *TheOffendingSrcType = PrevUnwrappedSrcType;
531 *TheOffendingDestType = PrevUnwrappedDestType;
532 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
533 }
John McCall31168b02011-06-15 23:02:42 +0000534 }
535
536 if (CheckObjCLifetime &&
537 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
538 return true;
539
540 cv1.push_back(RetainedSrcQuals);
541 cv2.push_back(RetainedDestQuals);
Roman Divackyd5178012014-11-21 21:03:10 +0000542
543 PrevUnwrappedSrcType = UnwrappedSrcType;
544 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000545 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000546 if (cv1.empty())
547 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000548
549 // Construct void pointers with those qualifiers (in reverse order of
550 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000551 QualType SrcConstruct = Self.Context.VoidTy;
552 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000553 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000554 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
555 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000556 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000557 SrcConstruct
558 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
559 DestConstruct
560 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000561 }
562
563 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000564 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000565 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000566 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
567 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000568}
569
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000570/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
571/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
572/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000573void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000574 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000575 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000576 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000577 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000578 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
579 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000580
John McCallb50451a2011-10-05 07:41:44 +0000581 QualType OrigSrcType = SrcExpr.get()->getType();
582 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000583
584 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
585 // or "pointer to cv void".
586
587 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000588 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000589 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000590 if (DestPointer) {
591 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000592 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000593 DestPointee = DestReference->getPointeeType();
594 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000595 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000596 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000597 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000598 return;
599 }
600
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000601 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000602 if (DestPointee->isVoidType()) {
603 assert(DestPointer && "Reference to void is not possible");
604 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000605 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000606 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000607 DestRange)) {
608 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000609 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000610 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000611 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000612 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000613 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000614 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000615 return;
616 }
617
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000618 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
619 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000620 // an lvalue of a complete class type, [...]. If T is an rvalue reference
621 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000622 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000623 QualType SrcPointee;
624 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000625 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000626 SrcPointee = SrcPointer->getPointeeType();
627 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000628 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000629 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000630 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000631 return;
632 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000633 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000634 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000635 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000636 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000637 }
638 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000639 } else {
Richard Smith11330852014-07-08 17:25:14 +0000640 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
641 // to materialize the prvalue before we bind the reference to it.
642 if (SrcExpr.get()->isRValue())
643 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
644 SrcType, SrcExpr.get(), /*IsLValueReference*/false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000645 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000646 }
647
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000648 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000649 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000650 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000651 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000652 SrcExpr.get())) {
653 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000654 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000655 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000656 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000657 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000658 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000659 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000660 return;
661 }
662
663 assert((DestPointer || DestReference) &&
664 "Bad destination non-ptr/ref slipped through.");
665 assert((DestRecord || DestPointee->isVoidType()) &&
666 "Bad destination pointee slipped through.");
667 assert(SrcRecord && "Bad source pointee slipped through.");
668
669 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
670 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000671 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000672 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000673 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000674 return;
675 }
676
677 // C++ 5.2.7p3: If the type of v is the same as the required result type,
678 // [except for cv].
679 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000680 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000681 return;
682 }
683
684 // C++ 5.2.7p5
685 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000686 if (DestRecord &&
687 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000688 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
689 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000690 &BasePath)) {
691 SrcExpr = ExprError();
692 return;
693 }
Richard Smith11330852014-07-08 17:25:14 +0000694
John McCalle3027922010-08-25 11:45:40 +0000695 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000696 return;
697 }
698
699 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000700 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000701 assert(SrcDecl && "Definition missing");
702 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000703 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000704 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000705 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000706 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000707
Eli Friedman3ce27102013-09-24 23:21:41 +0000708 // dynamic_cast is not available with -fno-rtti.
709 // As an exception, dynamic_cast to void* is available because it doesn't
710 // use RTTI.
711 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000712 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
713 SrcExpr = ExprError();
714 return;
715 }
716
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000717 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000718 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000719}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000720
721/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
722/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
723/// like this:
724/// const char *str = "literal";
725/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000726void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000727 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000728 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000729 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000730 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000731 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
732 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000733
734 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000735 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000736 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000737 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000738 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000739 SrcExpr = ExprError();
740 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000741}
742
John McCallcda80832013-03-22 02:58:14 +0000743/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
744/// or downcast between respective pointers or references.
745static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
746 QualType DestType,
747 SourceRange OpRange) {
748 QualType SrcType = SrcExpr->getType();
749 // When casting from pointer or reference, get pointee type; use original
750 // type otherwise.
751 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
752 const CXXRecordDecl *SrcRD =
753 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
754
John McCallf2abe192013-03-27 00:03:48 +0000755 // Examining subobjects for records is only possible if the complete and
756 // valid definition is available. Also, template instantiation is not
757 // allowed here.
758 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000759 return;
760
761 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
762
John McCallf2abe192013-03-27 00:03:48 +0000763 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000764 return;
765
766 enum {
767 ReinterpretUpcast,
768 ReinterpretDowncast
769 } ReinterpretKind;
770
771 CXXBasePaths BasePaths;
772
773 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
774 ReinterpretKind = ReinterpretUpcast;
775 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
776 ReinterpretKind = ReinterpretDowncast;
777 else
778 return;
779
780 bool VirtualBase = true;
781 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000782 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000783 E = BasePaths.end();
784 I != E; ++I) {
785 const CXXBasePath &Path = *I;
786 CharUnits Offset = CharUnits::Zero();
787 bool IsVirtual = false;
788 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
789 IElem != EElem; ++IElem) {
790 IsVirtual = IElem->Base->isVirtual();
791 if (IsVirtual)
792 break;
793 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
794 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000795 // Don't check if any base has invalid declaration or has no definition
796 // since it has no layout info.
797 const CXXRecordDecl *Class = IElem->Class,
798 *ClassDefinition = Class->getDefinition();
799 if (Class->isInvalidDecl() || !ClassDefinition ||
800 !ClassDefinition->isCompleteDefinition())
801 return;
802
John McCallcda80832013-03-22 02:58:14 +0000803 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000804 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000805 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
806 }
807 if (!IsVirtual) {
808 // Don't warn if any path is a non-virtually derived base at offset zero.
809 if (Offset.isZero())
810 return;
811 // Offset makes sense only for non-virtual bases.
812 else
813 NonZeroOffset = true;
814 }
815 VirtualBase = VirtualBase && IsVirtual;
816 }
817
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000818 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000819 assert((VirtualBase || NonZeroOffset) &&
820 "Should have returned if has non-virtual base with zero offset");
821
822 QualType BaseType =
823 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
824 QualType DerivedType =
825 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
826
Jordan Rose04a94d12013-03-28 19:09:40 +0000827 SourceLocation BeginLoc = OpRange.getBegin();
828 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000829 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000830 << OpRange;
831 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000832 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000833 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000834}
835
Sebastian Redl9f831db2009-07-25 15:41:38 +0000836/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
837/// valid.
838/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
839/// like this:
840/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000841void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000842 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000843 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000844 else
845 checkNonOverloadPlaceholders();
846 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
847 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000848
849 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000850 TryCastResult tcr =
851 TryReinterpretCast(Self, SrcExpr, DestType,
852 /*CStyle*/false, OpRange, msg, Kind);
853 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000854 {
John Wiegley01296292011-04-08 18:41:53 +0000855 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
856 return;
857 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000858 //FIXME: &f<int>; is overloaded and resolvable
859 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000860 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000861 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000862 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000863
John McCall909acf82011-02-14 18:34:10 +0000864 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000865 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
866 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000867 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000868 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000869 } else if (tcr == TC_Success) {
870 if (Self.getLangOpts().ObjCAutoRefCount)
871 checkObjCARCConversion(Sema::CCK_OtherCast);
872 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000873 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000874}
875
876
877/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
878/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
879/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000880void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000881 if (isPlaceholder()) {
882 checkNonOverloadPlaceholders();
883 if (SrcExpr.isInvalid())
884 return;
885 }
886
Sebastian Redl9f831db2009-07-25 15:41:38 +0000887 // This test is outside everything else because it's the only case where
888 // a non-lvalue-reference target type does not lead to decay.
889 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000890 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000891 Kind = CK_ToVoid;
892
893 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000894 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000895 false, // Decay Function to ptr
896 true, // Complain
897 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000898 if (SrcExpr.isInvalid())
899 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000900 }
John McCall9776e432011-10-06 23:25:11 +0000901
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000902 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000903 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000904 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000905
John McCall50a2c2c2011-10-11 23:14:30 +0000906 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
907 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000908 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +0000909 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
910 return;
911 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000912
913 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000914 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000915 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000916 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000917 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000918 if (SrcExpr.isInvalid())
919 return;
920 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
921 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000922 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000923 << oe->getName() << DestType << OpRange
924 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000925 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000926 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000927 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
928 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000929 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000930 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000931 } else if (tcr == TC_Success) {
932 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000933 checkCastAlign();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000934 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smith507840d2011-11-29 22:48:16 +0000935 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000936 } else if (Kind == CK_BitCast) {
937 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000938 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000939}
940
941/// TryStaticCast - Check if a static cast can be performed, and do so if
942/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
943/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000944static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000945 QualType DestType,
946 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000947 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000948 CastKind &Kind, CXXCastPath &BasePath,
949 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000950 // Determine whether we have the semantics of a C-style cast.
951 bool CStyle
952 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
953
Sebastian Redl9f831db2009-07-25 15:41:38 +0000954 // The order the tests is not entirely arbitrary. There is one conversion
955 // that can be handled in two different ways. Given:
956 // struct A {};
957 // struct B : public A {
958 // B(); B(const A&);
959 // };
960 // const A &a = B();
961 // the cast static_cast<const B&>(a) could be seen as either a static
962 // reference downcast, or an explicit invocation of the user-defined
963 // conversion using B's conversion constructor.
964 // DR 427 specifies that the downcast is to be applied here.
965
966 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
967 // Done outside this function.
968
969 TryCastResult tcr;
970
971 // C++ 5.2.9p5, reference downcast.
972 // See the function for details.
973 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +0000974 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
975 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000976 if (tcr != TC_NotApplicable)
977 return tcr;
978
Davide Italianoa2275912015-07-12 22:10:56 +0000979 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +0000980 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
981 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redld74dd492012-02-12 18:41:05 +0000982 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
983 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000984 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000985 return tcr;
986
987 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
988 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000989 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000990 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000991 if (SrcExpr.isInvalid())
992 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000993 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000995
Sebastian Redl9f831db2009-07-25 15:41:38 +0000996 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
997 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
998 // conversions, subject to further restrictions.
999 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1000 // of qualification conversions impossible.
1001 // In the CStyle case, the earlier attempt to const_cast should have taken
1002 // care of reverse qualification conversions.
1003
John Wiegley01296292011-04-08 18:41:53 +00001004 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001005
Douglas Gregor0bf31402010-10-08 23:50:27 +00001006 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001007 // converted to an integral type. [...] A value of a scoped enumeration type
1008 // can also be explicitly converted to a floating-point type [...].
1009 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1010 if (Enum->getDecl()->isScoped()) {
1011 if (DestType->isBooleanType()) {
1012 Kind = CK_IntegralToBoolean;
1013 return TC_Success;
1014 } else if (DestType->isIntegralType(Self.Context)) {
1015 Kind = CK_IntegralCast;
1016 return TC_Success;
1017 } else if (DestType->isRealFloatingType()) {
1018 Kind = CK_IntegralToFloating;
1019 return TC_Success;
1020 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001021 }
1022 }
Douglas Gregorb327eac2011-02-18 03:01:41 +00001023
Sebastian Redl9f831db2009-07-25 15:41:38 +00001024 // Reverse integral promotion/conversion. All such conversions are themselves
1025 // again integral promotions or conversions and are thus already handled by
1026 // p2 (TryDirectInitialization above).
1027 // (Note: any data loss warnings should be suppressed.)
1028 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1029 // enum->enum). See also C++ 5.2.9p7.
1030 // The same goes for reverse floating point promotion/conversion and
1031 // floating-integral conversions. Again, only floating->enum is relevant.
1032 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001033 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001034 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001035 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001036 } else if (SrcType->isRealFloatingType()) {
1037 Kind = CK_FloatingToIntegral;
1038 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001039 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001040 }
1041
1042 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1043 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001044 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001045 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001046 if (tcr != TC_NotApplicable)
1047 return tcr;
1048
1049 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1050 // conversion. C++ 5.2.9p9 has additional information.
1051 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001052 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001053 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001054 if (tcr != TC_NotApplicable)
1055 return tcr;
1056
1057 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1058 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1059 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001061 QualType SrcPointee = SrcPointer->getPointeeType();
1062 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001063 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001064 QualType DestPointee = DestPointer->getPointeeType();
1065 if (DestPointee->isIncompleteOrObjectType()) {
1066 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001067 // to a qualifier violation. Note that we permit Objective-C lifetime
1068 // and GC qualifier mismatches here.
1069 if (!CStyle) {
1070 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1071 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1072 DestPointeeQuals.removeObjCGCAttr();
1073 DestPointeeQuals.removeObjCLifetime();
1074 SrcPointeeQuals.removeObjCGCAttr();
1075 SrcPointeeQuals.removeObjCLifetime();
1076 if (DestPointeeQuals != SrcPointeeQuals &&
1077 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1078 msg = diag::err_bad_cxx_cast_qualifiers_away;
1079 return TC_Failed;
1080 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001081 }
John McCalle3027922010-08-25 11:45:40 +00001082 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001083 return TC_Success;
1084 }
David Majnemer85bd1202015-06-02 22:15:12 +00001085
1086 // Microsoft permits static_cast from 'pointer-to-void' to
1087 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001088 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1089 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001090 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1091 Kind = CK_BitCast;
1092 return TC_Success;
1093 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001094 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001095 else if (DestType->isObjCObjectPointerType()) {
1096 // allow both c-style cast and static_cast of objective-c pointers as
1097 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001098 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001099 return TC_Success;
1100 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001101 else if (CStyle && DestType->isBlockPointerType()) {
1102 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001103 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001104 return TC_Success;
1105 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001106 }
1107 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001108 // Allow arbitray objective-c pointer conversion with static casts.
1109 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001110 DestType->isObjCObjectPointerType()) {
1111 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001112 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001113 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001114 // Allow ns-pointer to cf-pointer conversion in either direction
1115 // with static casts.
1116 if (!CStyle &&
1117 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1118 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001119
1120 // See if it looks like the user is trying to convert between
1121 // related record types, and select a better diagnostic if so.
1122 if (auto SrcPointer = SrcType->getAs<PointerType>())
1123 if (auto DestPointer = DestType->getAs<PointerType>())
1124 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1125 DestPointer->getPointeeType()->getAs<RecordType>())
1126 msg = diag::err_bad_cxx_cast_unrelated_class;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001127
Sebastian Redl9f831db2009-07-25 15:41:38 +00001128 // We tried everything. Everything! Nothing works! :-(
1129 return TC_NotApplicable;
1130}
1131
1132/// Tests whether a conversion according to N2844 is valid.
1133TryCastResult
1134TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +00001135 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1136 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001137 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001138 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1139 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001140 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001141 if (!R)
1142 return TC_NotApplicable;
1143
Douglas Gregor465184a2011-01-22 00:06:57 +00001144 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001145 return TC_NotApplicable;
1146
1147 // Because we try the reference downcast before this function, from now on
1148 // this is the only cast possibility, so we issue an error if we fail now.
1149 // FIXME: Should allow casting away constness if CStyle.
1150 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001151 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001152 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001153 QualType FromType = SrcExpr->getType();
1154 QualType ToType = R->getPointeeType();
1155 if (CStyle) {
1156 FromType = FromType.getUnqualifiedType();
1157 ToType = ToType.getUnqualifiedType();
1158 }
1159
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001160 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +00001161 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +00001162 DerivedToBase, ObjCConversion,
1163 ObjCLifetimeConversion)
1164 < Sema::Ref_Compatible_With_Added_Qualification) {
Davide Italianoa2275912015-07-12 22:10:56 +00001165 if (CStyle)
1166 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001167 msg = diag::err_bad_lvalue_to_rvalue_cast;
1168 return TC_Failed;
1169 }
1170
Douglas Gregorba278e22011-01-25 16:13:26 +00001171 if (DerivedToBase) {
1172 Kind = CK_DerivedToBase;
1173 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1174 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001175 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1176 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001177 return TC_NotApplicable;
1178
1179 Self.BuildBasePathArray(Paths, BasePath);
1180 } else
1181 Kind = CK_NoOp;
1182
Sebastian Redl9f831db2009-07-25 15:41:38 +00001183 return TC_Success;
1184}
1185
1186/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1187TryCastResult
1188TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001189 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001190 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001191 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001192 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1193 // cast to type "reference to cv2 D", where D is a class derived from B,
1194 // if a valid standard conversion from "pointer to D" to "pointer to B"
1195 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1196 // In addition, DR54 clarifies that the base must be accessible in the
1197 // current context. Although the wording of DR54 only applies to the pointer
1198 // variant of this rule, the intent is clearly for it to apply to the this
1199 // conversion as well.
1200
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001201 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001202 if (!DestReference) {
1203 return TC_NotApplicable;
1204 }
1205 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001206 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001207 // We know the left side is an lvalue reference, so we can suggest a reason.
1208 msg = diag::err_bad_cxx_cast_rvalue;
1209 return TC_NotApplicable;
1210 }
1211
1212 QualType DestPointee = DestReference->getPointeeType();
1213
Richard Smith11330852014-07-08 17:25:14 +00001214 // FIXME: If the source is a prvalue, we should issue a warning (because the
1215 // cast always has undefined behavior), and for AST consistency, we should
1216 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001217 return TryStaticDowncast(Self,
1218 Self.Context.getCanonicalType(SrcExpr->getType()),
1219 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001220 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1221 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001222}
1223
1224/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1225TryCastResult
1226TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001227 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001228 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001229 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001230 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1231 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1232 // is a class derived from B, if a valid standard conversion from "pointer
1233 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1234 // class of D.
1235 // In addition, DR54 clarifies that the base must be accessible in the
1236 // current context.
1237
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001238 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001239 if (!DestPointer) {
1240 return TC_NotApplicable;
1241 }
1242
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001243 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001244 if (!SrcPointer) {
1245 msg = diag::err_bad_static_cast_pointer_nonpointer;
1246 return TC_NotApplicable;
1247 }
1248
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001249 return TryStaticDowncast(Self,
1250 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1251 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001252 CStyle, OpRange, SrcType, DestType, msg, Kind,
1253 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001254}
1255
1256/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1257/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001258/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001259TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001260TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001261 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001262 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001263 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001264 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001265 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1266 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001267 return TC_NotApplicable;
1268
Sebastian Redl9f831db2009-07-25 15:41:38 +00001269 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001270 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001271 return TC_NotApplicable;
1272 }
1273
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001274 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001275 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001276 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001277 return TC_NotApplicable;
1278 }
1279
1280 // Target type does derive from source type. Now we're serious. If an error
1281 // appears now, it's not ignored.
1282 // This may not be entirely in line with the standard. Take for example:
1283 // struct A {};
1284 // struct B : virtual A {
1285 // B(A&);
1286 // };
Mike Stump11289f42009-09-09 15:08:12 +00001287 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001288 // void f()
1289 // {
1290 // (void)static_cast<const B&>(*((A*)0));
1291 // }
1292 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1293 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1294 // However, both GCC and Comeau reject this example, and accepting it would
1295 // mean more complex code if we're to preserve the nice error message.
1296 // FIXME: Being 100% compliant here would be nice to have.
1297
1298 // Must preserve cv, as always, unless we're in C-style mode.
1299 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001300 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001301 return TC_Failed;
1302 }
1303
1304 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1305 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1306 // that it builds the paths in reverse order.
1307 // To sum up: record all paths to the base and build a nice string from
1308 // them. Use it to spice up the error message.
1309 if (!Paths.isRecordingPaths()) {
1310 Paths.clear();
1311 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001312 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001313 }
1314 std::string PathDisplayStr;
1315 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001316 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001317 PI != PE; ++PI) {
1318 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1319 // We haven't displayed a path to this particular base
1320 // class subobject yet.
1321 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001322 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1323 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001324 EI != EE; ++EI)
1325 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001326 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001327 }
1328 }
1329
1330 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001331 << QualType(SrcType).getUnqualifiedType()
1332 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001333 << PathDisplayStr << OpRange;
1334 msg = 0;
1335 return TC_Failed;
1336 }
1337
Craig Topperc3ec1492014-05-26 06:22:03 +00001338 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001339 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1340 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1341 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1342 msg = 0;
1343 return TC_Failed;
1344 }
1345
John McCallfe9cf0a2011-02-14 23:21:33 +00001346 if (!CStyle) {
1347 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1348 SrcType, DestType,
1349 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001350 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001351 case Sema::AR_accessible:
1352 case Sema::AR_delayed: // be optimistic
1353 case Sema::AR_dependent: // be optimistic
1354 break;
1355
1356 case Sema::AR_inaccessible:
1357 msg = 0;
1358 return TC_Failed;
1359 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001360 }
1361
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001362 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001363 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001364 return TC_Success;
1365}
1366
1367/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1368/// C++ 5.2.9p9 is valid:
1369///
1370/// An rvalue of type "pointer to member of D of type cv1 T" can be
1371/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1372/// where B is a base class of D [...].
1373///
1374TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001375TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001376 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001377 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001378 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001379 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001380 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001381 if (!DestMemPtr)
1382 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001383
1384 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001385 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001386 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001387 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001388 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001389 FoundOverload)) {
1390 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1391 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1392 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1393 WasOverloadedFunction = true;
1394 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001395 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001396
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001397 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001398 if (!SrcMemPtr) {
1399 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1400 return TC_NotApplicable;
1401 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001402
1403 // Lock down the inheritance model right now in MS ABI, whether or not the
1404 // pointee types are the same.
Alexey Bataeva93fb5b2015-08-10 04:07:49 +00001405 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft())
Richard Smithdb0ac552015-12-18 22:40:25 +00001406 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001407
1408 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001409 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1410 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001411 return TC_NotApplicable;
1412
1413 // B base of D
1414 QualType SrcClass(SrcMemPtr->getClass(), 0);
1415 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001416 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001417 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001418 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001419 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001420
1421 // 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 +00001422 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001423 Paths.clear();
1424 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001425 bool StillOkay =
1426 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001427 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001428 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001429 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1430 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1431 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1432 msg = 0;
1433 return TC_Failed;
1434 }
1435
1436 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1437 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1438 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1439 msg = 0;
1440 return TC_Failed;
1441 }
1442
John McCallfe9cf0a2011-02-14 23:21:33 +00001443 if (!CStyle) {
1444 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1445 DestClass, SrcClass,
1446 Paths.front(),
1447 diag::err_upcast_to_inaccessible_base)) {
1448 case Sema::AR_accessible:
1449 case Sema::AR_delayed:
1450 case Sema::AR_dependent:
1451 // Optimistically assume that the delayed and dependent cases
1452 // will work out.
1453 break;
1454
1455 case Sema::AR_inaccessible:
1456 msg = 0;
1457 return TC_Failed;
1458 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001459 }
1460
Douglas Gregorc934bc82010-03-07 23:24:59 +00001461 if (WasOverloadedFunction) {
1462 // Resolve the address of the overloaded function again, this time
1463 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001464 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001465 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001466 true,
1467 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001468 if (!Fn) {
1469 msg = 0;
1470 return TC_Failed;
1471 }
1472
John McCall16df1e52010-03-30 21:47:33 +00001473 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001474 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001475 msg = 0;
1476 return TC_Failed;
1477 }
1478 }
1479
Anders Carlssonb78feca2010-04-24 19:22:20 +00001480 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001481 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001482 return TC_Success;
1483}
1484
1485/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1486/// is valid:
1487///
1488/// An expression e can be explicitly converted to a type T using a
1489/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1490TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001491TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001492 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001493 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001494 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001495 if (DestType->isRecordType()) {
1496 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001497 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001498 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001499 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001500 msg = 0;
1501 return TC_Failed;
1502 }
1503 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001504
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001505 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1506 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001507 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001508 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001509 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001510 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001511 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001512 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001513 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001514 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001515
1516 // At this point of CheckStaticCast, if the destination is a reference,
1517 // or the expression is an overload expression this has to work.
1518 // There is no other way that works.
1519 // On the other hand, if we're checking a C-style cast, we've still got
1520 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001521 bool CStyle
1522 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001523 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001524 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001525
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001526 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001527 if (Result.isInvalid()) {
1528 msg = 0;
1529 return TC_Failed;
1530 }
1531
Douglas Gregorb33eed02010-04-16 22:09:46 +00001532 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001533 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001534 else
John McCalle3027922010-08-25 11:45:40 +00001535 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001536
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001537 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001538 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001539}
1540
1541/// TryConstCast - See if a const_cast from source to destination is allowed,
1542/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001543static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1544 QualType DestType, bool CStyle,
1545 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001546 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001547 QualType SrcType = SrcExpr.get()->getType();
1548 bool NeedToMaterializeTemporary = false;
1549
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001550 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001551 // C++11 5.2.11p4:
1552 // if a pointer to T1 can be explicitly converted to the type "pointer to
1553 // T2" using a const_cast, then the following conversions can also be
1554 // made:
1555 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1556 // type T2 using the cast const_cast<T2&>;
1557 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1558 // type T2 using the cast const_cast<T2&&>; and
1559 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1560 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1561
1562 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001563 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1564 // is C-style, static_cast might find a way, so we simply suggest a
1565 // message and tell the parent to keep searching.
1566 msg = diag::err_bad_cxx_cast_rvalue;
1567 return TC_NotApplicable;
1568 }
1569
Richard Smith82c9b512013-06-14 22:27:52 +00001570 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1571 if (!SrcType->isRecordType()) {
1572 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1573 // this is C-style, static_cast can do this.
1574 msg = diag::err_bad_cxx_cast_rvalue;
1575 return TC_NotApplicable;
1576 }
1577
1578 // Materialize the class prvalue so that the const_cast can bind a
1579 // reference to it.
1580 NeedToMaterializeTemporary = true;
1581 }
1582
John McCalld25db7e2013-05-06 21:39:12 +00001583 // It's not completely clear under the standard whether we can
1584 // const_cast bit-field gl-values. Doing so would not be
1585 // intrinsically complicated, but for now, we say no for
1586 // consistency with other compilers and await the word of the
1587 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001588 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001589 msg = diag::err_bad_cxx_cast_bitfield;
1590 return TC_NotApplicable;
1591 }
1592
Sebastian Redl9f831db2009-07-25 15:41:38 +00001593 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1594 SrcType = Self.Context.getPointerType(SrcType);
1595 }
1596
1597 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1598 // the rules for const_cast are the same as those used for pointers.
1599
John McCall0e704f72010-05-18 09:35:29 +00001600 if (!DestType->isPointerType() &&
1601 !DestType->isMemberPointerType() &&
1602 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001603 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1604 // was a reference type, we converted it to a pointer above.
1605 // The status of rvalue references isn't entirely clear, but it looks like
1606 // conversion to them is simply invalid.
1607 // C++ 5.2.11p3: For two pointer types [...]
1608 if (!CStyle)
1609 msg = diag::err_bad_const_cast_dest;
1610 return TC_NotApplicable;
1611 }
1612 if (DestType->isFunctionPointerType() ||
1613 DestType->isMemberFunctionPointerType()) {
1614 // Cannot cast direct function pointers.
1615 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1616 // T is the ultimate pointee of source and target type.
1617 if (!CStyle)
1618 msg = diag::err_bad_const_cast_dest;
1619 return TC_NotApplicable;
1620 }
1621 SrcType = Self.Context.getCanonicalType(SrcType);
1622
1623 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1624 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001625 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1626 // in multi-level pointers may change, but the level count must be the same,
1627 // as must be the final pointee type.
1628 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001629 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001630 Qualifiers SrcQuals, DestQuals;
1631 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1632 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1633
1634 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1635 // the other qualifiers (e.g., address spaces) are identical.
1636 SrcQuals.removeCVRQualifiers();
1637 DestQuals.removeCVRQualifiers();
1638 if (SrcQuals != DestQuals)
1639 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001640 }
1641
1642 // Since we're dealing in canonical types, the remainder must be the same.
1643 if (SrcType != DestType)
1644 return TC_NotApplicable;
1645
Richard Smith82c9b512013-06-14 22:27:52 +00001646 if (NeedToMaterializeTemporary)
1647 // This is a const_cast from a class prvalue to an rvalue reference type.
1648 // Materialize a temporary to store the result of the conversion.
1649 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001650 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001651
Sebastian Redl9f831db2009-07-25 15:41:38 +00001652 return TC_Success;
1653}
1654
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001655// Checks for undefined behavior in reinterpret_cast.
1656// The cases that is checked for is:
1657// *reinterpret_cast<T*>(&a)
1658// reinterpret_cast<T&>(a)
1659// where accessing 'a' as type 'T' will result in undefined behavior.
1660void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1661 bool IsDereference,
1662 SourceRange Range) {
1663 unsigned DiagID = IsDereference ?
1664 diag::warn_pointer_indirection_from_incompatible_type :
1665 diag::warn_undefined_reinterpret_cast;
1666
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001667 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001668 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001669
1670 QualType SrcTy, DestTy;
1671 if (IsDereference) {
1672 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1673 return;
1674 }
1675 SrcTy = SrcType->getPointeeType();
1676 DestTy = DestType->getPointeeType();
1677 } else {
1678 if (!DestType->getAs<ReferenceType>()) {
1679 return;
1680 }
1681 SrcTy = SrcType;
1682 DestTy = DestType->getPointeeType();
1683 }
1684
1685 // Cast is compatible if the types are the same.
1686 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1687 return;
1688 }
1689 // or one of the types is a char or void type
1690 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1691 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1692 return;
1693 }
1694 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001695 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001696 return;
1697 }
1698
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001699 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001700 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1701 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1702 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1703 return;
1704 }
1705 }
1706
1707 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1708}
Douglas Gregor1beec452011-03-12 01:48:56 +00001709
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001710static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1711 QualType DestType) {
1712 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001713 if (Self.Context.hasSameType(SrcType, DestType))
1714 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001715 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1716 if (SrcPtrTy->isObjCSelType()) {
1717 QualType DT = DestType;
1718 if (isa<PointerType>(DestType))
1719 DT = DestType->getPointeeType();
1720 if (!DT.getUnqualifiedType()->isVoidType())
1721 Self.Diag(SrcExpr.get()->getExprLoc(),
1722 diag::warn_cast_pointer_from_sel)
1723 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1724 }
1725}
1726
David Blaikie282ad872012-10-16 18:53:14 +00001727static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1728 const Expr *SrcExpr, QualType DestType,
1729 Sema &Self) {
1730 QualType SrcType = SrcExpr->getType();
1731
1732 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1733 // are not explicit design choices, but consistent with GCC's behavior.
1734 // Feel free to modify them if you've reason/evidence for an alternative.
1735 if (CStyle && SrcType->isIntegralType(Self.Context)
1736 && !SrcType->isBooleanType()
1737 && !SrcType->isEnumeralType()
1738 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001739 && Self.Context.getTypeSize(DestType) >
1740 Self.Context.getTypeSize(SrcType)) {
1741 // Separate between casts to void* and non-void* pointers.
1742 // Some APIs use (abuse) void* for something like a user context,
1743 // and often that value is an integer even if it isn't a pointer itself.
1744 // Having a separate warning flag allows users to control the warning
1745 // for their workflow.
1746 unsigned Diag = DestType->isVoidPointerType() ?
1747 diag::warn_int_to_void_pointer_cast
1748 : diag::warn_int_to_pointer_cast;
1749 Self.Diag(Loc, Diag) << SrcType << DestType;
1750 }
David Blaikie282ad872012-10-16 18:53:14 +00001751}
1752
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001753static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1754 ExprResult &Result) {
1755 // We can only fix an overloaded reinterpret_cast if
1756 // - it is a template with explicit arguments that resolves to an lvalue
1757 // unambiguously, or
1758 // - it is the only function in an overload set that may have its address
1759 // taken.
1760
1761 Expr *E = Result.get();
1762 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1763 // like it?
1764 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1765 Result,
1766 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1767 ) &&
1768 Result.isUsable())
1769 return true;
1770
1771 DeclAccessPair DAP;
1772 FunctionDecl *Found = Self.resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
1773 if (!Found)
1774 return false;
1775
1776 // It seems that if we encounter a call to a function that is both unavailable
1777 // and inaccessible, we'll emit multiple diags for said call. Hence, we run
1778 // both checks below unconditionally.
1779 Self.DiagnoseUseOfDecl(Found, E->getExprLoc());
1780 Self.CheckAddressOfMemberAccess(E, DAP);
1781
1782 Expr *Fixed = Self.FixOverloadedFunctionReference(E, DAP, Found);
1783 if (Fixed->getType()->isFunctionType())
1784 Result = Self.DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
1785 else
1786 Result = Fixed;
1787
1788 return !Result.isInvalid();
1789}
1790
John Wiegley01296292011-04-08 18:41:53 +00001791static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001792 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001793 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001794 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001795 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001796 bool IsLValueCast = false;
1797
Sebastian Redl9f831db2009-07-25 15:41:38 +00001798 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001799 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001800
1801 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001802 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001803 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001804 ExprResult FixedExpr = SrcExpr;
1805 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001806 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001807
1808 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1809 SrcExpr = FixedExpr;
1810 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001811 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001812
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001813 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001814 if (!SrcExpr.get()->isGLValue()) {
1815 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1816 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001817 msg = diag::err_bad_cxx_cast_rvalue;
1818 return TC_NotApplicable;
1819 }
1820
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001821 if (!CStyle) {
1822 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1823 /*isDereference=*/false, OpRange);
1824 }
1825
Sebastian Redl9f831db2009-07-25 15:41:38 +00001826 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1827 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1828 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001829
Craig Topperc3ec1492014-05-26 06:22:03 +00001830 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001831 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001832 case OK_Ordinary:
1833 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001834 case OK_BitField: inappropriate = "bit-field"; break;
1835 case OK_VectorComponent: inappropriate = "vector element"; break;
1836 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001837 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1838 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001839 }
1840 if (inappropriate) {
1841 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1842 << inappropriate << DestType
1843 << OpRange << SrcExpr.get()->getSourceRange();
1844 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001845 return TC_NotApplicable;
1846 }
1847
Sebastian Redl9f831db2009-07-25 15:41:38 +00001848 // This code does this transformation for the checked types.
1849 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1850 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001851
Douglas Gregor51954272010-07-13 23:17:26 +00001852 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001853 }
1854
1855 // Canonicalize source for comparison.
1856 SrcType = Self.Context.getCanonicalType(SrcType);
1857
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001858 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1859 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001860 if (DestMemPtr && SrcMemPtr) {
1861 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1862 // can be explicitly converted to an rvalue of type "pointer to member
1863 // of Y of type T2" if T1 and T2 are both function types or both object
1864 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00001865 if (DestMemPtr->isMemberFunctionPointer() !=
1866 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001867 return TC_NotApplicable;
1868
1869 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1870 // constness.
1871 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1872 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001873 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1874 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001875 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001876 return TC_Failed;
1877 }
1878
David Majnemer1cdd96d2014-01-17 09:01:00 +00001879 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1880 // We need to determine the inheritance model that the class will use if
1881 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00001882 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1883 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00001884 }
1885
Charles Davisebab1ed2010-08-16 05:30:44 +00001886 // Don't allow casting between member pointers of different sizes.
1887 if (Self.Context.getTypeSize(DestMemPtr) !=
1888 Self.Context.getTypeSize(SrcMemPtr)) {
1889 msg = diag::err_bad_cxx_cast_member_pointer_size;
1890 return TC_Failed;
1891 }
1892
Sebastian Redl9f831db2009-07-25 15:41:38 +00001893 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00001894 assert(!IsLValueCast);
1895 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001896 return TC_Success;
1897 }
1898
1899 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001900 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001901 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1902 // type large enough to hold it. A value of std::nullptr_t can be
1903 // converted to an integral type; the conversion has the same meaning
1904 // and validity as a conversion of (void*)0 to the integral type.
1905 if (Self.Context.getTypeSize(SrcType) >
1906 Self.Context.getTypeSize(DestType)) {
1907 msg = diag::err_bad_reinterpret_cast_small_int;
1908 return TC_Failed;
1909 }
John McCalle3027922010-08-25 11:45:40 +00001910 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001911 return TC_Success;
1912 }
1913
John McCall1c78f082015-07-23 23:54:07 +00001914 // Allow reinterpret_casts between vectors of the same size and
1915 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00001916 bool destIsVector = DestType->isVectorType();
1917 bool srcIsVector = SrcType->isVectorType();
1918 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00001919 // The non-vector type, if any, must have integral type. This is
1920 // the same rule that C vector casts use; note, however, that enum
1921 // types are not integral in C++.
1922 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
1923 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00001924 return TC_NotApplicable;
1925
John McCall1c78f082015-07-23 23:54:07 +00001926 // The size we want to consider is eltCount * eltSize.
1927 // That's exactly what the lax-conversion rules will check.
1928 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001929 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001930 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001931 }
John McCall1c78f082015-07-23 23:54:07 +00001932
1933 // Otherwise, pick a reasonable diagnostic.
1934 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00001935 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00001936 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00001937 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1938 else
1939 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1940
1941 return TC_Failed;
1942 }
Chad Rosier96c755d12012-02-03 02:54:37 +00001943
1944 if (SrcType == DestType) {
1945 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1946 // restrictions, a cast to the same type is allowed so long as it does not
1947 // cast away constness. In C++98, the intent was not entirely clear here,
1948 // since all other paragraphs explicitly forbid casts to the same type.
1949 // C++11 clarifies this case with p2.
1950 //
1951 // The only allowed types are: integral, enumeration, pointer, or
1952 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1953 Kind = CK_NoOp;
1954 TryCastResult Result = TC_NotApplicable;
1955 if (SrcType->isIntegralOrEnumerationType() ||
1956 SrcType->isAnyPointerType() ||
1957 SrcType->isMemberPointerType() ||
1958 SrcType->isBlockPointerType()) {
1959 Result = TC_Success;
1960 }
1961 return Result;
1962 }
1963
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001964 bool destIsPtr = DestType->isAnyPointerType() ||
1965 DestType->isBlockPointerType();
1966 bool srcIsPtr = SrcType->isAnyPointerType() ||
1967 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001968 if (!destIsPtr && !srcIsPtr) {
1969 // Except for std::nullptr_t->integer and lvalue->reference, which are
1970 // handled above, at least one of the two arguments must be a pointer.
1971 return TC_NotApplicable;
1972 }
1973
Douglas Gregor6972a622010-06-16 00:35:25 +00001974 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001975 assert(srcIsPtr && "One type must be a pointer");
1976 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001977 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00001978 // integral type size doesn't matter (except we don't allow bool).
1979 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1980 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00001981 if ((Self.Context.getTypeSize(SrcType) >
1982 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00001983 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001984 msg = diag::err_bad_reinterpret_cast_small_int;
1985 return TC_Failed;
1986 }
John McCalle3027922010-08-25 11:45:40 +00001987 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001988 return TC_Success;
1989 }
1990
Douglas Gregorb90df602010-06-16 00:17:44 +00001991 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001992 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00001993 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1994 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001995 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1996 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001997 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1998 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001999 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002000 return TC_Success;
2001 }
2002
2003 if (!destIsPtr || !srcIsPtr) {
2004 // With the valid non-pointer conversions out of the way, we can be even
2005 // more stringent.
2006 return TC_NotApplicable;
2007 }
2008
2009 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2010 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00002011 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2012 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00002013 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002014 return TC_Failed;
2015 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002016
2017 // Cannot convert between block pointers and Objective-C object pointers.
2018 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2019 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2020 return TC_NotApplicable;
2021
John McCall9320b872011-09-09 05:25:32 +00002022 if (IsLValueCast) {
2023 Kind = CK_LValueBitCast;
2024 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002025 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002026 } else if (DestType->isBlockPointerType()) {
2027 if (!SrcType->isBlockPointerType()) {
2028 Kind = CK_AnyPointerToBlockPointerCast;
2029 } else {
2030 Kind = CK_BitCast;
2031 }
2032 } else {
2033 Kind = CK_BitCast;
2034 }
2035
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002036 // Any pointer can be cast to an Objective-C pointer type with a C-style
2037 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002038 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002039 return TC_Success;
2040 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002041 if (CStyle)
2042 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2043
Sebastian Redl9f831db2009-07-25 15:41:38 +00002044 // Not casting away constness, so the only remaining check is for compatible
2045 // pointer categories.
2046
2047 if (SrcType->isFunctionPointerType()) {
2048 if (DestType->isFunctionPointerType()) {
2049 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2050 // a pointer to a function of a different type.
2051 return TC_Success;
2052 }
2053
2054 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2055 // an object type or vice versa is conditionally-supported.
2056 // Compilers support it in C++03 too, though, because it's necessary for
2057 // casting the return value of dlsym() and GetProcAddress().
2058 // FIXME: Conditionally-supported behavior should be configurable in the
2059 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002060 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002061 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002062 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2063 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002064 return TC_Success;
2065 }
2066
2067 if (DestType->isFunctionPointerType()) {
2068 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002069 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002070 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002071 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2072 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002073 return TC_Success;
2074 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002075
Sebastian Redl9f831db2009-07-25 15:41:38 +00002076 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2077 // a pointer to an object of different type.
2078 // Void pointers are not specified, but supported by every compiler out there.
2079 // So we finish by allowing everything that remains - it's got to be two
2080 // object pointers.
2081 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00002082}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002083
Sebastian Redld74dd492012-02-12 18:41:05 +00002084void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2085 bool ListInitialization) {
John McCall9776e432011-10-06 23:25:11 +00002086 // Handle placeholders.
2087 if (isPlaceholder()) {
2088 // C-style casts can resolve __unknown_any types.
2089 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2090 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2091 SrcExpr.get(), Kind,
2092 ValueKind, BasePath);
2093 return;
2094 }
John McCallb50451a2011-10-05 07:41:44 +00002095
John McCall9776e432011-10-06 23:25:11 +00002096 checkNonOverloadPlaceholders();
2097 if (SrcExpr.isInvalid())
2098 return;
John McCalla072f5d2011-10-17 17:42:19 +00002099 }
John McCall9776e432011-10-06 23:25:11 +00002100
2101 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002102 // This test is outside everything else because it's the only case where
2103 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002104 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002105 Kind = CK_ToVoid;
2106
John McCall9776e432011-10-06 23:25:11 +00002107 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002108 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2109 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002110 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002111 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002112 if (SrcExpr.isInvalid())
2113 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002114 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002115
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002116 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002117 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002118 }
2119
Sebastian Redl9f831db2009-07-25 15:41:38 +00002120 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002121 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2122 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002123 assert(Kind == CK_Dependent);
2124 return;
John McCall8cb679e2010-11-15 09:13:47 +00002125 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002126
John McCall50a2c2c2011-10-11 23:14:30 +00002127 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2128 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002129 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002130 if (SrcExpr.isInvalid())
2131 return;
John Wiegley01296292011-04-08 18:41:53 +00002132 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002133
John McCall3aef3d82011-04-10 19:13:55 +00002134 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002135 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002136 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002137 && (SrcExpr.get()->getType()->isIntegerType()
2138 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002139 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002140 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002141 return;
John McCall3aef3d82011-04-10 19:13:55 +00002142 }
2143
Sebastian Redl9f831db2009-07-25 15:41:38 +00002144 // C++ [expr.cast]p5: The conversions performed by
2145 // - a const_cast,
2146 // - a static_cast,
2147 // - a static_cast followed by a const_cast,
2148 // - a reinterpret_cast, or
2149 // - a reinterpret_cast followed by a const_cast,
2150 // can be performed using the cast notation of explicit type conversion.
2151 // [...] If a conversion can be interpreted in more than one of the ways
2152 // listed above, the interpretation that appears first in the list is used,
2153 // even if a cast resulting from that interpretation is ill-formed.
2154 // In plain language, this means trying a const_cast ...
2155 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002156 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002157 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002158 if (SrcExpr.isInvalid())
2159 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002160 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002161 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002162
John McCall31168b02011-06-15 23:02:42 +00002163 Sema::CheckedConversionKind CCK
2164 = FunctionalStyle? Sema::CCK_FunctionalCast
2165 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002166 if (tcr == TC_NotApplicable) {
2167 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002168 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002169 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002170 if (SrcExpr.isInvalid())
2171 return;
2172
Sebastian Redl9f831db2009-07-25 15:41:38 +00002173 if (tcr == TC_NotApplicable) {
2174 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002175 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2176 OpRange, msg, Kind);
2177 if (SrcExpr.isInvalid())
2178 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002179 }
2180 }
2181
David Blaikiebbafb8a2012-03-11 07:00:24 +00002182 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002183 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002184
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002185 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002186 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002187 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002188 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2189 DestType,
2190 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002191 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002192 if (Fn) {
2193 // If DestType is a function type (not to be confused with the function
2194 // pointer type), it will be possible to resolve the function address,
2195 // but the type cast should be considered as failure.
2196 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2197 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2198 << OE->getName() << DestType << OpRange
2199 << OE->getQualifierLoc().getSourceRange();
2200 Self.NoteAllOverloadCandidates(SrcExpr.get());
2201 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002202 } else {
John McCallb50451a2011-10-05 07:41:44 +00002203 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002204 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002205 }
John McCallb50451a2011-10-05 07:41:44 +00002206 } else if (Kind == CK_BitCast) {
2207 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002208 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002209
John McCallb50451a2011-10-05 07:41:44 +00002210 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002211 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002212 SrcExpr = ExprError();
2213}
2214
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002215/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2216/// non-matching type. Such as enum function call to int, int call to
2217/// pointer; etc. Cast to 'void' is an exception.
2218static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2219 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002220 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2221 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002222 return;
2223
2224 if (!isa<CallExpr>(SrcExpr.get()))
2225 return;
2226
2227 QualType SrcType = SrcExpr.get()->getType();
2228 if (DestType.getUnqualifiedType()->isVoidType())
2229 return;
2230 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2231 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2232 return;
2233 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2234 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2235 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2236 return;
2237 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2238 return;
2239 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2240 return;
2241 if (SrcType->isComplexType() && DestType->isComplexType())
2242 return;
2243 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2244 return;
2245
2246 Self.Diag(SrcExpr.get()->getExprLoc(),
2247 diag::warn_bad_function_cast)
2248 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2249}
2250
John McCall9776e432011-10-06 23:25:11 +00002251/// Check the semantics of a C-style cast operation, in C.
2252void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002253 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002254
John McCall4124c492011-10-17 18:40:02 +00002255 // C-style casts can resolve __unknown_any types.
2256 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2257 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2258 SrcExpr.get(), Kind,
2259 ValueKind, BasePath);
2260 return;
2261 }
John McCall9776e432011-10-06 23:25:11 +00002262
2263 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2264 // type needs to be scalar.
2265 if (DestType->isVoidType()) {
2266 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002267 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002268 if (SrcExpr.isInvalid())
2269 return;
2270
2271 // Cast to void allows any expr type.
2272 Kind = CK_ToVoid;
2273 return;
2274 }
2275
George Burgess IV5f21c712015-10-12 19:57:04 +00002276 // Overloads are allowed with C extensions, so we need to support them.
2277 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2278 DeclAccessPair DAP;
2279 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2280 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2281 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2282 else
2283 return;
2284 assert(SrcExpr.isUsable());
2285 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002286 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002287 if (SrcExpr.isInvalid())
2288 return;
2289 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002290
John McCall4124c492011-10-17 18:40:02 +00002291 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002292
Joey Gouly8fc32f02014-01-14 12:47:29 +00002293 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2294 // address space B is illegal.
2295 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2296 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002297 const PointerType *DestPtr = DestType->getAs<PointerType>();
2298 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002299 Self.Diag(OpRange.getBegin(),
2300 diag::err_typecheck_incompatible_address_space)
2301 << SrcType << DestType << Sema::AA_Casting
2302 << SrcExpr.get()->getSourceRange();
2303 SrcExpr = ExprError();
2304 return;
2305 }
2306 }
2307
John McCall9776e432011-10-06 23:25:11 +00002308 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2309 diag::err_typecheck_cast_to_incomplete)) {
2310 SrcExpr = ExprError();
2311 return;
2312 }
2313
2314 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2315 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2316
2317 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2318 // GCC struct/union extension: allow cast to self.
2319 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2320 << DestType << SrcExpr.get()->getSourceRange();
2321 Kind = CK_NoOp;
2322 return;
2323 }
2324
2325 // GCC's cast to union extension.
2326 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2327 RecordDecl *RD = DestRecordTy->getDecl();
2328 RecordDecl::field_iterator Field, FieldEnd;
2329 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2330 Field != FieldEnd; ++Field) {
2331 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2332 !Field->isUnnamedBitfield()) {
2333 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2334 << SrcExpr.get()->getSourceRange();
2335 break;
2336 }
2337 }
2338 if (Field == FieldEnd) {
2339 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2340 << SrcType << SrcExpr.get()->getSourceRange();
2341 SrcExpr = ExprError();
2342 return;
2343 }
2344 Kind = CK_ToUnion;
2345 return;
2346 }
2347
2348 // Reject any other conversions to non-scalar types.
2349 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2350 << DestType << SrcExpr.get()->getSourceRange();
2351 SrcExpr = ExprError();
2352 return;
2353 }
2354
2355 // The type we're casting to is known to be a scalar or vector.
2356
2357 // Require the operand to be a scalar or vector.
2358 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2359 Self.Diag(SrcExpr.get()->getExprLoc(),
2360 diag::err_typecheck_expect_scalar_operand)
2361 << SrcType << SrcExpr.get()->getSourceRange();
2362 SrcExpr = ExprError();
2363 return;
2364 }
2365
2366 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002367 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002368 return;
2369 }
2370
2371 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2372 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2373 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2374 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002375 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002376 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2377 SrcExpr = ExprError();
2378 }
2379 return;
2380 }
2381
2382 if (SrcType->isVectorType()) {
2383 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2384 SrcExpr = ExprError();
2385 return;
2386 }
2387
2388 // The source and target types are both scalars, i.e.
2389 // - arithmetic types (fundamental, enum, and complex)
2390 // - all kinds of pointers
2391 // Note that member pointers were filtered out with C++, above.
2392
2393 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2394 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2395 SrcExpr = ExprError();
2396 return;
2397 }
2398
2399 // If either type is a pointer, the other type has to be either an
2400 // integer or a pointer.
2401 if (!DestType->isArithmeticType()) {
2402 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2403 Self.Diag(SrcExpr.get()->getExprLoc(),
2404 diag::err_cast_pointer_from_non_pointer_int)
2405 << SrcType << SrcExpr.get()->getSourceRange();
2406 SrcExpr = ExprError();
2407 return;
2408 }
David Blaikie282ad872012-10-16 18:53:14 +00002409 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2410 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002411 } else if (!SrcType->isArithmeticType()) {
2412 if (!DestType->isIntegralType(Self.Context) &&
2413 DestType->isArithmeticType()) {
2414 Self.Diag(SrcExpr.get()->getLocStart(),
2415 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002416 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002417 SrcExpr = ExprError();
2418 return;
2419 }
2420 }
2421
Joey Goulydd7f4562013-01-23 11:56:20 +00002422 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2423 if (DestType->isHalfType()) {
2424 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2425 << DestType << SrcExpr.get()->getSourceRange();
2426 SrcExpr = ExprError();
2427 return;
2428 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002429 }
2430
John McCall9776e432011-10-06 23:25:11 +00002431 // ARC imposes extra restrictions on casts.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002432 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCall9776e432011-10-06 23:25:11 +00002433 checkObjCARCConversion(Sema::CCK_CStyleCast);
2434 if (SrcExpr.isInvalid())
2435 return;
2436
2437 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2438 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2439 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2440 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2441 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2442 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2443 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2444 Self.Diag(SrcExpr.get()->getLocStart(),
2445 diag::err_typecheck_incompatible_ownership)
2446 << SrcType << DestType << Sema::AA_Casting
2447 << SrcExpr.get()->getSourceRange();
2448 return;
2449 }
2450 }
2451 }
2452 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2453 Self.Diag(SrcExpr.get()->getLocStart(),
2454 diag::err_arc_convesion_of_weak_unavailable)
2455 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2456 SrcExpr = ExprError();
2457 return;
2458 }
2459 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002460
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002461 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002462 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002463 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2464 if (SrcExpr.isInvalid())
2465 return;
2466
2467 if (Kind == CK_BitCast)
2468 checkCastAlign();
Roman Divackyd5178012014-11-21 21:03:10 +00002469
2470 // -Wcast-qual
2471 QualType TheOffendingSrcType, TheOffendingDestType;
2472 Qualifiers CastAwayQualifiers;
2473 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
2474 CastsAwayConstness(Self, SrcType, DestType, true, false,
2475 &TheOffendingSrcType, &TheOffendingDestType,
2476 &CastAwayQualifiers)) {
2477 int qualifiers = -1;
2478 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2479 qualifiers = 0;
2480 } else if (CastAwayQualifiers.hasConst()) {
2481 qualifiers = 1;
2482 } else if (CastAwayQualifiers.hasVolatile()) {
2483 qualifiers = 2;
2484 }
2485 // This is a variant of int **x; const int **y = (const int **)x;
2486 if (qualifiers == -1)
2487 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
2488 SrcType << DestType;
2489 else
2490 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
2491 TheOffendingSrcType << TheOffendingDestType << qualifiers;
2492 }
John McCall9776e432011-10-06 23:25:11 +00002493}
2494
2495ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2496 TypeSourceInfo *CastTypeInfo,
2497 SourceLocation RPLoc,
2498 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002499 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2500 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2501 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2502
David Blaikiebbafb8a2012-03-11 07:00:24 +00002503 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002504 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2505 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002506 } else {
2507 Op.CheckCStyleCast();
2508 }
2509
John McCallb50451a2011-10-05 07:41:44 +00002510 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002511 return ExprError();
2512
John McCall4124c492011-10-17 18:40:02 +00002513 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002514 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002515 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002516}
2517
2518ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2519 SourceLocation LPLoc,
2520 Expr *CastExpr,
2521 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002522 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb50451a2011-10-05 07:41:44 +00002523 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2524 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2525 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2526
Sebastian Redl2b80af42012-02-13 19:55:43 +00002527 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002528 if (Op.SrcExpr.isInvalid())
2529 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002530
2531 auto *SubExpr = Op.SrcExpr.get();
2532 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2533 SubExpr = BindExpr->getSubExpr();
2534 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002535 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002536
John McCall4124c492011-10-17 18:40:02 +00002537 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002538 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002539 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002540}