blob: b3f6be4aec73788f1a58c679fe3c9a3f3c4c2709 [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"
Reid Kleckner9f497332016-05-10 21:00:03 +000025#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000027#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000028#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000029using namespace clang;
30
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Douglas Gregore81f58e2010-11-08 03:40:48 +000032
Sebastian Redl9f831db2009-07-25 15:41:38 +000033enum TryCastResult {
34 TC_NotApplicable, ///< The cast method is not applicable.
35 TC_Success, ///< The cast method is appropriate and successful.
Richard Smithf276e2d2018-07-10 23:04:35 +000036 TC_Extension, ///< The cast method is appropriate and accepted as a
37 ///< language extension.
Sebastian Redl9f831db2009-07-25 15:41:38 +000038 TC_Failed ///< The cast method is appropriate, but failed. A
39 ///< diagnostic has been emitted.
40};
41
Richard Smithf276e2d2018-07-10 23:04:35 +000042static bool isValidCast(TryCastResult TCR) {
43 return TCR == TC_Success || TCR == TC_Extension;
44}
45
Sebastian Redl9f831db2009-07-25 15:41:38 +000046enum CastType {
47 CT_Const, ///< const_cast
48 CT_Static, ///< static_cast
49 CT_Reinterpret, ///< reinterpret_cast
50 CT_Dynamic, ///< dynamic_cast
51 CT_CStyle, ///< (Type)expr
52 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000053};
54
John McCallb50451a2011-10-05 07:41:44 +000055namespace {
56 struct CastOperation {
57 CastOperation(Sema &S, QualType destType, ExprResult src)
58 : Self(S), SrcExpr(src), DestType(destType),
59 ResultType(destType.getNonLValueExprType(S.Context)),
60 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000061 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000062
63 if (const BuiltinType *placeholder =
64 src.get()->getType()->getAsPlaceholderType()) {
65 PlaceholderKind = placeholder->getKind();
66 } else {
67 PlaceholderKind = (BuiltinType::Kind) 0;
68 }
69 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000070
John McCallb50451a2011-10-05 07:41:44 +000071 Sema &Self;
72 ExprResult SrcExpr;
73 QualType DestType;
74 QualType ResultType;
75 ExprValueKind ValueKind;
76 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000077 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000078 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000079 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000080
John McCallb50451a2011-10-05 07:41:44 +000081 SourceRange OpRange;
82 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000083
John McCall9776e432011-10-06 23:25:11 +000084 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000085 void CheckConstCast();
86 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000087 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000088 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000089 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000090 void CheckCStyleCast();
91
John McCall4124c492011-10-17 18:40:02 +000092 /// Complete an apparently-successful cast operation that yields
93 /// the given expression.
94 ExprResult complete(CastExpr *castExpr) {
95 // If this is an unbridged cast, wrap the result in an implicit
96 // cast that yields the unbridged-cast placeholder type.
97 if (IsARCUnbridgedCast) {
98 castExpr = ImplicitCastExpr::Create(Self.Context,
99 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000100 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +0000101 castExpr->getValueKind());
102 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000103 return castExpr;
John McCall4124c492011-10-17 18:40:02 +0000104 }
105
John McCall9776e432011-10-06 23:25:11 +0000106 // Internal convenience methods.
107
108 /// Try to handle the given placeholder expression kind. Return
109 /// true if the source expression has the appropriate placeholder
110 /// kind. A placeholder can only be claimed once.
111 bool claimPlaceholder(BuiltinType::Kind K) {
112 if (PlaceholderKind != K) return false;
113
114 PlaceholderKind = (BuiltinType::Kind) 0;
115 return true;
116 }
117
118 bool isPlaceholder() const {
119 return PlaceholderKind != 0;
120 }
121 bool isPlaceholder(BuiltinType::Kind K) const {
122 return PlaceholderKind == K;
123 }
John McCallb50451a2011-10-05 07:41:44 +0000124
125 void checkCastAlign() {
126 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
127 }
128
Brian Kelley11352a82017-03-29 18:09:02 +0000129 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
130 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
John McCall4124c492011-10-17 18:40:02 +0000131
John McCallb50451a2011-10-05 07:41:44 +0000132 Expr *src = SrcExpr.get();
Brian Kelley11352a82017-03-29 18:09:02 +0000133 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
134 Sema::ACR_unbridged)
John McCall4124c492011-10-17 18:40:02 +0000135 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000136 SrcExpr = src;
137 }
John McCall9776e432011-10-06 23:25:11 +0000138
139 /// Check for and handle non-overload placeholder expressions.
140 void checkNonOverloadPlaceholders() {
141 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
142 return;
143
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000144 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000145 if (SrcExpr.isInvalid())
146 return;
147 PlaceholderKind = (BuiltinType::Kind) 0;
148 }
John McCallb50451a2011-10-05 07:41:44 +0000149 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000150}
Sebastian Redl842ef522008-11-08 13:00:26 +0000151
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000152static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
153 QualType DestType);
154
Sebastian Redl9f831db2009-07-25 15:41:38 +0000155// The Try functions attempt a specific way of casting. If they succeed, they
156// return TC_Success. If their way of casting is not appropriate for the given
157// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
158// to emit if no other way succeeds. If their way of casting is appropriate but
159// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
160// they emit a specialized diagnostic.
161// All diagnostics returned by these functions must expect the same three
162// arguments:
163// %0: Cast Type (a value from the CastType enumeration)
164// %1: Source Type
165// %2: Destination Type
166static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000167 QualType DestType, bool CStyle,
168 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000169 CXXCastPath &BasePath,
170 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000171static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000172 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000173 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000174 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000175 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000176 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000177static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
178 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000179 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000180 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000181 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000182 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000183static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
184 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000185 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000186 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000187 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000188 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000189 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000190static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000191 QualType SrcType,
192 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000193 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000194 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000195 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000196 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000197
John Wiegley01296292011-04-08 18:41:53 +0000198static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000199 QualType DestType,
200 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000201 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000202 unsigned &msg, CastKind &Kind,
203 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000204static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000205 QualType DestType,
206 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000207 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000208 unsigned &msg, CastKind &Kind,
209 CXXCastPath &BasePath,
210 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000211static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
212 QualType DestType, bool CStyle,
213 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000214static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000215 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000216 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000217 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000218 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000219
Douglas Gregorb491ed32011-02-19 21:32:49 +0000220
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000221/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000222ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000223Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000224 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000225 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000226 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000227 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000228
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000229 assert(!D.isInvalidType());
230
231 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
232 if (D.isInvalidType())
233 return ExprError();
234
David Blaikiebbafb8a2012-03-11 07:00:24 +0000235 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000236 // Check that there are no default arguments (C++ only).
237 CheckExtraCXXDefaultArguments(D);
238 }
239
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000240 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000241 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
242 SourceRange(LParenLoc, RParenLoc));
243}
244
John McCalldadc5752010-08-24 06:29:42 +0000245ExprResult
John McCalld377e042010-01-15 19:13:16 +0000246Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000247 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000248 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000249 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000250 QualType DestType = DestTInfo->getType();
251
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000252 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000253 bool TypeDependent =
254 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000255
John McCallb50451a2011-10-05 07:41:44 +0000256 CastOperation Op(*this, DestType, E);
257 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
258 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000259
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000260 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000261 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000262
263 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000264 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000265 Op.CheckConstCast();
266 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000267 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000268 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000269 }
John McCall4124c492011-10-17 18:40:02 +0000270 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000272 OpLoc, Parens.getEnd(),
273 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000274
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000275 case tok::kw_dynamic_cast: {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000276 // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
277 if (getLangOpts().OpenCLCPlusPlus) {
278 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
279 << "dynamic_cast");
280 }
281
John Wiegley01296292011-04-08 18:41:53 +0000282 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000283 Op.CheckDynamicCast();
284 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000285 return ExprError();
286 }
John McCall4124c492011-10-17 18:40:02 +0000287 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000288 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000289 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000290 OpLoc, Parens.getEnd(),
291 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000292 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000293 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000294 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000295 Op.CheckReinterpretCast();
296 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000297 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000298 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000299 }
John McCall4124c492011-10-17 18:40:02 +0000300 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000301 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000302 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000303 Parens.getEnd(),
304 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000305 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000306 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000307 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000308 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000309 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000310 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000311 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000312 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000313
John McCall4124c492011-10-17 18:40:02 +0000314 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000315 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000316 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000317 OpLoc, Parens.getEnd(),
318 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000319 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000320 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000321}
322
John McCall909acf82011-02-14 18:34:10 +0000323/// Try to diagnose a failed overloaded cast. Returns true if
324/// diagnostics were emitted.
325static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
326 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000327 QualType destType,
328 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000329 switch (CT) {
330 // These cast kinds don't consider user-defined conversions.
331 case CT_Const:
332 case CT_Reinterpret:
333 case CT_Dynamic:
334 return false;
335
336 // These do.
337 case CT_Static:
338 case CT_CStyle:
339 case CT_Functional:
340 break;
341 }
342
343 QualType srcType = src->getType();
344 if (!destType->isRecordType() && !srcType->isRecordType())
345 return false;
346
347 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
348 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000349 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000350 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000351 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000352 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000353 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000354 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000355
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000356 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000357 switch (sequence.getFailureKind()) {
358 default: return false;
359
360 case InitializationSequence::FK_ConstructorOverloadFailed:
361 case InitializationSequence::FK_UserConversionOverloadFailed:
362 break;
363 }
364
365 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
366
367 unsigned msg = 0;
368 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
369
370 switch (sequence.getFailedOverloadResult()) {
371 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000372 case OR_No_Viable_Function:
373 if (candidates.empty())
374 msg = diag::err_ovl_no_conversion_in_cast;
375 else
376 msg = diag::err_ovl_no_viable_conversion_in_cast;
377 howManyCandidates = OCD_AllCandidates;
378 break;
379
380 case OR_Ambiguous:
381 msg = diag::err_ovl_ambiguous_conversion_in_cast;
382 howManyCandidates = OCD_ViableCandidates;
383 break;
384
385 case OR_Deleted:
386 msg = diag::err_ovl_deleted_conversion_in_cast;
387 howManyCandidates = OCD_ViableCandidates;
388 break;
389 }
390
391 S.Diag(range.getBegin(), msg)
392 << CT << srcType << destType
393 << range << src->getSourceRange();
394
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000395 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000396
397 return true;
398}
399
400/// Diagnose a failed cast.
401static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000402 SourceRange opRange, Expr *src, QualType destType,
403 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000404 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000405 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
406 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000407 return;
408
409 S.Diag(opRange.getBegin(), msg) << castType
410 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000411
412 // Detect if both types are (ptr to) class, and note any incompleteness.
413 int DifferentPtrness = 0;
414 QualType From = destType;
415 if (auto Ptr = From->getAs<PointerType>()) {
416 From = Ptr->getPointeeType();
417 DifferentPtrness++;
418 }
419 QualType To = src->getType();
420 if (auto Ptr = To->getAs<PointerType>()) {
421 To = Ptr->getPointeeType();
422 DifferentPtrness--;
423 }
424 if (!DifferentPtrness) {
425 auto RecFrom = From->getAs<RecordType>();
426 auto RecTo = To->getAs<RecordType>();
427 if (RecFrom && RecTo) {
428 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
429 if (!DeclFrom->isCompleteDefinition())
430 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
431 << DeclFrom->getDeclName();
432 auto DeclTo = RecTo->getAsCXXRecordDecl();
433 if (!DeclTo->isCompleteDefinition())
434 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
435 << DeclTo->getDeclName();
436 }
437 }
John McCall909acf82011-02-14 18:34:10 +0000438}
439
Richard Smithf276e2d2018-07-10 23:04:35 +0000440namespace {
441/// The kind of unwrapping we did when determining whether a conversion casts
442/// away constness.
443enum CastAwayConstnessKind {
444 /// The conversion does not cast away constness.
445 CACK_None = 0,
446 /// We unwrapped similar types.
447 CACK_Similar = 1,
448 /// We unwrapped dissimilar types with similar representations (eg, a pointer
449 /// versus an Objective-C object pointer).
450 CACK_SimilarKind = 2,
451 /// We unwrapped representationally-unrelated types, such as a pointer versus
452 /// a pointer-to-member.
453 CACK_Incoherent = 3,
454};
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000455}
456
Richard Smithf276e2d2018-07-10 23:04:35 +0000457/// Unwrap one level of types for CastsAwayConstness.
458///
Richard Smitha3405ff2018-07-11 00:19:19 +0000459/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
460/// both types, provided that they're both pointer-like or array-like. Unlike
461/// the Sema function, doesn't care if the unwrapped pieces are related.
Richard Smith5407d4f2018-07-18 20:13:36 +0000462///
463/// This function may remove additional levels as necessary for correctness:
464/// the resulting T1 is unwrapped sufficiently that it is never an array type,
465/// so that its qualifiers can be directly compared to those of T2 (which will
466/// have the combined set of qualifiers from all indermediate levels of T2),
467/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
468/// with those from T2.
Richard Smithf276e2d2018-07-10 23:04:35 +0000469static CastAwayConstnessKind
470unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000471 enum { None, Ptr, MemPtr, BlockPtr, Array };
Richard Smithf276e2d2018-07-10 23:04:35 +0000472 auto Classify = [](QualType T) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000473 if (T->isAnyPointerType()) return Ptr;
474 if (T->isMemberPointerType()) return MemPtr;
475 if (T->isBlockPointerType()) return BlockPtr;
Richard Smitha3405ff2018-07-11 00:19:19 +0000476 // We somewhat-arbitrarily don't look through VLA types here. This is at
477 // least consistent with the behavior of UnwrapSimilarTypes.
Richard Smith5407d4f2018-07-18 20:13:36 +0000478 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
479 return None;
Richard Smithf276e2d2018-07-10 23:04:35 +0000480 };
481
Richard Smitha3405ff2018-07-11 00:19:19 +0000482 auto Unwrap = [&](QualType T) {
483 if (auto *AT = Context.getAsArrayType(T))
484 return AT->getElementType();
485 return T->getPointeeType();
486 };
487
Richard Smith5407d4f2018-07-18 20:13:36 +0000488 CastAwayConstnessKind Kind;
489
490 if (T2->isReferenceType()) {
491 // Special case: if the destination type is a reference type, unwrap it as
492 // the first level. (The source will have been an lvalue expression in this
493 // case, so there is no corresponding "reference to" in T1 to remove.) This
494 // simulates removing a "pointer to" from both sides.
495 T2 = T2->getPointeeType();
496 Kind = CastAwayConstnessKind::CACK_Similar;
497 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
498 Kind = CastAwayConstnessKind::CACK_Similar;
499 } else {
500 // Try unwrapping mismatching levels.
501 int T1Class = Classify(T1);
502 if (T1Class == None)
503 return CastAwayConstnessKind::CACK_None;
504
505 int T2Class = Classify(T2);
506 if (T2Class == None)
507 return CastAwayConstnessKind::CACK_None;
508
509 T1 = Unwrap(T1);
510 T2 = Unwrap(T2);
511 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
512 : CastAwayConstnessKind::CACK_Incoherent;
513 }
514
515 // We've unwrapped at least one level. If the resulting T1 is a (possibly
516 // multidimensional) array type, any qualifier on any matching layer of
517 // T2 is considered to correspond to T1. Decompose down to the element
518 // type of T1 so that we can compare properly.
519 while (true) {
520 Context.UnwrapSimilarArrayTypes(T1, T2);
521
522 if (Classify(T1) != Array)
523 break;
524
525 auto T2Class = Classify(T2);
526 if (T2Class == None)
527 break;
528
529 if (T2Class != Array)
530 Kind = CastAwayConstnessKind::CACK_Incoherent;
531 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
532 Kind = CastAwayConstnessKind::CACK_SimilarKind;
533
534 T1 = Unwrap(T1);
535 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
536 }
537
538 return Kind;
Richard Smithf276e2d2018-07-10 23:04:35 +0000539}
540
541/// Check if the pointer conversion from SrcType to DestType casts away
542/// constness as defined in C++ [expr.const.cast]. This is used by the cast
543/// checkers. Both arguments must denote pointer (possibly to member) types.
John McCall31168b02011-06-15 23:02:42 +0000544///
545/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
John McCall31168b02011-06-15 23:02:42 +0000546/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Richard Smithf276e2d2018-07-10 23:04:35 +0000547static CastAwayConstnessKind
John McCall31168b02011-06-15 23:02:42 +0000548CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000549 bool CheckCVR, bool CheckObjCLifetime,
550 QualType *TheOffendingSrcType = nullptr,
551 QualType *TheOffendingDestType = nullptr,
552 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000553 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000554 // and we're not in ObjC mode, there's nothing to check.
Richard Smithf276e2d2018-07-10 23:04:35 +0000555 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC1)
556 return CastAwayConstnessKind::CACK_None;
557
558 if (!DestType->isReferenceType()) {
559 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
560 SrcType->isBlockPointerType()) &&
561 "Source type is not pointer or pointer to member.");
562 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
563 DestType->isBlockPointerType()) &&
564 "Destination type is not pointer or pointer to member.");
565 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000566
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000567 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
568 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000569
Douglas Gregorb472e932011-04-15 17:59:54 +0000570 // Find the qualifiers. We only care about cvr-qualifiers for the
571 // purpose of this check, because other qualifiers (address spaces,
572 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000573 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
574 QualType PrevUnwrappedDestType = UnwrappedDestType;
Richard Smithf276e2d2018-07-10 23:04:35 +0000575 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
576 bool AllConstSoFar = true;
577 while (auto Kind = unwrapCastAwayConstnessLevel(
578 Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
579 // Track the worst kind of unwrap we needed to do before we found a
580 // problem.
581 if (Kind > WorstKind)
582 WorstKind = Kind;
583
John McCall31168b02011-06-15 23:02:42 +0000584 // Determine the relevant qualifiers at this level.
585 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000586 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000587 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Akira Hatanaka8d7bdf62017-08-11 00:06:49 +0000588
589 // We do not meaningfully track object const-ness of Objective-C object
590 // types. Remove const from the source type if either the source or
591 // the destination is an Objective-C object type.
592 if (UnwrappedSrcType->isObjCObjectType() ||
593 UnwrappedDestType->isObjCObjectType())
594 SrcQuals.removeConst();
595
John McCall31168b02011-06-15 23:02:42 +0000596 if (CheckCVR) {
Richard Smithf276e2d2018-07-10 23:04:35 +0000597 Qualifiers SrcCvrQuals =
598 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
599 Qualifiers DestCvrQuals =
600 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000601
Richard Smithf276e2d2018-07-10 23:04:35 +0000602 if (SrcCvrQuals != DestCvrQuals) {
603 if (CastAwayQualifiers)
604 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
605
606 // If we removed a cvr-qualifier, this is casting away 'constness'.
607 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
608 if (TheOffendingSrcType)
609 *TheOffendingSrcType = PrevUnwrappedSrcType;
610 if (TheOffendingDestType)
611 *TheOffendingDestType = PrevUnwrappedDestType;
612 return WorstKind;
613 }
614
615 // If any prior level was not 'const', this is also casting away
616 // 'constness'. We noted the outermost type missing a 'const' already.
617 if (!AllConstSoFar)
618 return WorstKind;
Roman Divackyd5178012014-11-21 21:03:10 +0000619 }
John McCall31168b02011-06-15 23:02:42 +0000620 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000621
John McCall31168b02011-06-15 23:02:42 +0000622 if (CheckObjCLifetime &&
623 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
Richard Smithf276e2d2018-07-10 23:04:35 +0000624 return WorstKind;
625
626 // If we found our first non-const-qualified type, this may be the place
627 // where things start to go wrong.
628 if (AllConstSoFar && !DestQuals.hasConst()) {
629 AllConstSoFar = false;
630 if (TheOffendingSrcType)
631 *TheOffendingSrcType = PrevUnwrappedSrcType;
632 if (TheOffendingDestType)
633 *TheOffendingDestType = PrevUnwrappedDestType;
634 }
Roman Divackyd5178012014-11-21 21:03:10 +0000635
636 PrevUnwrappedSrcType = UnwrappedSrcType;
637 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000638 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000639
Richard Smithf276e2d2018-07-10 23:04:35 +0000640 return CastAwayConstnessKind::CACK_None;
641}
642
643static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
644 unsigned &DiagID) {
645 switch (CACK) {
646 case CastAwayConstnessKind::CACK_None:
647 llvm_unreachable("did not cast away constness");
648
649 case CastAwayConstnessKind::CACK_Similar:
650 // FIXME: Accept these as an extension too?
651 case CastAwayConstnessKind::CACK_SimilarKind:
652 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
653 return TC_Failed;
654
655 case CastAwayConstnessKind::CACK_Incoherent:
656 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
657 return TC_Extension;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000658 }
659
Richard Smithf276e2d2018-07-10 23:04:35 +0000660 llvm_unreachable("unexpected cast away constness kind");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000661}
662
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000663/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
664/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
665/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000666void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000667 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000668 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000669 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000670 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000671 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
672 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000673
John McCallb50451a2011-10-05 07:41:44 +0000674 QualType OrigSrcType = SrcExpr.get()->getType();
675 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000676
677 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
678 // or "pointer to cv void".
679
680 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000681 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000683 if (DestPointer) {
684 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000685 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000686 DestPointee = DestReference->getPointeeType();
687 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000688 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000689 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000690 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000691 return;
692 }
693
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000694 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000695 if (DestPointee->isVoidType()) {
696 assert(DestPointer && "Reference to void is not possible");
697 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000698 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000699 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000700 DestRange)) {
701 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000702 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000703 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000704 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000705 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000706 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000707 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000708 return;
709 }
710
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000711 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
712 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000713 // an lvalue of a complete class type, [...]. If T is an rvalue reference
714 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000715 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000716 QualType SrcPointee;
717 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000718 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000719 SrcPointee = SrcPointer->getPointeeType();
720 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000721 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000722 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000723 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000724 return;
725 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000726 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000727 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000728 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000729 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000730 }
731 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000732 } else {
Richard Smith11330852014-07-08 17:25:14 +0000733 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
734 // to materialize the prvalue before we bind the reference to it.
735 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000736 SrcExpr = Self.CreateMaterializeTemporaryExpr(
737 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000738 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000739 }
740
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000741 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000742 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000743 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000744 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000745 SrcExpr.get())) {
746 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000747 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000748 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000749 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000750 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000751 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000752 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000753 return;
754 }
755
756 assert((DestPointer || DestReference) &&
757 "Bad destination non-ptr/ref slipped through.");
758 assert((DestRecord || DestPointee->isVoidType()) &&
759 "Bad destination pointee slipped through.");
760 assert(SrcRecord && "Bad source pointee slipped through.");
761
762 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
763 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000764 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000765 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000766 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000767 return;
768 }
769
770 // C++ 5.2.7p3: If the type of v is the same as the required result type,
771 // [except for cv].
772 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000773 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000774 return;
775 }
776
777 // C++ 5.2.7p5
778 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000779 if (DestRecord &&
780 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000781 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
782 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000783 &BasePath)) {
784 SrcExpr = ExprError();
785 return;
786 }
Richard Smith11330852014-07-08 17:25:14 +0000787
John McCalle3027922010-08-25 11:45:40 +0000788 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000789 return;
790 }
791
792 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000793 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000794 assert(SrcDecl && "Definition missing");
795 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000796 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000797 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000798 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000799 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000800
Eli Friedman3ce27102013-09-24 23:21:41 +0000801 // dynamic_cast is not available with -fno-rtti.
802 // As an exception, dynamic_cast to void* is available because it doesn't
803 // use RTTI.
804 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000805 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
806 SrcExpr = ExprError();
807 return;
808 }
809
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000810 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000811 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000812}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000813
814/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
815/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
816/// like this:
817/// const char *str = "literal";
818/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000819void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000820 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000821 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000822 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000823 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000824 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
825 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000826
827 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smithf276e2d2018-07-10 23:04:35 +0000828 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
829 if (TCR != TC_Success && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000830 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000831 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000832 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000833 if (!isValidCast(TCR))
834 SrcExpr = ExprError();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000835}
836
John McCallcda80832013-03-22 02:58:14 +0000837/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
838/// or downcast between respective pointers or references.
839static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
840 QualType DestType,
841 SourceRange OpRange) {
842 QualType SrcType = SrcExpr->getType();
843 // When casting from pointer or reference, get pointee type; use original
844 // type otherwise.
845 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
846 const CXXRecordDecl *SrcRD =
847 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
848
John McCallf2abe192013-03-27 00:03:48 +0000849 // Examining subobjects for records is only possible if the complete and
850 // valid definition is available. Also, template instantiation is not
851 // allowed here.
852 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000853 return;
854
855 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
856
John McCallf2abe192013-03-27 00:03:48 +0000857 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000858 return;
859
860 enum {
861 ReinterpretUpcast,
862 ReinterpretDowncast
863 } ReinterpretKind;
864
865 CXXBasePaths BasePaths;
866
867 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
868 ReinterpretKind = ReinterpretUpcast;
869 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
870 ReinterpretKind = ReinterpretDowncast;
871 else
872 return;
873
874 bool VirtualBase = true;
875 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000876 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000877 E = BasePaths.end();
878 I != E; ++I) {
879 const CXXBasePath &Path = *I;
880 CharUnits Offset = CharUnits::Zero();
881 bool IsVirtual = false;
882 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
883 IElem != EElem; ++IElem) {
884 IsVirtual = IElem->Base->isVirtual();
885 if (IsVirtual)
886 break;
887 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
888 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000889 // Don't check if any base has invalid declaration or has no definition
890 // since it has no layout info.
891 const CXXRecordDecl *Class = IElem->Class,
892 *ClassDefinition = Class->getDefinition();
893 if (Class->isInvalidDecl() || !ClassDefinition ||
894 !ClassDefinition->isCompleteDefinition())
895 return;
896
John McCallcda80832013-03-22 02:58:14 +0000897 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000898 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000899 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
900 }
901 if (!IsVirtual) {
902 // Don't warn if any path is a non-virtually derived base at offset zero.
903 if (Offset.isZero())
904 return;
905 // Offset makes sense only for non-virtual bases.
906 else
907 NonZeroOffset = true;
908 }
909 VirtualBase = VirtualBase && IsVirtual;
910 }
911
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000912 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000913 assert((VirtualBase || NonZeroOffset) &&
914 "Should have returned if has non-virtual base with zero offset");
915
916 QualType BaseType =
917 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
918 QualType DerivedType =
919 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
920
Jordan Rose04a94d12013-03-28 19:09:40 +0000921 SourceLocation BeginLoc = OpRange.getBegin();
922 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000923 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000924 << OpRange;
925 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000926 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000927 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000928}
929
Sebastian Redl9f831db2009-07-25 15:41:38 +0000930/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
931/// valid.
932/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
933/// like this:
934/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000935void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000936 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000937 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000938 else
939 checkNonOverloadPlaceholders();
940 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
941 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000942
943 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000944 TryCastResult tcr =
945 TryReinterpretCast(Self, SrcExpr, DestType,
946 /*CStyle*/false, OpRange, msg, Kind);
Richard Smithf276e2d2018-07-10 23:04:35 +0000947 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000948 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
949 return;
950 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000951 //FIXME: &f<int>; is overloaded and resolvable
952 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000953 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000954 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000955 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000956
John McCall909acf82011-02-14 18:34:10 +0000957 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000958 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
959 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000960 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000961 }
962
963 if (isValidCast(tcr)) {
Brian Kelley762f9282017-03-29 18:16:38 +0000964 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000965 checkObjCConversion(Sema::CCK_OtherCast);
John McCallcda80832013-03-22 02:58:14 +0000966 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
Richard Smithf276e2d2018-07-10 23:04:35 +0000967 } else {
968 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000969 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000970}
971
972
973/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
974/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
975/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000976void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000977 if (isPlaceholder()) {
978 checkNonOverloadPlaceholders();
979 if (SrcExpr.isInvalid())
980 return;
981 }
982
Sebastian Redl9f831db2009-07-25 15:41:38 +0000983 // This test is outside everything else because it's the only case where
984 // a non-lvalue-reference target type does not lead to decay.
985 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000986 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000987 Kind = CK_ToVoid;
988
989 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000990 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000991 false, // Decay Function to ptr
992 true, // Complain
993 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000994 if (SrcExpr.isInvalid())
995 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000996 }
John McCall9776e432011-10-06 23:25:11 +0000997
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000998 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000999 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001000 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001001
John McCall50a2c2c2011-10-11 23:14:30 +00001002 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1003 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001004 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00001005 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1006 return;
1007 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001008
1009 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +00001010 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +00001011 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001012 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +00001013 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +00001014 if (SrcExpr.isInvalid())
1015 return;
1016 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1017 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +00001018 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +00001019 << oe->getName() << DestType << OpRange
1020 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00001021 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +00001022 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +00001023 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1024 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001025 }
Richard Smithf276e2d2018-07-10 23:04:35 +00001026 }
1027
1028 if (isValidCast(tcr)) {
John McCall31168b02011-06-15 23:02:42 +00001029 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +00001030 checkCastAlign();
Brian Kelley762f9282017-03-29 18:16:38 +00001031 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +00001032 checkObjCConversion(Sema::CCK_OtherCast);
Richard Smithf276e2d2018-07-10 23:04:35 +00001033 } else {
1034 SrcExpr = ExprError();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001035 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001036}
1037
1038/// TryStaticCast - Check if a static cast can be performed, and do so if
1039/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1040/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +00001041static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +00001042 QualType DestType,
1043 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001044 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001045 CastKind &Kind, CXXCastPath &BasePath,
1046 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +00001047 // Determine whether we have the semantics of a C-style cast.
1048 bool CStyle
1049 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1050
Sebastian Redl9f831db2009-07-25 15:41:38 +00001051 // The order the tests is not entirely arbitrary. There is one conversion
1052 // that can be handled in two different ways. Given:
1053 // struct A {};
1054 // struct B : public A {
1055 // B(); B(const A&);
1056 // };
1057 // const A &a = B();
1058 // the cast static_cast<const B&>(a) could be seen as either a static
1059 // reference downcast, or an explicit invocation of the user-defined
1060 // conversion using B's conversion constructor.
1061 // DR 427 specifies that the downcast is to be applied here.
1062
1063 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1064 // Done outside this function.
1065
1066 TryCastResult tcr;
1067
1068 // C++ 5.2.9p5, reference downcast.
1069 // See the function for details.
1070 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +00001071 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1072 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001073 if (tcr != TC_NotApplicable)
1074 return tcr;
1075
Davide Italianoa2275912015-07-12 22:10:56 +00001076 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001077 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1078 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001079 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
Sebastian Redld74dd492012-02-12 18:41:05 +00001080 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +00001081 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001082 return tcr;
1083
1084 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1085 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +00001086 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001087 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +00001088 if (SrcExpr.isInvalid())
1089 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001090 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001091 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +00001092
Sebastian Redl9f831db2009-07-25 15:41:38 +00001093 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1094 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1095 // conversions, subject to further restrictions.
1096 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1097 // of qualification conversions impossible.
1098 // In the CStyle case, the earlier attempt to const_cast should have taken
1099 // care of reverse qualification conversions.
1100
John Wiegley01296292011-04-08 18:41:53 +00001101 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001102
Douglas Gregor0bf31402010-10-08 23:50:27 +00001103 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001104 // converted to an integral type. [...] A value of a scoped enumeration type
1105 // can also be explicitly converted to a floating-point type [...].
1106 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1107 if (Enum->getDecl()->isScoped()) {
1108 if (DestType->isBooleanType()) {
1109 Kind = CK_IntegralToBoolean;
1110 return TC_Success;
1111 } else if (DestType->isIntegralType(Self.Context)) {
1112 Kind = CK_IntegralCast;
1113 return TC_Success;
1114 } else if (DestType->isRealFloatingType()) {
1115 Kind = CK_IntegralToFloating;
1116 return TC_Success;
1117 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001118 }
1119 }
Douglas Gregorb327eac2011-02-18 03:01:41 +00001120
Sebastian Redl9f831db2009-07-25 15:41:38 +00001121 // Reverse integral promotion/conversion. All such conversions are themselves
1122 // again integral promotions or conversions and are thus already handled by
1123 // p2 (TryDirectInitialization above).
1124 // (Note: any data loss warnings should be suppressed.)
1125 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1126 // enum->enum). See also C++ 5.2.9p7.
1127 // The same goes for reverse floating point promotion/conversion and
1128 // floating-integral conversions. Again, only floating->enum is relevant.
1129 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001130 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001131 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001132 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001133 } else if (SrcType->isRealFloatingType()) {
1134 Kind = CK_FloatingToIntegral;
1135 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001136 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001137 }
1138
1139 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1140 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001141 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001142 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001143 if (tcr != TC_NotApplicable)
1144 return tcr;
1145
1146 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1147 // conversion. C++ 5.2.9p9 has additional information.
1148 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001149 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001150 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001151 if (tcr != TC_NotApplicable)
1152 return tcr;
1153
1154 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1155 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1156 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001157 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001158 QualType SrcPointee = SrcPointer->getPointeeType();
1159 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001160 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001161 QualType DestPointee = DestPointer->getPointeeType();
1162 if (DestPointee->isIncompleteOrObjectType()) {
1163 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001164 // to a qualifier violation. Note that we permit Objective-C lifetime
1165 // and GC qualifier mismatches here.
1166 if (!CStyle) {
1167 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1168 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1169 DestPointeeQuals.removeObjCGCAttr();
1170 DestPointeeQuals.removeObjCLifetime();
1171 SrcPointeeQuals.removeObjCGCAttr();
1172 SrcPointeeQuals.removeObjCLifetime();
1173 if (DestPointeeQuals != SrcPointeeQuals &&
1174 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1175 msg = diag::err_bad_cxx_cast_qualifiers_away;
1176 return TC_Failed;
1177 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001178 }
John McCalle3027922010-08-25 11:45:40 +00001179 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001180 return TC_Success;
1181 }
David Majnemer85bd1202015-06-02 22:15:12 +00001182
1183 // Microsoft permits static_cast from 'pointer-to-void' to
1184 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001185 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1186 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001187 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1188 Kind = CK_BitCast;
1189 return TC_Success;
1190 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001191 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001192 else if (DestType->isObjCObjectPointerType()) {
1193 // allow both c-style cast and static_cast of objective-c pointers as
1194 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001195 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001196 return TC_Success;
1197 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001198 else if (CStyle && DestType->isBlockPointerType()) {
1199 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001200 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001201 return TC_Success;
1202 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001203 }
1204 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001205 // Allow arbitrary objective-c pointer conversion with static casts.
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001206 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001207 DestType->isObjCObjectPointerType()) {
1208 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001209 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001210 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001211 // Allow ns-pointer to cf-pointer conversion in either direction
1212 // with static casts.
1213 if (!CStyle &&
1214 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1215 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001216
1217 // See if it looks like the user is trying to convert between
1218 // related record types, and select a better diagnostic if so.
1219 if (auto SrcPointer = SrcType->getAs<PointerType>())
1220 if (auto DestPointer = DestType->getAs<PointerType>())
1221 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1222 DestPointer->getPointeeType()->getAs<RecordType>())
1223 msg = diag::err_bad_cxx_cast_unrelated_class;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001224
Sebastian Redl9f831db2009-07-25 15:41:38 +00001225 // We tried everything. Everything! Nothing works! :-(
1226 return TC_NotApplicable;
1227}
1228
1229/// Tests whether a conversion according to N2844 is valid.
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001230TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1231 QualType DestType, bool CStyle,
1232 CastKind &Kind, CXXCastPath &BasePath,
1233 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001234 // C++11 [expr.static.cast]p3:
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001235 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
Douglas Gregor465184a2011-01-22 00:06:57 +00001236 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001237 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001238 if (!R)
1239 return TC_NotApplicable;
1240
Douglas Gregor465184a2011-01-22 00:06:57 +00001241 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001242 return TC_NotApplicable;
1243
1244 // Because we try the reference downcast before this function, from now on
1245 // this is the only cast possibility, so we issue an error if we fail now.
1246 // FIXME: Should allow casting away constness if CStyle.
1247 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001248 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001249 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001250 QualType FromType = SrcExpr->getType();
1251 QualType ToType = R->getPointeeType();
1252 if (CStyle) {
1253 FromType = FromType.getUnqualifiedType();
1254 ToType = ToType.getUnqualifiedType();
1255 }
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001256
1257 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1258 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
1259 ObjCLifetimeConversion);
1260 if (RefResult != Sema::Ref_Compatible) {
1261 if (CStyle || RefResult == Sema::Ref_Incompatible)
Davide Italianoa2275912015-07-12 22:10:56 +00001262 return TC_NotApplicable;
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001263 // Diagnose types which are reference-related but not compatible here since
1264 // we can provide better diagnostics. In these cases forwarding to
1265 // [expr.static.cast]p4 should never result in a well-formed cast.
1266 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1267 : diag::err_bad_rvalue_to_rvalue_cast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001268 return TC_Failed;
1269 }
1270
Douglas Gregorba278e22011-01-25 16:13:26 +00001271 if (DerivedToBase) {
1272 Kind = CK_DerivedToBase;
1273 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1274 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001275 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1276 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001277 return TC_NotApplicable;
1278
1279 Self.BuildBasePathArray(Paths, BasePath);
1280 } else
1281 Kind = CK_NoOp;
1282
Sebastian Redl9f831db2009-07-25 15:41:38 +00001283 return TC_Success;
1284}
1285
1286/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1287TryCastResult
1288TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001289 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001290 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001291 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001292 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1293 // cast to type "reference to cv2 D", where D is a class derived from B,
1294 // if a valid standard conversion from "pointer to D" to "pointer to B"
1295 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1296 // In addition, DR54 clarifies that the base must be accessible in the
1297 // current context. Although the wording of DR54 only applies to the pointer
1298 // variant of this rule, the intent is clearly for it to apply to the this
1299 // conversion as well.
1300
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001301 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001302 if (!DestReference) {
1303 return TC_NotApplicable;
1304 }
1305 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001306 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001307 // We know the left side is an lvalue reference, so we can suggest a reason.
1308 msg = diag::err_bad_cxx_cast_rvalue;
1309 return TC_NotApplicable;
1310 }
1311
1312 QualType DestPointee = DestReference->getPointeeType();
1313
Richard Smith11330852014-07-08 17:25:14 +00001314 // FIXME: If the source is a prvalue, we should issue a warning (because the
1315 // cast always has undefined behavior), and for AST consistency, we should
1316 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001317 return TryStaticDowncast(Self,
1318 Self.Context.getCanonicalType(SrcExpr->getType()),
1319 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001320 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1321 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001322}
1323
1324/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1325TryCastResult
1326TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001327 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001328 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001329 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001330 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1331 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1332 // is a class derived from B, if a valid standard conversion from "pointer
1333 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1334 // class of D.
1335 // In addition, DR54 clarifies that the base must be accessible in the
1336 // current context.
1337
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001338 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001339 if (!DestPointer) {
1340 return TC_NotApplicable;
1341 }
1342
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001343 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001344 if (!SrcPointer) {
1345 msg = diag::err_bad_static_cast_pointer_nonpointer;
1346 return TC_NotApplicable;
1347 }
1348
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001349 return TryStaticDowncast(Self,
1350 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1351 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001352 CStyle, OpRange, SrcType, DestType, msg, Kind,
1353 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001354}
1355
1356/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1357/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001358/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001359TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001360TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001361 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001362 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001363 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001364 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001365 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1366 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001367 return TC_NotApplicable;
1368
Sebastian Redl9f831db2009-07-25 15:41:38 +00001369 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001370 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001371 return TC_NotApplicable;
1372 }
1373
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001374 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001375 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001376 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001377 return TC_NotApplicable;
1378 }
1379
1380 // Target type does derive from source type. Now we're serious. If an error
1381 // appears now, it's not ignored.
1382 // This may not be entirely in line with the standard. Take for example:
1383 // struct A {};
1384 // struct B : virtual A {
1385 // B(A&);
1386 // };
Mike Stump11289f42009-09-09 15:08:12 +00001387 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001388 // void f()
1389 // {
1390 // (void)static_cast<const B&>(*((A*)0));
1391 // }
1392 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1393 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1394 // However, both GCC and Comeau reject this example, and accepting it would
1395 // mean more complex code if we're to preserve the nice error message.
1396 // FIXME: Being 100% compliant here would be nice to have.
1397
1398 // Must preserve cv, as always, unless we're in C-style mode.
1399 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001400 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001401 return TC_Failed;
1402 }
1403
1404 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1405 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1406 // that it builds the paths in reverse order.
1407 // To sum up: record all paths to the base and build a nice string from
1408 // them. Use it to spice up the error message.
1409 if (!Paths.isRecordingPaths()) {
1410 Paths.clear();
1411 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001412 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001413 }
1414 std::string PathDisplayStr;
1415 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001416 for (clang::CXXBasePath &Path : Paths) {
1417 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001418 // We haven't displayed a path to this particular base
1419 // class subobject yet.
1420 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001421 for (CXXBasePathElement &PE : llvm::reverse(Path))
1422 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001423 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001424 }
1425 }
1426
1427 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001428 << QualType(SrcType).getUnqualifiedType()
1429 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001430 << PathDisplayStr << OpRange;
1431 msg = 0;
1432 return TC_Failed;
1433 }
1434
Craig Topperc3ec1492014-05-26 06:22:03 +00001435 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001436 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1437 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1438 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1439 msg = 0;
1440 return TC_Failed;
1441 }
1442
John McCallfe9cf0a2011-02-14 23:21:33 +00001443 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001444 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1445 SrcType, DestType,
1446 Paths.front(),
1447 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001448 case Sema::AR_accessible:
1449 case Sema::AR_delayed: // be optimistic
1450 case Sema::AR_dependent: // be optimistic
1451 break;
1452
1453 case Sema::AR_inaccessible:
1454 msg = 0;
1455 return TC_Failed;
1456 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001457 }
1458
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001459 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001460 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001461 return TC_Success;
1462}
1463
1464/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1465/// C++ 5.2.9p9 is valid:
1466///
1467/// An rvalue of type "pointer to member of D of type cv1 T" can be
1468/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1469/// where B is a base class of D [...].
1470///
1471TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001472TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001473 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001474 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001475 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001476 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001477 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001478 if (!DestMemPtr)
1479 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001480
1481 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001482 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001483 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001484 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001485 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001486 FoundOverload)) {
1487 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1488 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1489 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1490 WasOverloadedFunction = true;
1491 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001492 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001493
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001494 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001495 if (!SrcMemPtr) {
1496 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1497 return TC_NotApplicable;
1498 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001499
1500 // Lock down the inheritance model right now in MS ABI, whether or not the
1501 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001502 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001503 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001504 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1505 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001506
1507 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001508 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1509 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001510 return TC_NotApplicable;
1511
1512 // B base of D
1513 QualType SrcClass(SrcMemPtr->getClass(), 0);
1514 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001515 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001516 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001517 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001518 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001519
1520 // 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 +00001521 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001522 Paths.clear();
1523 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001524 bool StillOkay =
1525 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001526 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001527 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001528 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1529 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1530 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1531 msg = 0;
1532 return TC_Failed;
1533 }
1534
1535 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1536 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1537 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1538 msg = 0;
1539 return TC_Failed;
1540 }
1541
John McCallfe9cf0a2011-02-14 23:21:33 +00001542 if (!CStyle) {
1543 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1544 DestClass, SrcClass,
1545 Paths.front(),
1546 diag::err_upcast_to_inaccessible_base)) {
1547 case Sema::AR_accessible:
1548 case Sema::AR_delayed:
1549 case Sema::AR_dependent:
1550 // Optimistically assume that the delayed and dependent cases
1551 // will work out.
1552 break;
1553
1554 case Sema::AR_inaccessible:
1555 msg = 0;
1556 return TC_Failed;
1557 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001558 }
1559
Douglas Gregorc934bc82010-03-07 23:24:59 +00001560 if (WasOverloadedFunction) {
1561 // Resolve the address of the overloaded function again, this time
1562 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001563 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001564 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001565 true,
1566 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001567 if (!Fn) {
1568 msg = 0;
1569 return TC_Failed;
1570 }
1571
John McCall16df1e52010-03-30 21:47:33 +00001572 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001573 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001574 msg = 0;
1575 return TC_Failed;
1576 }
1577 }
1578
Anders Carlssonb78feca2010-04-24 19:22:20 +00001579 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001580 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001581 return TC_Success;
1582}
1583
1584/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1585/// is valid:
1586///
1587/// An expression e can be explicitly converted to a type T using a
1588/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1589TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001590TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001591 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001592 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001593 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001594 if (DestType->isRecordType()) {
1595 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001596 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001597 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001598 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001599 msg = 0;
1600 return TC_Failed;
1601 }
1602 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001603
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001604 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1605 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001606 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001607 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001608 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001609 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001610 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001611 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001612 Expr *SrcExprRaw = SrcExpr.get();
Richard Smithb8c0f552016-12-09 18:49:13 +00001613 // FIXME: Per DR242, we should check for an implicit conversion sequence
1614 // or for a constructor that could be invoked by direct-initialization
1615 // here, not for an initialization sequence.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001616 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001617
1618 // At this point of CheckStaticCast, if the destination is a reference,
1619 // or the expression is an overload expression this has to work.
1620 // There is no other way that works.
1621 // On the other hand, if we're checking a C-style cast, we've still got
1622 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001623 bool CStyle
1624 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001625 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001626 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001627
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001628 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001629 if (Result.isInvalid()) {
1630 msg = 0;
1631 return TC_Failed;
1632 }
1633
Douglas Gregorb33eed02010-04-16 22:09:46 +00001634 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001635 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001636 else
John McCalle3027922010-08-25 11:45:40 +00001637 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001638
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001639 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001640 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001641}
1642
1643/// TryConstCast - See if a const_cast from source to destination is allowed,
1644/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001645static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1646 QualType DestType, bool CStyle,
1647 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001648 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001649 QualType SrcType = SrcExpr.get()->getType();
1650 bool NeedToMaterializeTemporary = false;
1651
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001652 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001653 // C++11 5.2.11p4:
1654 // if a pointer to T1 can be explicitly converted to the type "pointer to
1655 // T2" using a const_cast, then the following conversions can also be
1656 // made:
1657 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1658 // type T2 using the cast const_cast<T2&>;
1659 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1660 // type T2 using the cast const_cast<T2&&>; and
1661 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1662 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1663
1664 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001665 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1666 // is C-style, static_cast might find a way, so we simply suggest a
1667 // message and tell the parent to keep searching.
1668 msg = diag::err_bad_cxx_cast_rvalue;
1669 return TC_NotApplicable;
1670 }
1671
Richard Smith82c9b512013-06-14 22:27:52 +00001672 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1673 if (!SrcType->isRecordType()) {
1674 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1675 // this is C-style, static_cast can do this.
1676 msg = diag::err_bad_cxx_cast_rvalue;
1677 return TC_NotApplicable;
1678 }
1679
1680 // Materialize the class prvalue so that the const_cast can bind a
1681 // reference to it.
1682 NeedToMaterializeTemporary = true;
1683 }
1684
John McCalld25db7e2013-05-06 21:39:12 +00001685 // It's not completely clear under the standard whether we can
1686 // const_cast bit-field gl-values. Doing so would not be
1687 // intrinsically complicated, but for now, we say no for
1688 // consistency with other compilers and await the word of the
1689 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001690 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001691 msg = diag::err_bad_cxx_cast_bitfield;
1692 return TC_NotApplicable;
1693 }
1694
Sebastian Redl9f831db2009-07-25 15:41:38 +00001695 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1696 SrcType = Self.Context.getPointerType(SrcType);
1697 }
1698
1699 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1700 // the rules for const_cast are the same as those used for pointers.
1701
John McCall0e704f72010-05-18 09:35:29 +00001702 if (!DestType->isPointerType() &&
1703 !DestType->isMemberPointerType() &&
1704 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001705 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1706 // was a reference type, we converted it to a pointer above.
1707 // The status of rvalue references isn't entirely clear, but it looks like
1708 // conversion to them is simply invalid.
1709 // C++ 5.2.11p3: For two pointer types [...]
1710 if (!CStyle)
1711 msg = diag::err_bad_const_cast_dest;
1712 return TC_NotApplicable;
1713 }
1714 if (DestType->isFunctionPointerType() ||
1715 DestType->isMemberFunctionPointerType()) {
1716 // Cannot cast direct function pointers.
1717 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1718 // T is the ultimate pointee of source and target type.
1719 if (!CStyle)
1720 msg = diag::err_bad_const_cast_dest;
1721 return TC_NotApplicable;
1722 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001723
Richard Smitha3405ff2018-07-11 00:19:19 +00001724 // C++ [expr.const.cast]p3:
1725 // "For two similar types T1 and T2, [...]"
1726 //
1727 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1728 // type qualifiers. (Likewise, we ignore other changes when determining
1729 // whether a cast casts away constness.)
1730 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001731 return TC_NotApplicable;
1732
Richard Smith82c9b512013-06-14 22:27:52 +00001733 if (NeedToMaterializeTemporary)
1734 // This is a const_cast from a class prvalue to an rvalue reference type.
1735 // Materialize a temporary to store the result of the conversion.
Richard Smithb8c0f552016-12-09 18:49:13 +00001736 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1737 SrcExpr.get(),
Tim Shen4a05bb82016-06-21 20:29:17 +00001738 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001739
Sebastian Redl9f831db2009-07-25 15:41:38 +00001740 return TC_Success;
1741}
1742
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001743// Checks for undefined behavior in reinterpret_cast.
1744// The cases that is checked for is:
1745// *reinterpret_cast<T*>(&a)
1746// reinterpret_cast<T&>(a)
1747// where accessing 'a' as type 'T' will result in undefined behavior.
1748void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1749 bool IsDereference,
1750 SourceRange Range) {
1751 unsigned DiagID = IsDereference ?
1752 diag::warn_pointer_indirection_from_incompatible_type :
1753 diag::warn_undefined_reinterpret_cast;
1754
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001755 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001756 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001757
1758 QualType SrcTy, DestTy;
1759 if (IsDereference) {
1760 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1761 return;
1762 }
1763 SrcTy = SrcType->getPointeeType();
1764 DestTy = DestType->getPointeeType();
1765 } else {
1766 if (!DestType->getAs<ReferenceType>()) {
1767 return;
1768 }
1769 SrcTy = SrcType;
1770 DestTy = DestType->getPointeeType();
1771 }
1772
1773 // Cast is compatible if the types are the same.
1774 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1775 return;
1776 }
1777 // or one of the types is a char or void type
1778 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1779 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1780 return;
1781 }
1782 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001783 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001784 return;
1785 }
1786
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001787 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001788 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1789 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1790 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1791 return;
1792 }
1793 }
1794
1795 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1796}
Douglas Gregor1beec452011-03-12 01:48:56 +00001797
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001798static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1799 QualType DestType) {
1800 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001801 if (Self.Context.hasSameType(SrcType, DestType))
1802 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001803 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1804 if (SrcPtrTy->isObjCSelType()) {
1805 QualType DT = DestType;
1806 if (isa<PointerType>(DestType))
1807 DT = DestType->getPointeeType();
1808 if (!DT.getUnqualifiedType()->isVoidType())
1809 Self.Diag(SrcExpr.get()->getExprLoc(),
1810 diag::warn_cast_pointer_from_sel)
1811 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1812 }
1813}
1814
Reid Kleckner9f497332016-05-10 21:00:03 +00001815/// Diagnose casts that change the calling convention of a pointer to a function
1816/// defined in the current TU.
1817static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1818 QualType DstType, SourceRange OpRange) {
1819 // Check if this cast would change the calling convention of a function
1820 // pointer type.
1821 QualType SrcType = SrcExpr.get()->getType();
1822 if (Self.Context.hasSameType(SrcType, DstType) ||
1823 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1824 return;
1825 const auto *SrcFTy =
1826 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1827 const auto *DstFTy =
1828 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1829 CallingConv SrcCC = SrcFTy->getCallConv();
1830 CallingConv DstCC = DstFTy->getCallConv();
1831 if (SrcCC == DstCC)
1832 return;
1833
1834 // We have a calling convention cast. Check if the source is a pointer to a
1835 // known, specific function that has already been defined.
1836 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1837 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1838 if (UO->getOpcode() == UO_AddrOf)
1839 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1840 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1841 if (!DRE)
1842 return;
1843 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Reid Kleckner0b009e82017-01-31 19:37:45 +00001844 if (!FD)
Reid Kleckner9f497332016-05-10 21:00:03 +00001845 return;
1846
Reid Kleckner43be52a2016-05-11 17:43:13 +00001847 // Only warn if we are casting from the default convention to a non-default
1848 // convention. This can happen when the programmer forgot to apply the calling
Reid Kleckner0b009e82017-01-31 19:37:45 +00001849 // convention to the function declaration and then inserted this cast to
Reid Kleckner43be52a2016-05-11 17:43:13 +00001850 // satisfy the type system.
1851 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1852 FD->isVariadic(), FD->isCXXInstanceMember());
1853 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1854 return;
1855
Reid Kleckner9f497332016-05-10 21:00:03 +00001856 // Diagnose this cast, as it is probably bad.
1857 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1858 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1859 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1860 << SrcCCName << DstCCName << OpRange;
1861
1862 // The checks above are cheaper than checking if the diagnostic is enabled.
1863 // However, it's worth checking if the warning is enabled before we construct
1864 // a fixit.
1865 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1866 return;
1867
1868 // Try to suggest a fixit to change the calling convention of the function
1869 // whose address was taken. Try to use the latest macro for the convention.
1870 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1871 // to match the Windows header declarations.
Reid Kleckner0b009e82017-01-31 19:37:45 +00001872 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
Reid Kleckner9f497332016-05-10 21:00:03 +00001873 Preprocessor &PP = Self.getPreprocessor();
1874 SmallVector<TokenValue, 6> AttrTokens;
1875 SmallString<64> CCAttrText;
1876 llvm::raw_svector_ostream OS(CCAttrText);
1877 if (Self.getLangOpts().MicrosoftExt) {
1878 // __stdcall or __vectorcall
1879 OS << "__" << DstCCName;
1880 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1881 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1882 ? TokenValue(II->getTokenID())
1883 : TokenValue(II));
1884 } else {
1885 // __attribute__((stdcall)) or __attribute__((vectorcall))
1886 OS << "__attribute__((" << DstCCName << "))";
1887 AttrTokens.push_back(tok::kw___attribute);
1888 AttrTokens.push_back(tok::l_paren);
1889 AttrTokens.push_back(tok::l_paren);
1890 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1891 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1892 ? TokenValue(II->getTokenID())
1893 : TokenValue(II));
1894 AttrTokens.push_back(tok::r_paren);
1895 AttrTokens.push_back(tok::r_paren);
1896 }
1897 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1898 if (!AttrSpelling.empty())
1899 CCAttrText = AttrSpelling;
1900 OS << ' ';
1901 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1902 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1903}
1904
David Blaikie282ad872012-10-16 18:53:14 +00001905static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1906 const Expr *SrcExpr, QualType DestType,
1907 Sema &Self) {
1908 QualType SrcType = SrcExpr->getType();
1909
1910 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1911 // are not explicit design choices, but consistent with GCC's behavior.
1912 // Feel free to modify them if you've reason/evidence for an alternative.
1913 if (CStyle && SrcType->isIntegralType(Self.Context)
1914 && !SrcType->isBooleanType()
1915 && !SrcType->isEnumeralType()
1916 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001917 && Self.Context.getTypeSize(DestType) >
1918 Self.Context.getTypeSize(SrcType)) {
1919 // Separate between casts to void* and non-void* pointers.
1920 // Some APIs use (abuse) void* for something like a user context,
1921 // and often that value is an integer even if it isn't a pointer itself.
1922 // Having a separate warning flag allows users to control the warning
1923 // for their workflow.
1924 unsigned Diag = DestType->isVoidPointerType() ?
1925 diag::warn_int_to_void_pointer_cast
1926 : diag::warn_int_to_pointer_cast;
1927 Self.Diag(Loc, Diag) << SrcType << DestType;
1928 }
David Blaikie282ad872012-10-16 18:53:14 +00001929}
1930
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001931static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1932 ExprResult &Result) {
1933 // We can only fix an overloaded reinterpret_cast if
1934 // - it is a template with explicit arguments that resolves to an lvalue
1935 // unambiguously, or
1936 // - it is the only function in an overload set that may have its address
1937 // taken.
1938
1939 Expr *E = Result.get();
1940 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1941 // like it?
1942 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1943 Result,
1944 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1945 ) &&
1946 Result.isUsable())
1947 return true;
1948
George Burgess IVbeca4a32016-06-08 00:34:22 +00001949 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1950 // preserves Result.
1951 Result = E;
George Burgess IV1dbfa852017-05-09 04:06:24 +00001952 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1953 Result, /*DoFunctionPointerConversion=*/true))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001954 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00001955 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001956}
1957
Yaxun Liu99a9f752018-07-20 11:32:51 +00001958static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1959 return SrcType->isPointerType() && DestType->isPointerType() &&
1960 SrcType->getAs<PointerType>()->getPointeeType().getAddressSpace() !=
1961 DestType->getAs<PointerType>()->getPointeeType().getAddressSpace();
1962}
1963
John Wiegley01296292011-04-08 18:41:53 +00001964static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001965 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001966 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001967 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001968 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001969 bool IsLValueCast = false;
1970
Sebastian Redl9f831db2009-07-25 15:41:38 +00001971 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001972 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001973
1974 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001975 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001976 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001977 ExprResult FixedExpr = SrcExpr;
1978 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001979 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001980
1981 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1982 SrcExpr = FixedExpr;
1983 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001984 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001985
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001986 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001987 if (!SrcExpr.get()->isGLValue()) {
1988 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1989 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001990 msg = diag::err_bad_cxx_cast_rvalue;
1991 return TC_NotApplicable;
1992 }
1993
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001994 if (!CStyle) {
1995 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1996 /*isDereference=*/false, OpRange);
1997 }
1998
Sebastian Redl9f831db2009-07-25 15:41:38 +00001999 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2000 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2001 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002002
Craig Topperc3ec1492014-05-26 06:22:03 +00002003 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002004 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00002005 case OK_Ordinary:
2006 break;
Richard Smithb8c0f552016-12-09 18:49:13 +00002007 case OK_BitField:
2008 msg = diag::err_bad_cxx_cast_bitfield;
2009 return TC_NotApplicable;
2010 // FIXME: Use a specific diagnostic for the rest of these cases.
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002011 case OK_VectorComponent: inappropriate = "vector element"; break;
2012 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00002013 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
2014 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002015 }
2016 if (inappropriate) {
2017 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2018 << inappropriate << DestType
2019 << OpRange << SrcExpr.get()->getSourceRange();
2020 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002021 return TC_NotApplicable;
2022 }
2023
Sebastian Redl9f831db2009-07-25 15:41:38 +00002024 // This code does this transformation for the checked types.
2025 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2026 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002027
Douglas Gregor51954272010-07-13 23:17:26 +00002028 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002029 }
2030
2031 // Canonicalize source for comparison.
2032 SrcType = Self.Context.getCanonicalType(SrcType);
2033
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002034 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2035 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002036 if (DestMemPtr && SrcMemPtr) {
2037 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2038 // can be explicitly converted to an rvalue of type "pointer to member
2039 // of Y of type T2" if T1 and T2 are both function types or both object
2040 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00002041 if (DestMemPtr->isMemberFunctionPointer() !=
2042 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00002043 return TC_NotApplicable;
2044
David Majnemer1cdd96d2014-01-17 09:01:00 +00002045 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2046 // We need to determine the inheritance model that the class will use if
2047 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00002048 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2049 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00002050 }
2051
Charles Davisebab1ed2010-08-16 05:30:44 +00002052 // Don't allow casting between member pointers of different sizes.
2053 if (Self.Context.getTypeSize(DestMemPtr) !=
2054 Self.Context.getTypeSize(SrcMemPtr)) {
2055 msg = diag::err_bad_cxx_cast_member_pointer_size;
2056 return TC_Failed;
2057 }
2058
Richard Smithf276e2d2018-07-10 23:04:35 +00002059 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2060 // constness.
2061 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2062 // we accept it.
2063 if (auto CACK =
2064 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2065 /*CheckObjCLifetime=*/CStyle))
2066 return getCastAwayConstnessCastKind(CACK, msg);
2067
Sebastian Redl9f831db2009-07-25 15:41:38 +00002068 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00002069 assert(!IsLValueCast);
2070 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002071 return TC_Success;
2072 }
2073
2074 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00002075 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002076 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2077 // type large enough to hold it. A value of std::nullptr_t can be
2078 // converted to an integral type; the conversion has the same meaning
2079 // and validity as a conversion of (void*)0 to the integral type.
2080 if (Self.Context.getTypeSize(SrcType) >
2081 Self.Context.getTypeSize(DestType)) {
2082 msg = diag::err_bad_reinterpret_cast_small_int;
2083 return TC_Failed;
2084 }
John McCalle3027922010-08-25 11:45:40 +00002085 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002086 return TC_Success;
2087 }
2088
John McCall1c78f082015-07-23 23:54:07 +00002089 // Allow reinterpret_casts between vectors of the same size and
2090 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00002091 bool destIsVector = DestType->isVectorType();
2092 bool srcIsVector = SrcType->isVectorType();
2093 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00002094 // The non-vector type, if any, must have integral type. This is
2095 // the same rule that C vector casts use; note, however, that enum
2096 // types are not integral in C++.
2097 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2098 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002099 return TC_NotApplicable;
2100
John McCall1c78f082015-07-23 23:54:07 +00002101 // The size we want to consider is eltCount * eltSize.
2102 // That's exactly what the lax-conversion rules will check.
2103 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002104 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002105 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002106 }
John McCall1c78f082015-07-23 23:54:07 +00002107
2108 // Otherwise, pick a reasonable diagnostic.
2109 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002110 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002111 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002112 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2113 else
2114 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2115
2116 return TC_Failed;
2117 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002118
2119 if (SrcType == DestType) {
2120 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2121 // restrictions, a cast to the same type is allowed so long as it does not
2122 // cast away constness. In C++98, the intent was not entirely clear here,
2123 // since all other paragraphs explicitly forbid casts to the same type.
2124 // C++11 clarifies this case with p2.
2125 //
2126 // The only allowed types are: integral, enumeration, pointer, or
2127 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2128 Kind = CK_NoOp;
2129 TryCastResult Result = TC_NotApplicable;
2130 if (SrcType->isIntegralOrEnumerationType() ||
2131 SrcType->isAnyPointerType() ||
2132 SrcType->isMemberPointerType() ||
2133 SrcType->isBlockPointerType()) {
2134 Result = TC_Success;
2135 }
2136 return Result;
2137 }
2138
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002139 bool destIsPtr = DestType->isAnyPointerType() ||
2140 DestType->isBlockPointerType();
2141 bool srcIsPtr = SrcType->isAnyPointerType() ||
2142 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002143 if (!destIsPtr && !srcIsPtr) {
2144 // Except for std::nullptr_t->integer and lvalue->reference, which are
2145 // handled above, at least one of the two arguments must be a pointer.
2146 return TC_NotApplicable;
2147 }
2148
Douglas Gregor6972a622010-06-16 00:35:25 +00002149 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002150 assert(srcIsPtr && "One type must be a pointer");
2151 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002152 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002153 // integral type size doesn't matter (except we don't allow bool).
2154 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2155 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002156 if ((Self.Context.getTypeSize(SrcType) >
2157 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002158 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002159 msg = diag::err_bad_reinterpret_cast_small_int;
2160 return TC_Failed;
2161 }
John McCalle3027922010-08-25 11:45:40 +00002162 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002163 return TC_Success;
2164 }
2165
Douglas Gregorb90df602010-06-16 00:17:44 +00002166 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002167 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002168 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2169 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002170 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2171 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002172 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2173 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002174 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002175 return TC_Success;
2176 }
2177
2178 if (!destIsPtr || !srcIsPtr) {
2179 // With the valid non-pointer conversions out of the way, we can be even
2180 // more stringent.
2181 return TC_NotApplicable;
2182 }
2183
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002184 // Cannot convert between block pointers and Objective-C object pointers.
2185 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2186 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2187 return TC_NotApplicable;
2188
Richard Smithf276e2d2018-07-10 23:04:35 +00002189 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2190 // The C-style cast operator can.
2191 TryCastResult SuccessResult = TC_Success;
2192 if (auto CACK =
2193 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2194 /*CheckObjCLifetime=*/CStyle))
2195 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2196
John McCall9320b872011-09-09 05:25:32 +00002197 if (IsLValueCast) {
2198 Kind = CK_LValueBitCast;
2199 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002200 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002201 } else if (DestType->isBlockPointerType()) {
2202 if (!SrcType->isBlockPointerType()) {
2203 Kind = CK_AnyPointerToBlockPointerCast;
2204 } else {
2205 Kind = CK_BitCast;
2206 }
Yaxun Liu99a9f752018-07-20 11:32:51 +00002207 } else if (IsAddressSpaceConversion(SrcType, DestType)) {
2208 Kind = CK_AddressSpaceConversion;
John McCall9320b872011-09-09 05:25:32 +00002209 } else {
2210 Kind = CK_BitCast;
2211 }
2212
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002213 // Any pointer can be cast to an Objective-C pointer type with a C-style
2214 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002215 if (CStyle && DestType->isObjCObjectPointerType()) {
Richard Smithf276e2d2018-07-10 23:04:35 +00002216 return SuccessResult;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002217 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002218 if (CStyle)
2219 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002220
2221 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2222
Sebastian Redl9f831db2009-07-25 15:41:38 +00002223 // Not casting away constness, so the only remaining check is for compatible
2224 // pointer categories.
2225
2226 if (SrcType->isFunctionPointerType()) {
2227 if (DestType->isFunctionPointerType()) {
2228 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2229 // a pointer to a function of a different type.
Richard Smithf276e2d2018-07-10 23:04:35 +00002230 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002231 }
2232
2233 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2234 // an object type or vice versa is conditionally-supported.
2235 // Compilers support it in C++03 too, though, because it's necessary for
2236 // casting the return value of dlsym() and GetProcAddress().
2237 // FIXME: Conditionally-supported behavior should be configurable in the
2238 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002239 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002240 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002241 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2242 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002243 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002244 }
2245
2246 if (DestType->isFunctionPointerType()) {
2247 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002248 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002249 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002250 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2251 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002252 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002253 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002254
Sebastian Redl9f831db2009-07-25 15:41:38 +00002255 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2256 // a pointer to an object of different type.
2257 // Void pointers are not specified, but supported by every compiler out there.
2258 // So we finish by allowing everything that remains - it's got to be two
2259 // object pointers.
Richard Smithf276e2d2018-07-10 23:04:35 +00002260 return SuccessResult;
2261}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002262
Sebastian Redld74dd492012-02-12 18:41:05 +00002263void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2264 bool ListInitialization) {
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002265 assert(Self.getLangOpts().CPlusPlus);
2266
John McCall9776e432011-10-06 23:25:11 +00002267 // Handle placeholders.
2268 if (isPlaceholder()) {
2269 // C-style casts can resolve __unknown_any types.
2270 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2271 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2272 SrcExpr.get(), Kind,
2273 ValueKind, BasePath);
2274 return;
2275 }
John McCallb50451a2011-10-05 07:41:44 +00002276
John McCall9776e432011-10-06 23:25:11 +00002277 checkNonOverloadPlaceholders();
2278 if (SrcExpr.isInvalid())
2279 return;
John McCalla072f5d2011-10-17 17:42:19 +00002280 }
John McCall9776e432011-10-06 23:25:11 +00002281
2282 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002283 // This test is outside everything else because it's the only case where
2284 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002285 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002286 Kind = CK_ToVoid;
2287
John McCall9776e432011-10-06 23:25:11 +00002288 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002289 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2290 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002291 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002292 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002293 if (SrcExpr.isInvalid())
2294 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002295 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002296
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002297 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002298 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002299 }
2300
Sebastian Redl9f831db2009-07-25 15:41:38 +00002301 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002302 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2303 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002304 assert(Kind == CK_Dependent);
2305 return;
John McCall8cb679e2010-11-15 09:13:47 +00002306 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002307
John McCall50a2c2c2011-10-11 23:14:30 +00002308 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2309 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002310 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002311 if (SrcExpr.isInvalid())
2312 return;
John Wiegley01296292011-04-08 18:41:53 +00002313 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002314
John McCall3aef3d82011-04-10 19:13:55 +00002315 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002316 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002317 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002318 && (SrcExpr.get()->getType()->isIntegerType()
2319 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002320 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002321 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002322 return;
John McCall3aef3d82011-04-10 19:13:55 +00002323 }
2324
Sebastian Redl9f831db2009-07-25 15:41:38 +00002325 // C++ [expr.cast]p5: The conversions performed by
2326 // - a const_cast,
2327 // - a static_cast,
2328 // - a static_cast followed by a const_cast,
2329 // - a reinterpret_cast, or
2330 // - a reinterpret_cast followed by a const_cast,
2331 // can be performed using the cast notation of explicit type conversion.
2332 // [...] If a conversion can be interpreted in more than one of the ways
2333 // listed above, the interpretation that appears first in the list is used,
2334 // even if a cast resulting from that interpretation is ill-formed.
2335 // In plain language, this means trying a const_cast ...
2336 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002337 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002338 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002339 if (SrcExpr.isInvalid())
2340 return;
Richard Smithf276e2d2018-07-10 23:04:35 +00002341 if (isValidCast(tcr))
John McCalle3027922010-08-25 11:45:40 +00002342 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002343
John McCall31168b02011-06-15 23:02:42 +00002344 Sema::CheckedConversionKind CCK
2345 = FunctionalStyle? Sema::CCK_FunctionalCast
2346 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002347 if (tcr == TC_NotApplicable) {
2348 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002349 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002350 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002351 if (SrcExpr.isInvalid())
2352 return;
2353
Sebastian Redl9f831db2009-07-25 15:41:38 +00002354 if (tcr == TC_NotApplicable) {
2355 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002356 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2357 OpRange, msg, Kind);
2358 if (SrcExpr.isInvalid())
2359 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002360 }
2361 }
2362
Brian Kelley11352a82017-03-29 18:09:02 +00002363 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
Richard Smithf276e2d2018-07-10 23:04:35 +00002364 isValidCast(tcr))
Brian Kelley11352a82017-03-29 18:09:02 +00002365 checkObjCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002366
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002367 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002368 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002369 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002370 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2371 DestType,
2372 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002373 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002374 if (Fn) {
2375 // If DestType is a function type (not to be confused with the function
2376 // pointer type), it will be possible to resolve the function address,
2377 // but the type cast should be considered as failure.
2378 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2379 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2380 << OE->getName() << DestType << OpRange
2381 << OE->getQualifierLoc().getSourceRange();
2382 Self.NoteAllOverloadCandidates(SrcExpr.get());
2383 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002384 } else {
John McCallb50451a2011-10-05 07:41:44 +00002385 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002386 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002387 }
2388 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002389
Richard Smithf276e2d2018-07-10 23:04:35 +00002390 if (isValidCast(tcr)) {
2391 if (Kind == CK_BitCast)
2392 checkCastAlign();
2393 } else {
John McCallb50451a2011-10-05 07:41:44 +00002394 SrcExpr = ExprError();
Richard Smithf276e2d2018-07-10 23:04:35 +00002395 }
John McCallb50451a2011-10-05 07:41:44 +00002396}
2397
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002398/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2399/// non-matching type. Such as enum function call to int, int call to
2400/// pointer; etc. Cast to 'void' is an exception.
2401static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2402 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002403 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2404 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002405 return;
2406
2407 if (!isa<CallExpr>(SrcExpr.get()))
2408 return;
2409
2410 QualType SrcType = SrcExpr.get()->getType();
2411 if (DestType.getUnqualifiedType()->isVoidType())
2412 return;
2413 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2414 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2415 return;
2416 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2417 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2418 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2419 return;
2420 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2421 return;
2422 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2423 return;
2424 if (SrcType->isComplexType() && DestType->isComplexType())
2425 return;
2426 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2427 return;
2428
2429 Self.Diag(SrcExpr.get()->getExprLoc(),
2430 diag::warn_bad_function_cast)
2431 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2432}
2433
John McCall9776e432011-10-06 23:25:11 +00002434/// Check the semantics of a C-style cast operation, in C.
2435void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002436 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002437
John McCall4124c492011-10-17 18:40:02 +00002438 // C-style casts can resolve __unknown_any types.
2439 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2440 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2441 SrcExpr.get(), Kind,
2442 ValueKind, BasePath);
2443 return;
2444 }
John McCall9776e432011-10-06 23:25:11 +00002445
2446 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2447 // type needs to be scalar.
2448 if (DestType->isVoidType()) {
2449 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002450 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002451 if (SrcExpr.isInvalid())
2452 return;
2453
2454 // Cast to void allows any expr type.
2455 Kind = CK_ToVoid;
2456 return;
2457 }
2458
George Burgess IV5f21c712015-10-12 19:57:04 +00002459 // Overloads are allowed with C extensions, so we need to support them.
2460 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2461 DeclAccessPair DAP;
2462 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2463 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2464 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2465 else
2466 return;
2467 assert(SrcExpr.isUsable());
2468 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002469 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002470 if (SrcExpr.isInvalid())
2471 return;
2472 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002473
John McCall4124c492011-10-17 18:40:02 +00002474 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002475
Joey Gouly8fc32f02014-01-14 12:47:29 +00002476 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2477 // address space B is illegal.
2478 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2479 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002480 const PointerType *DestPtr = DestType->getAs<PointerType>();
2481 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002482 Self.Diag(OpRange.getBegin(),
2483 diag::err_typecheck_incompatible_address_space)
2484 << SrcType << DestType << Sema::AA_Casting
2485 << SrcExpr.get()->getSourceRange();
2486 SrcExpr = ExprError();
2487 return;
2488 }
2489 }
2490
John McCall9776e432011-10-06 23:25:11 +00002491 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2492 diag::err_typecheck_cast_to_incomplete)) {
2493 SrcExpr = ExprError();
2494 return;
2495 }
2496
2497 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2498 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2499
2500 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2501 // GCC struct/union extension: allow cast to self.
2502 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2503 << DestType << SrcExpr.get()->getSourceRange();
2504 Kind = CK_NoOp;
2505 return;
2506 }
2507
2508 // GCC's cast to union extension.
2509 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2510 RecordDecl *RD = DestRecordTy->getDecl();
John McCallf1ef7962017-08-15 21:42:47 +00002511 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2512 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2513 << SrcExpr.get()->getSourceRange();
2514 Kind = CK_ToUnion;
2515 return;
2516 } else {
John McCall9776e432011-10-06 23:25:11 +00002517 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2518 << SrcType << SrcExpr.get()->getSourceRange();
2519 SrcExpr = ExprError();
2520 return;
2521 }
John McCall9776e432011-10-06 23:25:11 +00002522 }
2523
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002524 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2525 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2526 llvm::APSInt CastInt;
2527 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2528 if (0 == CastInt) {
2529 Kind = CK_ZeroToOCLEvent;
2530 return;
2531 }
2532 Self.Diag(OpRange.getBegin(),
Richard Smithf8812672016-12-02 22:38:31 +00002533 diag::err_opencl_cast_non_zero_to_event_t)
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002534 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2535 SrcExpr = ExprError();
2536 return;
2537 }
2538 }
2539
John McCall9776e432011-10-06 23:25:11 +00002540 // Reject any other conversions to non-scalar types.
2541 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2542 << DestType << SrcExpr.get()->getSourceRange();
2543 SrcExpr = ExprError();
2544 return;
2545 }
2546
2547 // The type we're casting to is known to be a scalar or vector.
2548
2549 // Require the operand to be a scalar or vector.
2550 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2551 Self.Diag(SrcExpr.get()->getExprLoc(),
2552 diag::err_typecheck_expect_scalar_operand)
2553 << SrcType << SrcExpr.get()->getSourceRange();
2554 SrcExpr = ExprError();
2555 return;
2556 }
2557
2558 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002559 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002560 return;
2561 }
2562
2563 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2564 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2565 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2566 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002567 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002568 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2569 SrcExpr = ExprError();
2570 }
2571 return;
2572 }
2573
2574 if (SrcType->isVectorType()) {
2575 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2576 SrcExpr = ExprError();
2577 return;
2578 }
2579
2580 // The source and target types are both scalars, i.e.
2581 // - arithmetic types (fundamental, enum, and complex)
2582 // - all kinds of pointers
2583 // Note that member pointers were filtered out with C++, above.
2584
2585 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2586 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2587 SrcExpr = ExprError();
2588 return;
2589 }
2590
2591 // If either type is a pointer, the other type has to be either an
2592 // integer or a pointer.
2593 if (!DestType->isArithmeticType()) {
2594 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2595 Self.Diag(SrcExpr.get()->getExprLoc(),
2596 diag::err_cast_pointer_from_non_pointer_int)
2597 << SrcType << SrcExpr.get()->getSourceRange();
2598 SrcExpr = ExprError();
2599 return;
2600 }
David Blaikie282ad872012-10-16 18:53:14 +00002601 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2602 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002603 } else if (!SrcType->isArithmeticType()) {
2604 if (!DestType->isIntegralType(Self.Context) &&
2605 DestType->isArithmeticType()) {
2606 Self.Diag(SrcExpr.get()->getLocStart(),
2607 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002608 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002609 SrcExpr = ExprError();
2610 return;
2611 }
2612 }
2613
Yaxun Liu5b746652016-12-18 05:18:55 +00002614 if (Self.getLangOpts().OpenCL &&
2615 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
Joey Goulydd7f4562013-01-23 11:56:20 +00002616 if (DestType->isHalfType()) {
2617 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2618 << DestType << SrcExpr.get()->getSourceRange();
2619 SrcExpr = ExprError();
2620 return;
2621 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002622 }
2623
John McCall9776e432011-10-06 23:25:11 +00002624 // ARC imposes extra restrictions on casts.
Brian Kelley11352a82017-03-29 18:09:02 +00002625 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2626 checkObjCConversion(Sema::CCK_CStyleCast);
John McCall9776e432011-10-06 23:25:11 +00002627 if (SrcExpr.isInvalid())
2628 return;
Brian Kelley11352a82017-03-29 18:09:02 +00002629
2630 const PointerType *CastPtr = DestType->getAs<PointerType>();
2631 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
John McCall9776e432011-10-06 23:25:11 +00002632 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2633 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2634 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2635 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2636 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2637 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2638 Self.Diag(SrcExpr.get()->getLocStart(),
2639 diag::err_typecheck_incompatible_ownership)
2640 << SrcType << DestType << Sema::AA_Casting
2641 << SrcExpr.get()->getSourceRange();
2642 return;
2643 }
2644 }
2645 }
2646 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2647 Self.Diag(SrcExpr.get()->getLocStart(),
2648 diag::err_arc_convesion_of_weak_unavailable)
2649 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2650 SrcExpr = ExprError();
2651 return;
2652 }
2653 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002654
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002655 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002656 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002657 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002658 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2659 if (SrcExpr.isInvalid())
2660 return;
2661
2662 if (Kind == CK_BitCast)
2663 checkCastAlign();
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002664}
Roman Divackyd5178012014-11-21 21:03:10 +00002665
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002666/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2667/// const, volatile or both.
2668static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2669 QualType DestType) {
2670 if (SrcExpr.isInvalid())
2671 return;
2672
2673 QualType SrcType = SrcExpr.get()->getType();
2674 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2675 DestType->isLValueReferenceType()))
2676 return;
2677
Roman Divackyd5178012014-11-21 21:03:10 +00002678 QualType TheOffendingSrcType, TheOffendingDestType;
2679 Qualifiers CastAwayQualifiers;
Richard Smithf276e2d2018-07-10 23:04:35 +00002680 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
2681 &TheOffendingSrcType, &TheOffendingDestType,
2682 &CastAwayQualifiers) !=
2683 CastAwayConstnessKind::CACK_Similar)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002684 return;
2685
Richard Smithf276e2d2018-07-10 23:04:35 +00002686 // FIXME: 'restrict' is not properly handled here.
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002687 int qualifiers = -1;
2688 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2689 qualifiers = 0;
2690 } else if (CastAwayQualifiers.hasConst()) {
2691 qualifiers = 1;
2692 } else if (CastAwayQualifiers.hasVolatile()) {
2693 qualifiers = 2;
Roman Divackyd5178012014-11-21 21:03:10 +00002694 }
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002695 // This is a variant of int **x; const int **y = (const int **)x;
2696 if (qualifiers == -1)
2697 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
2698 << SrcType << DestType;
2699 else
2700 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
2701 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
John McCall9776e432011-10-06 23:25:11 +00002702}
2703
2704ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2705 TypeSourceInfo *CastTypeInfo,
2706 SourceLocation RPLoc,
2707 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002708 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2709 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2710 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2711
David Blaikiebbafb8a2012-03-11 07:00:24 +00002712 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002713 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2714 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002715 } else {
2716 Op.CheckCStyleCast();
2717 }
2718
John McCallb50451a2011-10-05 07:41:44 +00002719 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002720 return ExprError();
2721
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002722 // -Wcast-qual
2723 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2724
John McCall4124c492011-10-17 18:40:02 +00002725 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002726 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002727 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002728}
2729
2730ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
Richard Smith60437622017-02-09 19:17:44 +00002731 QualType Type,
John McCallb50451a2011-10-05 07:41:44 +00002732 SourceLocation LPLoc,
2733 Expr *CastExpr,
2734 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002735 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
Richard Smith60437622017-02-09 19:17:44 +00002736 CastOperation Op(*this, Type, CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002737 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2738 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2739
Sebastian Redl2b80af42012-02-13 19:55:43 +00002740 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002741 if (Op.SrcExpr.isInvalid())
2742 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002743
2744 auto *SubExpr = Op.SrcExpr.get();
2745 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2746 SubExpr = BindExpr->getSubExpr();
2747 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002748 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002749
John McCall4124c492011-10-17 18:40:02 +00002750 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002751 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002752 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002753}