blob: ad6348685b64e6ac8a989cb0ddfa15c712d0080e [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.
36 TC_Failed ///< The cast method is appropriate, but failed. A
37 ///< diagnostic has been emitted.
38};
39
40enum CastType {
41 CT_Const, ///< const_cast
42 CT_Static, ///< static_cast
43 CT_Reinterpret, ///< reinterpret_cast
44 CT_Dynamic, ///< dynamic_cast
45 CT_CStyle, ///< (Type)expr
46 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000047};
48
John McCallb50451a2011-10-05 07:41:44 +000049namespace {
50 struct CastOperation {
51 CastOperation(Sema &S, QualType destType, ExprResult src)
52 : Self(S), SrcExpr(src), DestType(destType),
53 ResultType(destType.getNonLValueExprType(S.Context)),
54 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000055 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000056
57 if (const BuiltinType *placeholder =
58 src.get()->getType()->getAsPlaceholderType()) {
59 PlaceholderKind = placeholder->getKind();
60 } else {
61 PlaceholderKind = (BuiltinType::Kind) 0;
62 }
63 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000064
John McCallb50451a2011-10-05 07:41:44 +000065 Sema &Self;
66 ExprResult SrcExpr;
67 QualType DestType;
68 QualType ResultType;
69 ExprValueKind ValueKind;
70 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000071 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000072 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000073 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000074
John McCallb50451a2011-10-05 07:41:44 +000075 SourceRange OpRange;
76 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000077
John McCall9776e432011-10-06 23:25:11 +000078 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000079 void CheckConstCast();
80 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000081 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000082 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000083 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000084 void CheckCStyleCast();
85
John McCall4124c492011-10-17 18:40:02 +000086 /// Complete an apparently-successful cast operation that yields
87 /// the given expression.
88 ExprResult complete(CastExpr *castExpr) {
89 // If this is an unbridged cast, wrap the result in an implicit
90 // cast that yields the unbridged-cast placeholder type.
91 if (IsARCUnbridgedCast) {
92 castExpr = ImplicitCastExpr::Create(Self.Context,
93 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000094 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +000095 castExpr->getValueKind());
96 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000097 return castExpr;
John McCall4124c492011-10-17 18:40:02 +000098 }
99
John McCall9776e432011-10-06 23:25:11 +0000100 // Internal convenience methods.
101
102 /// Try to handle the given placeholder expression kind. Return
103 /// true if the source expression has the appropriate placeholder
104 /// kind. A placeholder can only be claimed once.
105 bool claimPlaceholder(BuiltinType::Kind K) {
106 if (PlaceholderKind != K) return false;
107
108 PlaceholderKind = (BuiltinType::Kind) 0;
109 return true;
110 }
111
112 bool isPlaceholder() const {
113 return PlaceholderKind != 0;
114 }
115 bool isPlaceholder(BuiltinType::Kind K) const {
116 return PlaceholderKind == K;
117 }
John McCallb50451a2011-10-05 07:41:44 +0000118
119 void checkCastAlign() {
120 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
121 }
122
Brian Kelley11352a82017-03-29 18:09:02 +0000123 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
124 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
John McCall4124c492011-10-17 18:40:02 +0000125
John McCallb50451a2011-10-05 07:41:44 +0000126 Expr *src = SrcExpr.get();
Brian Kelley11352a82017-03-29 18:09:02 +0000127 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
128 Sema::ACR_unbridged)
John McCall4124c492011-10-17 18:40:02 +0000129 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000130 SrcExpr = src;
131 }
John McCall9776e432011-10-06 23:25:11 +0000132
133 /// Check for and handle non-overload placeholder expressions.
134 void checkNonOverloadPlaceholders() {
135 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
136 return;
137
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000138 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000139 if (SrcExpr.isInvalid())
140 return;
141 PlaceholderKind = (BuiltinType::Kind) 0;
142 }
John McCallb50451a2011-10-05 07:41:44 +0000143 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000144}
Sebastian Redl842ef522008-11-08 13:00:26 +0000145
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000146static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
147 QualType DestType);
148
Sebastian Redl9f831db2009-07-25 15:41:38 +0000149// The Try functions attempt a specific way of casting. If they succeed, they
150// return TC_Success. If their way of casting is not appropriate for the given
151// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
152// to emit if no other way succeeds. If their way of casting is appropriate but
153// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
154// they emit a specialized diagnostic.
155// All diagnostics returned by these functions must expect the same three
156// arguments:
157// %0: Cast Type (a value from the CastType enumeration)
158// %1: Source Type
159// %2: Destination Type
160static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000161 QualType DestType, bool CStyle,
162 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000163 CXXCastPath &BasePath,
164 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000165static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000166 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000167 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000168 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000169 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000170 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000171static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
172 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000173 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000174 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000175 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000176 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000177static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
178 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000179 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000180 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000181 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000182 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000183 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000184static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000185 QualType SrcType,
186 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000187 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000188 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000189 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000190 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000191
John Wiegley01296292011-04-08 18:41:53 +0000192static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000193 QualType DestType,
194 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000195 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000196 unsigned &msg, CastKind &Kind,
197 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000198static TryCastResult TryStaticCast(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 CXXCastPath &BasePath,
204 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000205static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
206 QualType DestType, bool CStyle,
207 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000208static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000209 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000210 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000211 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000212 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000213
Douglas Gregorb491ed32011-02-19 21:32:49 +0000214
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000216ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000217Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000218 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000219 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000220 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000221 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000222
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000223 assert(!D.isInvalidType());
224
225 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
226 if (D.isInvalidType())
227 return ExprError();
228
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000230 // Check that there are no default arguments (C++ only).
231 CheckExtraCXXDefaultArguments(D);
232 }
233
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000234 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000235 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
236 SourceRange(LParenLoc, RParenLoc));
237}
238
John McCalldadc5752010-08-24 06:29:42 +0000239ExprResult
John McCalld377e042010-01-15 19:13:16 +0000240Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000241 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000242 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000243 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000244 QualType DestType = DestTInfo->getType();
245
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000246 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000247 bool TypeDependent =
248 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000249
John McCallb50451a2011-10-05 07:41:44 +0000250 CastOperation Op(*this, DestType, E);
251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000253
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000254 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000255 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000256
257 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000258 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000259 Op.CheckConstCast();
260 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000261 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000262 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000263 }
John McCall4124c492011-10-17 18:40:02 +0000264 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000265 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000266 OpLoc, Parens.getEnd(),
267 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000268
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000269 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000270 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000271 Op.CheckDynamicCast();
272 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000273 return ExprError();
274 }
John McCall4124c492011-10-17 18:40:02 +0000275 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000276 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000277 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000278 OpLoc, Parens.getEnd(),
279 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000280 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000281 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000282 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000283 Op.CheckReinterpretCast();
284 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000285 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000286 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000287 }
John McCall4124c492011-10-17 18:40:02 +0000288 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000289 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000290 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000291 Parens.getEnd(),
292 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000293 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000294 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000295 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000296 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000297 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000298 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000299 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000300 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000301
John McCall4124c492011-10-17 18:40:02 +0000302 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000303 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000304 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000305 OpLoc, Parens.getEnd(),
306 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000307 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000308 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000309}
310
John McCall909acf82011-02-14 18:34:10 +0000311/// Try to diagnose a failed overloaded cast. Returns true if
312/// diagnostics were emitted.
313static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
314 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000315 QualType destType,
316 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000317 switch (CT) {
318 // These cast kinds don't consider user-defined conversions.
319 case CT_Const:
320 case CT_Reinterpret:
321 case CT_Dynamic:
322 return false;
323
324 // These do.
325 case CT_Static:
326 case CT_CStyle:
327 case CT_Functional:
328 break;
329 }
330
331 QualType srcType = src->getType();
332 if (!destType->isRecordType() && !srcType->isRecordType())
333 return false;
334
335 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
336 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000337 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000338 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000339 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000340 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000341 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000342 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000343
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000344 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000345 switch (sequence.getFailureKind()) {
346 default: return false;
347
348 case InitializationSequence::FK_ConstructorOverloadFailed:
349 case InitializationSequence::FK_UserConversionOverloadFailed:
350 break;
351 }
352
353 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
354
355 unsigned msg = 0;
356 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
357
358 switch (sequence.getFailedOverloadResult()) {
359 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000360 case OR_No_Viable_Function:
361 if (candidates.empty())
362 msg = diag::err_ovl_no_conversion_in_cast;
363 else
364 msg = diag::err_ovl_no_viable_conversion_in_cast;
365 howManyCandidates = OCD_AllCandidates;
366 break;
367
368 case OR_Ambiguous:
369 msg = diag::err_ovl_ambiguous_conversion_in_cast;
370 howManyCandidates = OCD_ViableCandidates;
371 break;
372
373 case OR_Deleted:
374 msg = diag::err_ovl_deleted_conversion_in_cast;
375 howManyCandidates = OCD_ViableCandidates;
376 break;
377 }
378
379 S.Diag(range.getBegin(), msg)
380 << CT << srcType << destType
381 << range << src->getSourceRange();
382
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000383 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000384
385 return true;
386}
387
388/// Diagnose a failed cast.
389static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000390 SourceRange opRange, Expr *src, QualType destType,
391 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000392 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000393 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
394 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000395 return;
396
397 S.Diag(opRange.getBegin(), msg) << castType
398 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000399
400 // Detect if both types are (ptr to) class, and note any incompleteness.
401 int DifferentPtrness = 0;
402 QualType From = destType;
403 if (auto Ptr = From->getAs<PointerType>()) {
404 From = Ptr->getPointeeType();
405 DifferentPtrness++;
406 }
407 QualType To = src->getType();
408 if (auto Ptr = To->getAs<PointerType>()) {
409 To = Ptr->getPointeeType();
410 DifferentPtrness--;
411 }
412 if (!DifferentPtrness) {
413 auto RecFrom = From->getAs<RecordType>();
414 auto RecTo = To->getAs<RecordType>();
415 if (RecFrom && RecTo) {
416 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
417 if (!DeclFrom->isCompleteDefinition())
418 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
419 << DeclFrom->getDeclName();
420 auto DeclTo = RecTo->getAsCXXRecordDecl();
421 if (!DeclTo->isCompleteDefinition())
422 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
423 << DeclTo->getDeclName();
424 }
425 }
John McCall909acf82011-02-14 18:34:10 +0000426}
427
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000428/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
429/// this removes one level of indirection from both types, provided that they're
430/// the same kind of pointer (plain or to-member). Unlike the Sema function,
431/// this one doesn't care if the two pointers-to-member don't point into the
432/// same class. This is because CastsAwayConstness doesn't care.
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000433/// And additionally, it handles C++ references. If both the types are
434/// references, then their pointee types are returned,
435/// else if only one of them is reference, it's pointee type is returned,
436/// and the other type is returned as-is.
Dan Gohman28ade552010-07-26 21:25:24 +0000437static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000438 const PointerType *T1PtrType = T1->getAs<PointerType>(),
439 *T2PtrType = T2->getAs<PointerType>();
440 if (T1PtrType && T2PtrType) {
441 T1 = T1PtrType->getPointeeType();
442 T2 = T2PtrType->getPointeeType();
443 return true;
444 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000445 const ObjCObjectPointerType *T1ObjCPtrType =
446 T1->getAs<ObjCObjectPointerType>(),
447 *T2ObjCPtrType =
448 T2->getAs<ObjCObjectPointerType>();
449 if (T1ObjCPtrType) {
450 if (T2ObjCPtrType) {
451 T1 = T1ObjCPtrType->getPointeeType();
452 T2 = T2ObjCPtrType->getPointeeType();
453 return true;
454 }
455 else if (T2PtrType) {
456 T1 = T1ObjCPtrType->getPointeeType();
457 T2 = T2PtrType->getPointeeType();
458 return true;
459 }
460 }
461 else if (T2ObjCPtrType) {
462 if (T1PtrType) {
463 T2 = T2ObjCPtrType->getPointeeType();
464 T1 = T1PtrType->getPointeeType();
465 return true;
466 }
467 }
468
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000469 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
470 *T2MPType = T2->getAs<MemberPointerType>();
471 if (T1MPType && T2MPType) {
472 T1 = T1MPType->getPointeeType();
473 T2 = T2MPType->getPointeeType();
474 return true;
475 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000476
477 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
478 *T2BPType = T2->getAs<BlockPointerType>();
479 if (T1BPType && T2BPType) {
480 T1 = T1BPType->getPointeeType();
481 T2 = T2BPType->getPointeeType();
482 return true;
483 }
484
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000485 const LValueReferenceType *T1RefType = T1->getAs<LValueReferenceType>(),
486 *T2RefType = T2->getAs<LValueReferenceType>();
487 if (T1RefType && T2RefType) {
488 T1 = T1RefType->getPointeeType();
489 T2 = T2RefType->getPointeeType();
490 return true;
491 }
492
493 if (T1RefType) {
494 T1 = T1RefType->getPointeeType();
495 // T2 = T2;
496 return true;
497 }
498
499 if (T2RefType) {
500 // T1 = T1;
501 T2 = T2RefType->getPointeeType();
502 return true;
503 }
504
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000505 return false;
506}
507
Sebastian Redla5a77a62009-01-27 23:18:31 +0000508/// CastsAwayConstness - Check if the pointer conversion from SrcType to
509/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
510/// the cast checkers. Both arguments must denote pointer (possibly to member)
511/// types.
John McCall31168b02011-06-15 23:02:42 +0000512///
513/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
514///
515/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000516static bool
John McCall31168b02011-06-15 23:02:42 +0000517CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000518 bool CheckCVR, bool CheckObjCLifetime,
519 QualType *TheOffendingSrcType = nullptr,
520 QualType *TheOffendingDestType = nullptr,
521 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000522 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000523 // and we're not in ObjC mode, there's nothing to check.
John McCall31168b02011-06-15 23:02:42 +0000524 if (!CheckCVR && CheckObjCLifetime &&
John McCall460ce582015-10-22 18:38:17 +0000525 !Self.Context.getLangOpts().ObjC1)
John McCall31168b02011-06-15 23:02:42 +0000526 return false;
527
Sebastian Redla5a77a62009-01-27 23:18:31 +0000528 // Casting away constness is defined in C++ 5.2.11p8 with reference to
529 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
530 // the rules are non-trivial. So first we construct Tcv *...cv* as described
531 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000532 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000533 SrcType->isBlockPointerType() ||
534 DestType->isLValueReferenceType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000535 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000536 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000537 DestType->isBlockPointerType() ||
538 DestType->isLValueReferenceType()) &&
539 "Destination type is not pointer or pointer to member, or reference.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000540
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000541 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
542 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000543 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000544
Douglas Gregorb472e932011-04-15 17:59:54 +0000545 // Find the qualifiers. We only care about cvr-qualifiers for the
546 // purpose of this check, because other qualifiers (address spaces,
547 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000548 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
549 QualType PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000550 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000551 // Determine the relevant qualifiers at this level.
552 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000553 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000554 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Akira Hatanaka8d7bdf62017-08-11 00:06:49 +0000555
556 // We do not meaningfully track object const-ness of Objective-C object
557 // types. Remove const from the source type if either the source or
558 // the destination is an Objective-C object type.
559 if (UnwrappedSrcType->isObjCObjectType() ||
560 UnwrappedDestType->isObjCObjectType())
561 SrcQuals.removeConst();
562
John McCall31168b02011-06-15 23:02:42 +0000563 Qualifiers RetainedSrcQuals, RetainedDestQuals;
564 if (CheckCVR) {
565 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
566 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000567
568 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
569 TheOffendingDestType && CastAwayQualifiers) {
570 *TheOffendingSrcType = PrevUnwrappedSrcType;
571 *TheOffendingDestType = PrevUnwrappedDestType;
572 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
573 }
John McCall31168b02011-06-15 23:02:42 +0000574 }
575
576 if (CheckObjCLifetime &&
577 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
578 return true;
579
580 cv1.push_back(RetainedSrcQuals);
581 cv2.push_back(RetainedDestQuals);
Roman Divackyd5178012014-11-21 21:03:10 +0000582
583 PrevUnwrappedSrcType = UnwrappedSrcType;
584 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000585 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000586 if (cv1.empty())
587 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000588
589 // Construct void pointers with those qualifiers (in reverse order of
590 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000591 QualType SrcConstruct = Self.Context.VoidTy;
592 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000593 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000594 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
595 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000596 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000597 SrcConstruct
598 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
599 DestConstruct
600 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000601 }
602
603 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000604 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000605 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000606 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
607 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000608}
609
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000610/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
611/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
612/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000613void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000614 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000615 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000616 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000617 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000618 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
619 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000620
John McCallb50451a2011-10-05 07:41:44 +0000621 QualType OrigSrcType = SrcExpr.get()->getType();
622 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000623
624 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
625 // or "pointer to cv void".
626
627 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000628 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000629 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000630 if (DestPointer) {
631 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000632 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000633 DestPointee = DestReference->getPointeeType();
634 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000635 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000636 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000637 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000638 return;
639 }
640
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000641 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000642 if (DestPointee->isVoidType()) {
643 assert(DestPointer && "Reference to void is not possible");
644 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000645 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000646 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000647 DestRange)) {
648 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000649 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000650 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000651 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000652 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000653 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000654 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000655 return;
656 }
657
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000658 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
659 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000660 // an lvalue of a complete class type, [...]. If T is an rvalue reference
661 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000662 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000663 QualType SrcPointee;
664 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000665 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000666 SrcPointee = SrcPointer->getPointeeType();
667 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000668 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000669 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000670 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000671 return;
672 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000673 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000674 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000675 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000676 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000677 }
678 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000679 } else {
Richard Smith11330852014-07-08 17:25:14 +0000680 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
681 // to materialize the prvalue before we bind the reference to it.
682 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000683 SrcExpr = Self.CreateMaterializeTemporaryExpr(
684 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000685 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000686 }
687
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000688 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000689 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000690 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000691 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000692 SrcExpr.get())) {
693 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000694 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000695 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000696 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000697 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000698 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000699 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000700 return;
701 }
702
703 assert((DestPointer || DestReference) &&
704 "Bad destination non-ptr/ref slipped through.");
705 assert((DestRecord || DestPointee->isVoidType()) &&
706 "Bad destination pointee slipped through.");
707 assert(SrcRecord && "Bad source pointee slipped through.");
708
709 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
710 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000711 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000712 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000713 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000714 return;
715 }
716
717 // C++ 5.2.7p3: If the type of v is the same as the required result type,
718 // [except for cv].
719 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000720 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000721 return;
722 }
723
724 // C++ 5.2.7p5
725 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000726 if (DestRecord &&
727 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000728 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
729 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000730 &BasePath)) {
731 SrcExpr = ExprError();
732 return;
733 }
Richard Smith11330852014-07-08 17:25:14 +0000734
John McCalle3027922010-08-25 11:45:40 +0000735 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000736 return;
737 }
738
739 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000740 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000741 assert(SrcDecl && "Definition missing");
742 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000743 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000744 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000745 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000746 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000747
Eli Friedman3ce27102013-09-24 23:21:41 +0000748 // dynamic_cast is not available with -fno-rtti.
749 // As an exception, dynamic_cast to void* is available because it doesn't
750 // use RTTI.
751 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000752 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
753 SrcExpr = ExprError();
754 return;
755 }
756
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000757 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000758 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000759}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000760
761/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
762/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
763/// like this:
764/// const char *str = "literal";
765/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000766void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000767 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000768 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000769 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000770 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000771 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
772 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000773
774 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000775 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000776 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000777 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000778 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000779 SrcExpr = ExprError();
780 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000781}
782
John McCallcda80832013-03-22 02:58:14 +0000783/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
784/// or downcast between respective pointers or references.
785static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
786 QualType DestType,
787 SourceRange OpRange) {
788 QualType SrcType = SrcExpr->getType();
789 // When casting from pointer or reference, get pointee type; use original
790 // type otherwise.
791 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
792 const CXXRecordDecl *SrcRD =
793 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
794
John McCallf2abe192013-03-27 00:03:48 +0000795 // Examining subobjects for records is only possible if the complete and
796 // valid definition is available. Also, template instantiation is not
797 // allowed here.
798 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000799 return;
800
801 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
802
John McCallf2abe192013-03-27 00:03:48 +0000803 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000804 return;
805
806 enum {
807 ReinterpretUpcast,
808 ReinterpretDowncast
809 } ReinterpretKind;
810
811 CXXBasePaths BasePaths;
812
813 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
814 ReinterpretKind = ReinterpretUpcast;
815 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
816 ReinterpretKind = ReinterpretDowncast;
817 else
818 return;
819
820 bool VirtualBase = true;
821 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000822 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000823 E = BasePaths.end();
824 I != E; ++I) {
825 const CXXBasePath &Path = *I;
826 CharUnits Offset = CharUnits::Zero();
827 bool IsVirtual = false;
828 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
829 IElem != EElem; ++IElem) {
830 IsVirtual = IElem->Base->isVirtual();
831 if (IsVirtual)
832 break;
833 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
834 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000835 // Don't check if any base has invalid declaration or has no definition
836 // since it has no layout info.
837 const CXXRecordDecl *Class = IElem->Class,
838 *ClassDefinition = Class->getDefinition();
839 if (Class->isInvalidDecl() || !ClassDefinition ||
840 !ClassDefinition->isCompleteDefinition())
841 return;
842
John McCallcda80832013-03-22 02:58:14 +0000843 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000844 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000845 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
846 }
847 if (!IsVirtual) {
848 // Don't warn if any path is a non-virtually derived base at offset zero.
849 if (Offset.isZero())
850 return;
851 // Offset makes sense only for non-virtual bases.
852 else
853 NonZeroOffset = true;
854 }
855 VirtualBase = VirtualBase && IsVirtual;
856 }
857
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000858 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000859 assert((VirtualBase || NonZeroOffset) &&
860 "Should have returned if has non-virtual base with zero offset");
861
862 QualType BaseType =
863 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
864 QualType DerivedType =
865 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
866
Jordan Rose04a94d12013-03-28 19:09:40 +0000867 SourceLocation BeginLoc = OpRange.getBegin();
868 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000869 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000870 << OpRange;
871 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000872 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000873 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000874}
875
Sebastian Redl9f831db2009-07-25 15:41:38 +0000876/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
877/// valid.
878/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
879/// like this:
880/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000881void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000882 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000883 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000884 else
885 checkNonOverloadPlaceholders();
886 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
887 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000888
889 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000890 TryCastResult tcr =
891 TryReinterpretCast(Self, SrcExpr, DestType,
892 /*CStyle*/false, OpRange, msg, Kind);
893 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000894 {
John Wiegley01296292011-04-08 18:41:53 +0000895 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
896 return;
897 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000898 //FIXME: &f<int>; is overloaded and resolvable
899 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000900 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000901 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000902 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000903
John McCall909acf82011-02-14 18:34:10 +0000904 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000905 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
906 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000907 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000908 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000909 } else if (tcr == TC_Success) {
Brian Kelley762f9282017-03-29 18:16:38 +0000910 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000911 checkObjCConversion(Sema::CCK_OtherCast);
John McCallcda80832013-03-22 02:58:14 +0000912 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000913 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000914}
915
916
917/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
918/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
919/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000920void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000921 if (isPlaceholder()) {
922 checkNonOverloadPlaceholders();
923 if (SrcExpr.isInvalid())
924 return;
925 }
926
Sebastian Redl9f831db2009-07-25 15:41:38 +0000927 // This test is outside everything else because it's the only case where
928 // a non-lvalue-reference target type does not lead to decay.
929 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000930 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000931 Kind = CK_ToVoid;
932
933 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000934 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000935 false, // Decay Function to ptr
936 true, // Complain
937 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000938 if (SrcExpr.isInvalid())
939 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000940 }
John McCall9776e432011-10-06 23:25:11 +0000941
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000942 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000943 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000944 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000945
John McCall50a2c2c2011-10-11 23:14:30 +0000946 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
947 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000948 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +0000949 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
950 return;
951 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000952
953 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000954 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000955 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000956 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000957 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000958 if (SrcExpr.isInvalid())
959 return;
960 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
961 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000962 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000963 << oe->getName() << DestType << OpRange
964 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000965 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000966 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000967 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
968 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000969 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000970 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000971 } else if (tcr == TC_Success) {
972 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000973 checkCastAlign();
Brian Kelley762f9282017-03-29 18:16:38 +0000974 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000975 checkObjCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000976 } else if (Kind == CK_BitCast) {
977 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000978 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000979}
980
981/// TryStaticCast - Check if a static cast can be performed, and do so if
982/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
983/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000984static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000985 QualType DestType,
986 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000987 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000988 CastKind &Kind, CXXCastPath &BasePath,
989 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000990 // Determine whether we have the semantics of a C-style cast.
991 bool CStyle
992 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
993
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 // The order the tests is not entirely arbitrary. There is one conversion
995 // that can be handled in two different ways. Given:
996 // struct A {};
997 // struct B : public A {
998 // B(); B(const A&);
999 // };
1000 // const A &a = B();
1001 // the cast static_cast<const B&>(a) could be seen as either a static
1002 // reference downcast, or an explicit invocation of the user-defined
1003 // conversion using B's conversion constructor.
1004 // DR 427 specifies that the downcast is to be applied here.
1005
1006 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1007 // Done outside this function.
1008
1009 TryCastResult tcr;
1010
1011 // C++ 5.2.9p5, reference downcast.
1012 // See the function for details.
1013 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +00001014 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1015 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001016 if (tcr != TC_NotApplicable)
1017 return tcr;
1018
Davide Italianoa2275912015-07-12 22:10:56 +00001019 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001020 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1021 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001022 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
Sebastian Redld74dd492012-02-12 18:41:05 +00001023 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +00001024 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 return tcr;
1026
1027 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1028 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +00001029 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001030 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +00001031 if (SrcExpr.isInvalid())
1032 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001033 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001034 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +00001035
Sebastian Redl9f831db2009-07-25 15:41:38 +00001036 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1037 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1038 // conversions, subject to further restrictions.
1039 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1040 // of qualification conversions impossible.
1041 // In the CStyle case, the earlier attempt to const_cast should have taken
1042 // care of reverse qualification conversions.
1043
John Wiegley01296292011-04-08 18:41:53 +00001044 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045
Douglas Gregor0bf31402010-10-08 23:50:27 +00001046 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001047 // converted to an integral type. [...] A value of a scoped enumeration type
1048 // can also be explicitly converted to a floating-point type [...].
1049 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1050 if (Enum->getDecl()->isScoped()) {
1051 if (DestType->isBooleanType()) {
1052 Kind = CK_IntegralToBoolean;
1053 return TC_Success;
1054 } else if (DestType->isIntegralType(Self.Context)) {
1055 Kind = CK_IntegralCast;
1056 return TC_Success;
1057 } else if (DestType->isRealFloatingType()) {
1058 Kind = CK_IntegralToFloating;
1059 return TC_Success;
1060 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001061 }
1062 }
Douglas Gregorb327eac2011-02-18 03:01:41 +00001063
Sebastian Redl9f831db2009-07-25 15:41:38 +00001064 // Reverse integral promotion/conversion. All such conversions are themselves
1065 // again integral promotions or conversions and are thus already handled by
1066 // p2 (TryDirectInitialization above).
1067 // (Note: any data loss warnings should be suppressed.)
1068 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1069 // enum->enum). See also C++ 5.2.9p7.
1070 // The same goes for reverse floating point promotion/conversion and
1071 // floating-integral conversions. Again, only floating->enum is relevant.
1072 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001073 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001074 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001075 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001076 } else if (SrcType->isRealFloatingType()) {
1077 Kind = CK_FloatingToIntegral;
1078 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001079 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001080 }
1081
1082 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1083 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001084 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001085 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001086 if (tcr != TC_NotApplicable)
1087 return tcr;
1088
1089 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1090 // conversion. C++ 5.2.9p9 has additional information.
1091 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001092 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001093 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001094 if (tcr != TC_NotApplicable)
1095 return tcr;
1096
1097 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1098 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1099 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001100 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001101 QualType SrcPointee = SrcPointer->getPointeeType();
1102 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001103 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001104 QualType DestPointee = DestPointer->getPointeeType();
1105 if (DestPointee->isIncompleteOrObjectType()) {
1106 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001107 // to a qualifier violation. Note that we permit Objective-C lifetime
1108 // and GC qualifier mismatches here.
1109 if (!CStyle) {
1110 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1111 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1112 DestPointeeQuals.removeObjCGCAttr();
1113 DestPointeeQuals.removeObjCLifetime();
1114 SrcPointeeQuals.removeObjCGCAttr();
1115 SrcPointeeQuals.removeObjCLifetime();
1116 if (DestPointeeQuals != SrcPointeeQuals &&
1117 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1118 msg = diag::err_bad_cxx_cast_qualifiers_away;
1119 return TC_Failed;
1120 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001121 }
John McCalle3027922010-08-25 11:45:40 +00001122 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001123 return TC_Success;
1124 }
David Majnemer85bd1202015-06-02 22:15:12 +00001125
1126 // Microsoft permits static_cast from 'pointer-to-void' to
1127 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001128 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1129 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001130 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1131 Kind = CK_BitCast;
1132 return TC_Success;
1133 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001134 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001135 else if (DestType->isObjCObjectPointerType()) {
1136 // allow both c-style cast and static_cast of objective-c pointers as
1137 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001138 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001139 return TC_Success;
1140 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001141 else if (CStyle && DestType->isBlockPointerType()) {
1142 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001143 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001144 return TC_Success;
1145 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001146 }
1147 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001148 // Allow arbitray objective-c pointer conversion with static casts.
1149 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001150 DestType->isObjCObjectPointerType()) {
1151 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001152 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001153 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001154 // Allow ns-pointer to cf-pointer conversion in either direction
1155 // with static casts.
1156 if (!CStyle &&
1157 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1158 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001159
1160 // See if it looks like the user is trying to convert between
1161 // related record types, and select a better diagnostic if so.
1162 if (auto SrcPointer = SrcType->getAs<PointerType>())
1163 if (auto DestPointer = DestType->getAs<PointerType>())
1164 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1165 DestPointer->getPointeeType()->getAs<RecordType>())
1166 msg = diag::err_bad_cxx_cast_unrelated_class;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001167
Sebastian Redl9f831db2009-07-25 15:41:38 +00001168 // We tried everything. Everything! Nothing works! :-(
1169 return TC_NotApplicable;
1170}
1171
1172/// Tests whether a conversion according to N2844 is valid.
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001173TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1174 QualType DestType, bool CStyle,
1175 CastKind &Kind, CXXCastPath &BasePath,
1176 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001177 // C++11 [expr.static.cast]p3:
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001178 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
Douglas Gregor465184a2011-01-22 00:06:57 +00001179 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001180 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001181 if (!R)
1182 return TC_NotApplicable;
1183
Douglas Gregor465184a2011-01-22 00:06:57 +00001184 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001185 return TC_NotApplicable;
1186
1187 // Because we try the reference downcast before this function, from now on
1188 // this is the only cast possibility, so we issue an error if we fail now.
1189 // FIXME: Should allow casting away constness if CStyle.
1190 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001191 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001192 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001193 QualType FromType = SrcExpr->getType();
1194 QualType ToType = R->getPointeeType();
1195 if (CStyle) {
1196 FromType = FromType.getUnqualifiedType();
1197 ToType = ToType.getUnqualifiedType();
1198 }
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001199
1200 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1201 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
1202 ObjCLifetimeConversion);
1203 if (RefResult != Sema::Ref_Compatible) {
1204 if (CStyle || RefResult == Sema::Ref_Incompatible)
Davide Italianoa2275912015-07-12 22:10:56 +00001205 return TC_NotApplicable;
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001206 // Diagnose types which are reference-related but not compatible here since
1207 // we can provide better diagnostics. In these cases forwarding to
1208 // [expr.static.cast]p4 should never result in a well-formed cast.
1209 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1210 : diag::err_bad_rvalue_to_rvalue_cast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001211 return TC_Failed;
1212 }
1213
Douglas Gregorba278e22011-01-25 16:13:26 +00001214 if (DerivedToBase) {
1215 Kind = CK_DerivedToBase;
1216 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1217 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001218 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1219 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001220 return TC_NotApplicable;
1221
1222 Self.BuildBasePathArray(Paths, BasePath);
1223 } else
1224 Kind = CK_NoOp;
1225
Sebastian Redl9f831db2009-07-25 15:41:38 +00001226 return TC_Success;
1227}
1228
1229/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1230TryCastResult
1231TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001232 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001233 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001234 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001235 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1236 // cast to type "reference to cv2 D", where D is a class derived from B,
1237 // if a valid standard conversion from "pointer to D" to "pointer to B"
1238 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1239 // In addition, DR54 clarifies that the base must be accessible in the
1240 // current context. Although the wording of DR54 only applies to the pointer
1241 // variant of this rule, the intent is clearly for it to apply to the this
1242 // conversion as well.
1243
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001244 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001245 if (!DestReference) {
1246 return TC_NotApplicable;
1247 }
1248 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001249 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001250 // We know the left side is an lvalue reference, so we can suggest a reason.
1251 msg = diag::err_bad_cxx_cast_rvalue;
1252 return TC_NotApplicable;
1253 }
1254
1255 QualType DestPointee = DestReference->getPointeeType();
1256
Richard Smith11330852014-07-08 17:25:14 +00001257 // FIXME: If the source is a prvalue, we should issue a warning (because the
1258 // cast always has undefined behavior), and for AST consistency, we should
1259 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001260 return TryStaticDowncast(Self,
1261 Self.Context.getCanonicalType(SrcExpr->getType()),
1262 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001263 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1264 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001265}
1266
1267/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1268TryCastResult
1269TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001270 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001271 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001272 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001273 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1274 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1275 // is a class derived from B, if a valid standard conversion from "pointer
1276 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1277 // class of D.
1278 // In addition, DR54 clarifies that the base must be accessible in the
1279 // current context.
1280
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001281 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001282 if (!DestPointer) {
1283 return TC_NotApplicable;
1284 }
1285
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001287 if (!SrcPointer) {
1288 msg = diag::err_bad_static_cast_pointer_nonpointer;
1289 return TC_NotApplicable;
1290 }
1291
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001292 return TryStaticDowncast(Self,
1293 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1294 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001295 CStyle, OpRange, SrcType, DestType, msg, Kind,
1296 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001297}
1298
1299/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1300/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001301/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001302TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001303TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001304 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001305 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001306 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001307 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001308 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1309 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001310 return TC_NotApplicable;
1311
Sebastian Redl9f831db2009-07-25 15:41:38 +00001312 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001313 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001314 return TC_NotApplicable;
1315 }
1316
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001317 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001318 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001319 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001320 return TC_NotApplicable;
1321 }
1322
1323 // Target type does derive from source type. Now we're serious. If an error
1324 // appears now, it's not ignored.
1325 // This may not be entirely in line with the standard. Take for example:
1326 // struct A {};
1327 // struct B : virtual A {
1328 // B(A&);
1329 // };
Mike Stump11289f42009-09-09 15:08:12 +00001330 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001331 // void f()
1332 // {
1333 // (void)static_cast<const B&>(*((A*)0));
1334 // }
1335 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1336 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1337 // However, both GCC and Comeau reject this example, and accepting it would
1338 // mean more complex code if we're to preserve the nice error message.
1339 // FIXME: Being 100% compliant here would be nice to have.
1340
1341 // Must preserve cv, as always, unless we're in C-style mode.
1342 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001343 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001344 return TC_Failed;
1345 }
1346
1347 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1348 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1349 // that it builds the paths in reverse order.
1350 // To sum up: record all paths to the base and build a nice string from
1351 // them. Use it to spice up the error message.
1352 if (!Paths.isRecordingPaths()) {
1353 Paths.clear();
1354 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001355 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001356 }
1357 std::string PathDisplayStr;
1358 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001359 for (clang::CXXBasePath &Path : Paths) {
1360 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001361 // We haven't displayed a path to this particular base
1362 // class subobject yet.
1363 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001364 for (CXXBasePathElement &PE : llvm::reverse(Path))
1365 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001366 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001367 }
1368 }
1369
1370 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001371 << QualType(SrcType).getUnqualifiedType()
1372 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001373 << PathDisplayStr << OpRange;
1374 msg = 0;
1375 return TC_Failed;
1376 }
1377
Craig Topperc3ec1492014-05-26 06:22:03 +00001378 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001379 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1380 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1381 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1382 msg = 0;
1383 return TC_Failed;
1384 }
1385
John McCallfe9cf0a2011-02-14 23:21:33 +00001386 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001387 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1388 SrcType, DestType,
1389 Paths.front(),
1390 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001391 case Sema::AR_accessible:
1392 case Sema::AR_delayed: // be optimistic
1393 case Sema::AR_dependent: // be optimistic
1394 break;
1395
1396 case Sema::AR_inaccessible:
1397 msg = 0;
1398 return TC_Failed;
1399 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001400 }
1401
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001402 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001403 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001404 return TC_Success;
1405}
1406
1407/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1408/// C++ 5.2.9p9 is valid:
1409///
1410/// An rvalue of type "pointer to member of D of type cv1 T" can be
1411/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1412/// where B is a base class of D [...].
1413///
1414TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001415TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001416 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001417 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001418 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001419 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001420 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001421 if (!DestMemPtr)
1422 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001423
1424 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001425 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001426 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001427 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001428 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001429 FoundOverload)) {
1430 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1431 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1432 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1433 WasOverloadedFunction = true;
1434 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001435 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001436
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001437 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001438 if (!SrcMemPtr) {
1439 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1440 return TC_NotApplicable;
1441 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001442
1443 // Lock down the inheritance model right now in MS ABI, whether or not the
1444 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001445 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001446 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001447 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1448 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001449
1450 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001451 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1452 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001453 return TC_NotApplicable;
1454
1455 // B base of D
1456 QualType SrcClass(SrcMemPtr->getClass(), 0);
1457 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001458 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001459 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001460 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001461 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001462
1463 // 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 +00001464 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001465 Paths.clear();
1466 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001467 bool StillOkay =
1468 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001469 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001470 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001471 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1472 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1473 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1474 msg = 0;
1475 return TC_Failed;
1476 }
1477
1478 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1479 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1480 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1481 msg = 0;
1482 return TC_Failed;
1483 }
1484
John McCallfe9cf0a2011-02-14 23:21:33 +00001485 if (!CStyle) {
1486 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1487 DestClass, SrcClass,
1488 Paths.front(),
1489 diag::err_upcast_to_inaccessible_base)) {
1490 case Sema::AR_accessible:
1491 case Sema::AR_delayed:
1492 case Sema::AR_dependent:
1493 // Optimistically assume that the delayed and dependent cases
1494 // will work out.
1495 break;
1496
1497 case Sema::AR_inaccessible:
1498 msg = 0;
1499 return TC_Failed;
1500 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001501 }
1502
Douglas Gregorc934bc82010-03-07 23:24:59 +00001503 if (WasOverloadedFunction) {
1504 // Resolve the address of the overloaded function again, this time
1505 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001506 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001507 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001508 true,
1509 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001510 if (!Fn) {
1511 msg = 0;
1512 return TC_Failed;
1513 }
1514
John McCall16df1e52010-03-30 21:47:33 +00001515 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001516 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001517 msg = 0;
1518 return TC_Failed;
1519 }
1520 }
1521
Anders Carlssonb78feca2010-04-24 19:22:20 +00001522 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001523 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001524 return TC_Success;
1525}
1526
1527/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1528/// is valid:
1529///
1530/// An expression e can be explicitly converted to a type T using a
1531/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1532TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001533TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001534 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001535 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001536 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001537 if (DestType->isRecordType()) {
1538 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001539 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001540 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001541 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001542 msg = 0;
1543 return TC_Failed;
1544 }
1545 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001546
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001547 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1548 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001549 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001550 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001551 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001552 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001553 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001554 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001555 Expr *SrcExprRaw = SrcExpr.get();
Richard Smithb8c0f552016-12-09 18:49:13 +00001556 // FIXME: Per DR242, we should check for an implicit conversion sequence
1557 // or for a constructor that could be invoked by direct-initialization
1558 // here, not for an initialization sequence.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001559 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001560
1561 // At this point of CheckStaticCast, if the destination is a reference,
1562 // or the expression is an overload expression this has to work.
1563 // There is no other way that works.
1564 // On the other hand, if we're checking a C-style cast, we've still got
1565 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001566 bool CStyle
1567 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001568 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001569 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001570
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001571 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001572 if (Result.isInvalid()) {
1573 msg = 0;
1574 return TC_Failed;
1575 }
1576
Douglas Gregorb33eed02010-04-16 22:09:46 +00001577 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001578 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001579 else
John McCalle3027922010-08-25 11:45:40 +00001580 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001581
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001582 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001583 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001584}
1585
1586/// TryConstCast - See if a const_cast from source to destination is allowed,
1587/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001588static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1589 QualType DestType, bool CStyle,
1590 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001591 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001592 QualType SrcType = SrcExpr.get()->getType();
1593 bool NeedToMaterializeTemporary = false;
1594
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001595 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001596 // C++11 5.2.11p4:
1597 // if a pointer to T1 can be explicitly converted to the type "pointer to
1598 // T2" using a const_cast, then the following conversions can also be
1599 // made:
1600 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1601 // type T2 using the cast const_cast<T2&>;
1602 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1603 // type T2 using the cast const_cast<T2&&>; and
1604 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1605 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1606
1607 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001608 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1609 // is C-style, static_cast might find a way, so we simply suggest a
1610 // message and tell the parent to keep searching.
1611 msg = diag::err_bad_cxx_cast_rvalue;
1612 return TC_NotApplicable;
1613 }
1614
Richard Smith82c9b512013-06-14 22:27:52 +00001615 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1616 if (!SrcType->isRecordType()) {
1617 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1618 // this is C-style, static_cast can do this.
1619 msg = diag::err_bad_cxx_cast_rvalue;
1620 return TC_NotApplicable;
1621 }
1622
1623 // Materialize the class prvalue so that the const_cast can bind a
1624 // reference to it.
1625 NeedToMaterializeTemporary = true;
1626 }
1627
John McCalld25db7e2013-05-06 21:39:12 +00001628 // It's not completely clear under the standard whether we can
1629 // const_cast bit-field gl-values. Doing so would not be
1630 // intrinsically complicated, but for now, we say no for
1631 // consistency with other compilers and await the word of the
1632 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001633 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001634 msg = diag::err_bad_cxx_cast_bitfield;
1635 return TC_NotApplicable;
1636 }
1637
Sebastian Redl9f831db2009-07-25 15:41:38 +00001638 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1639 SrcType = Self.Context.getPointerType(SrcType);
1640 }
1641
1642 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1643 // the rules for const_cast are the same as those used for pointers.
1644
John McCall0e704f72010-05-18 09:35:29 +00001645 if (!DestType->isPointerType() &&
1646 !DestType->isMemberPointerType() &&
1647 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001648 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1649 // was a reference type, we converted it to a pointer above.
1650 // The status of rvalue references isn't entirely clear, but it looks like
1651 // conversion to them is simply invalid.
1652 // C++ 5.2.11p3: For two pointer types [...]
1653 if (!CStyle)
1654 msg = diag::err_bad_const_cast_dest;
1655 return TC_NotApplicable;
1656 }
1657 if (DestType->isFunctionPointerType() ||
1658 DestType->isMemberFunctionPointerType()) {
1659 // Cannot cast direct function pointers.
1660 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1661 // T is the ultimate pointee of source and target type.
1662 if (!CStyle)
1663 msg = diag::err_bad_const_cast_dest;
1664 return TC_NotApplicable;
1665 }
1666 SrcType = Self.Context.getCanonicalType(SrcType);
1667
1668 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1669 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001670 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1671 // in multi-level pointers may change, but the level count must be the same,
1672 // as must be the final pointee type.
1673 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001674 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001675 Qualifiers SrcQuals, DestQuals;
1676 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1677 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1678
1679 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1680 // the other qualifiers (e.g., address spaces) are identical.
1681 SrcQuals.removeCVRQualifiers();
1682 DestQuals.removeCVRQualifiers();
1683 if (SrcQuals != DestQuals)
1684 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001685 }
1686
1687 // Since we're dealing in canonical types, the remainder must be the same.
1688 if (SrcType != DestType)
1689 return TC_NotApplicable;
1690
Richard Smith82c9b512013-06-14 22:27:52 +00001691 if (NeedToMaterializeTemporary)
1692 // This is a const_cast from a class prvalue to an rvalue reference type.
1693 // Materialize a temporary to store the result of the conversion.
Richard Smithb8c0f552016-12-09 18:49:13 +00001694 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1695 SrcExpr.get(),
Tim Shen4a05bb82016-06-21 20:29:17 +00001696 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001697
Sebastian Redl9f831db2009-07-25 15:41:38 +00001698 return TC_Success;
1699}
1700
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001701// Checks for undefined behavior in reinterpret_cast.
1702// The cases that is checked for is:
1703// *reinterpret_cast<T*>(&a)
1704// reinterpret_cast<T&>(a)
1705// where accessing 'a' as type 'T' will result in undefined behavior.
1706void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1707 bool IsDereference,
1708 SourceRange Range) {
1709 unsigned DiagID = IsDereference ?
1710 diag::warn_pointer_indirection_from_incompatible_type :
1711 diag::warn_undefined_reinterpret_cast;
1712
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001713 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001714 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001715
1716 QualType SrcTy, DestTy;
1717 if (IsDereference) {
1718 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1719 return;
1720 }
1721 SrcTy = SrcType->getPointeeType();
1722 DestTy = DestType->getPointeeType();
1723 } else {
1724 if (!DestType->getAs<ReferenceType>()) {
1725 return;
1726 }
1727 SrcTy = SrcType;
1728 DestTy = DestType->getPointeeType();
1729 }
1730
1731 // Cast is compatible if the types are the same.
1732 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1733 return;
1734 }
1735 // or one of the types is a char or void type
1736 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1737 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1738 return;
1739 }
1740 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001741 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001742 return;
1743 }
1744
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001745 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001746 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1747 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1748 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1749 return;
1750 }
1751 }
1752
1753 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1754}
Douglas Gregor1beec452011-03-12 01:48:56 +00001755
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001756static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1757 QualType DestType) {
1758 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001759 if (Self.Context.hasSameType(SrcType, DestType))
1760 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001761 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1762 if (SrcPtrTy->isObjCSelType()) {
1763 QualType DT = DestType;
1764 if (isa<PointerType>(DestType))
1765 DT = DestType->getPointeeType();
1766 if (!DT.getUnqualifiedType()->isVoidType())
1767 Self.Diag(SrcExpr.get()->getExprLoc(),
1768 diag::warn_cast_pointer_from_sel)
1769 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1770 }
1771}
1772
Reid Kleckner9f497332016-05-10 21:00:03 +00001773/// Diagnose casts that change the calling convention of a pointer to a function
1774/// defined in the current TU.
1775static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1776 QualType DstType, SourceRange OpRange) {
1777 // Check if this cast would change the calling convention of a function
1778 // pointer type.
1779 QualType SrcType = SrcExpr.get()->getType();
1780 if (Self.Context.hasSameType(SrcType, DstType) ||
1781 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1782 return;
1783 const auto *SrcFTy =
1784 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1785 const auto *DstFTy =
1786 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1787 CallingConv SrcCC = SrcFTy->getCallConv();
1788 CallingConv DstCC = DstFTy->getCallConv();
1789 if (SrcCC == DstCC)
1790 return;
1791
1792 // We have a calling convention cast. Check if the source is a pointer to a
1793 // known, specific function that has already been defined.
1794 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1795 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1796 if (UO->getOpcode() == UO_AddrOf)
1797 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1798 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1799 if (!DRE)
1800 return;
1801 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Reid Kleckner0b009e82017-01-31 19:37:45 +00001802 if (!FD)
Reid Kleckner9f497332016-05-10 21:00:03 +00001803 return;
1804
Reid Kleckner43be52a2016-05-11 17:43:13 +00001805 // Only warn if we are casting from the default convention to a non-default
1806 // convention. This can happen when the programmer forgot to apply the calling
Reid Kleckner0b009e82017-01-31 19:37:45 +00001807 // convention to the function declaration and then inserted this cast to
Reid Kleckner43be52a2016-05-11 17:43:13 +00001808 // satisfy the type system.
1809 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1810 FD->isVariadic(), FD->isCXXInstanceMember());
1811 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1812 return;
1813
Reid Kleckner9f497332016-05-10 21:00:03 +00001814 // Diagnose this cast, as it is probably bad.
1815 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1816 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1817 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1818 << SrcCCName << DstCCName << OpRange;
1819
1820 // The checks above are cheaper than checking if the diagnostic is enabled.
1821 // However, it's worth checking if the warning is enabled before we construct
1822 // a fixit.
1823 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1824 return;
1825
1826 // Try to suggest a fixit to change the calling convention of the function
1827 // whose address was taken. Try to use the latest macro for the convention.
1828 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1829 // to match the Windows header declarations.
Reid Kleckner0b009e82017-01-31 19:37:45 +00001830 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
Reid Kleckner9f497332016-05-10 21:00:03 +00001831 Preprocessor &PP = Self.getPreprocessor();
1832 SmallVector<TokenValue, 6> AttrTokens;
1833 SmallString<64> CCAttrText;
1834 llvm::raw_svector_ostream OS(CCAttrText);
1835 if (Self.getLangOpts().MicrosoftExt) {
1836 // __stdcall or __vectorcall
1837 OS << "__" << DstCCName;
1838 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1839 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1840 ? TokenValue(II->getTokenID())
1841 : TokenValue(II));
1842 } else {
1843 // __attribute__((stdcall)) or __attribute__((vectorcall))
1844 OS << "__attribute__((" << DstCCName << "))";
1845 AttrTokens.push_back(tok::kw___attribute);
1846 AttrTokens.push_back(tok::l_paren);
1847 AttrTokens.push_back(tok::l_paren);
1848 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1849 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1850 ? TokenValue(II->getTokenID())
1851 : TokenValue(II));
1852 AttrTokens.push_back(tok::r_paren);
1853 AttrTokens.push_back(tok::r_paren);
1854 }
1855 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1856 if (!AttrSpelling.empty())
1857 CCAttrText = AttrSpelling;
1858 OS << ' ';
1859 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1860 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1861}
1862
David Blaikie282ad872012-10-16 18:53:14 +00001863static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1864 const Expr *SrcExpr, QualType DestType,
1865 Sema &Self) {
1866 QualType SrcType = SrcExpr->getType();
1867
1868 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1869 // are not explicit design choices, but consistent with GCC's behavior.
1870 // Feel free to modify them if you've reason/evidence for an alternative.
1871 if (CStyle && SrcType->isIntegralType(Self.Context)
1872 && !SrcType->isBooleanType()
1873 && !SrcType->isEnumeralType()
1874 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001875 && Self.Context.getTypeSize(DestType) >
1876 Self.Context.getTypeSize(SrcType)) {
1877 // Separate between casts to void* and non-void* pointers.
1878 // Some APIs use (abuse) void* for something like a user context,
1879 // and often that value is an integer even if it isn't a pointer itself.
1880 // Having a separate warning flag allows users to control the warning
1881 // for their workflow.
1882 unsigned Diag = DestType->isVoidPointerType() ?
1883 diag::warn_int_to_void_pointer_cast
1884 : diag::warn_int_to_pointer_cast;
1885 Self.Diag(Loc, Diag) << SrcType << DestType;
1886 }
David Blaikie282ad872012-10-16 18:53:14 +00001887}
1888
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001889static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1890 ExprResult &Result) {
1891 // We can only fix an overloaded reinterpret_cast if
1892 // - it is a template with explicit arguments that resolves to an lvalue
1893 // unambiguously, or
1894 // - it is the only function in an overload set that may have its address
1895 // taken.
1896
1897 Expr *E = Result.get();
1898 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1899 // like it?
1900 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1901 Result,
1902 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1903 ) &&
1904 Result.isUsable())
1905 return true;
1906
George Burgess IVbeca4a32016-06-08 00:34:22 +00001907 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1908 // preserves Result.
1909 Result = E;
George Burgess IV1dbfa852017-05-09 04:06:24 +00001910 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1911 Result, /*DoFunctionPointerConversion=*/true))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001912 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00001913 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001914}
1915
John Wiegley01296292011-04-08 18:41:53 +00001916static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001917 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001918 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001919 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001920 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001921 bool IsLValueCast = false;
1922
Sebastian Redl9f831db2009-07-25 15:41:38 +00001923 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001924 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001925
1926 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001927 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001928 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001929 ExprResult FixedExpr = SrcExpr;
1930 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001931 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001932
1933 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1934 SrcExpr = FixedExpr;
1935 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001936 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001937
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001938 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001939 if (!SrcExpr.get()->isGLValue()) {
1940 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1941 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001942 msg = diag::err_bad_cxx_cast_rvalue;
1943 return TC_NotApplicable;
1944 }
1945
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001946 if (!CStyle) {
1947 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1948 /*isDereference=*/false, OpRange);
1949 }
1950
Sebastian Redl9f831db2009-07-25 15:41:38 +00001951 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1952 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1953 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001954
Craig Topperc3ec1492014-05-26 06:22:03 +00001955 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001956 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001957 case OK_Ordinary:
1958 break;
Richard Smithb8c0f552016-12-09 18:49:13 +00001959 case OK_BitField:
1960 msg = diag::err_bad_cxx_cast_bitfield;
1961 return TC_NotApplicable;
1962 // FIXME: Use a specific diagnostic for the rest of these cases.
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001963 case OK_VectorComponent: inappropriate = "vector element"; break;
1964 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001965 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1966 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001967 }
1968 if (inappropriate) {
1969 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1970 << inappropriate << DestType
1971 << OpRange << SrcExpr.get()->getSourceRange();
1972 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001973 return TC_NotApplicable;
1974 }
1975
Sebastian Redl9f831db2009-07-25 15:41:38 +00001976 // This code does this transformation for the checked types.
1977 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1978 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001979
Douglas Gregor51954272010-07-13 23:17:26 +00001980 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001981 }
1982
1983 // Canonicalize source for comparison.
1984 SrcType = Self.Context.getCanonicalType(SrcType);
1985
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001986 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1987 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001988 if (DestMemPtr && SrcMemPtr) {
1989 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1990 // can be explicitly converted to an rvalue of type "pointer to member
1991 // of Y of type T2" if T1 and T2 are both function types or both object
1992 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00001993 if (DestMemPtr->isMemberFunctionPointer() !=
1994 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001995 return TC_NotApplicable;
1996
1997 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1998 // constness.
1999 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2000 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00002001 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2002 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00002003 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002004 return TC_Failed;
2005 }
2006
David Majnemer1cdd96d2014-01-17 09:01:00 +00002007 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2008 // We need to determine the inheritance model that the class will use if
2009 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00002010 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2011 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00002012 }
2013
Charles Davisebab1ed2010-08-16 05:30:44 +00002014 // Don't allow casting between member pointers of different sizes.
2015 if (Self.Context.getTypeSize(DestMemPtr) !=
2016 Self.Context.getTypeSize(SrcMemPtr)) {
2017 msg = diag::err_bad_cxx_cast_member_pointer_size;
2018 return TC_Failed;
2019 }
2020
Sebastian Redl9f831db2009-07-25 15:41:38 +00002021 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00002022 assert(!IsLValueCast);
2023 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002024 return TC_Success;
2025 }
2026
2027 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00002028 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002029 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2030 // type large enough to hold it. A value of std::nullptr_t can be
2031 // converted to an integral type; the conversion has the same meaning
2032 // and validity as a conversion of (void*)0 to the integral type.
2033 if (Self.Context.getTypeSize(SrcType) >
2034 Self.Context.getTypeSize(DestType)) {
2035 msg = diag::err_bad_reinterpret_cast_small_int;
2036 return TC_Failed;
2037 }
John McCalle3027922010-08-25 11:45:40 +00002038 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002039 return TC_Success;
2040 }
2041
John McCall1c78f082015-07-23 23:54:07 +00002042 // Allow reinterpret_casts between vectors of the same size and
2043 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00002044 bool destIsVector = DestType->isVectorType();
2045 bool srcIsVector = SrcType->isVectorType();
2046 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00002047 // The non-vector type, if any, must have integral type. This is
2048 // the same rule that C vector casts use; note, however, that enum
2049 // types are not integral in C++.
2050 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2051 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002052 return TC_NotApplicable;
2053
John McCall1c78f082015-07-23 23:54:07 +00002054 // The size we want to consider is eltCount * eltSize.
2055 // That's exactly what the lax-conversion rules will check.
2056 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002057 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002058 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002059 }
John McCall1c78f082015-07-23 23:54:07 +00002060
2061 // Otherwise, pick a reasonable diagnostic.
2062 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002063 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002064 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002065 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2066 else
2067 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2068
2069 return TC_Failed;
2070 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002071
2072 if (SrcType == DestType) {
2073 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2074 // restrictions, a cast to the same type is allowed so long as it does not
2075 // cast away constness. In C++98, the intent was not entirely clear here,
2076 // since all other paragraphs explicitly forbid casts to the same type.
2077 // C++11 clarifies this case with p2.
2078 //
2079 // The only allowed types are: integral, enumeration, pointer, or
2080 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2081 Kind = CK_NoOp;
2082 TryCastResult Result = TC_NotApplicable;
2083 if (SrcType->isIntegralOrEnumerationType() ||
2084 SrcType->isAnyPointerType() ||
2085 SrcType->isMemberPointerType() ||
2086 SrcType->isBlockPointerType()) {
2087 Result = TC_Success;
2088 }
2089 return Result;
2090 }
2091
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002092 bool destIsPtr = DestType->isAnyPointerType() ||
2093 DestType->isBlockPointerType();
2094 bool srcIsPtr = SrcType->isAnyPointerType() ||
2095 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002096 if (!destIsPtr && !srcIsPtr) {
2097 // Except for std::nullptr_t->integer and lvalue->reference, which are
2098 // handled above, at least one of the two arguments must be a pointer.
2099 return TC_NotApplicable;
2100 }
2101
Douglas Gregor6972a622010-06-16 00:35:25 +00002102 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002103 assert(srcIsPtr && "One type must be a pointer");
2104 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002105 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002106 // integral type size doesn't matter (except we don't allow bool).
2107 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2108 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002109 if ((Self.Context.getTypeSize(SrcType) >
2110 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002111 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002112 msg = diag::err_bad_reinterpret_cast_small_int;
2113 return TC_Failed;
2114 }
John McCalle3027922010-08-25 11:45:40 +00002115 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002116 return TC_Success;
2117 }
2118
Douglas Gregorb90df602010-06-16 00:17:44 +00002119 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002120 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002121 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2122 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002123 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2124 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002125 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2126 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002127 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002128 return TC_Success;
2129 }
2130
2131 if (!destIsPtr || !srcIsPtr) {
2132 // With the valid non-pointer conversions out of the way, we can be even
2133 // more stringent.
2134 return TC_NotApplicable;
2135 }
2136
2137 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2138 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00002139 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2140 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00002141 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002142 return TC_Failed;
2143 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002144
2145 // Cannot convert between block pointers and Objective-C object pointers.
2146 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2147 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2148 return TC_NotApplicable;
2149
John McCall9320b872011-09-09 05:25:32 +00002150 if (IsLValueCast) {
2151 Kind = CK_LValueBitCast;
2152 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002153 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002154 } else if (DestType->isBlockPointerType()) {
2155 if (!SrcType->isBlockPointerType()) {
2156 Kind = CK_AnyPointerToBlockPointerCast;
2157 } else {
2158 Kind = CK_BitCast;
2159 }
2160 } else {
2161 Kind = CK_BitCast;
2162 }
2163
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002164 // Any pointer can be cast to an Objective-C pointer type with a C-style
2165 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002166 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002167 return TC_Success;
2168 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002169 if (CStyle)
2170 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002171
2172 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2173
Sebastian Redl9f831db2009-07-25 15:41:38 +00002174 // Not casting away constness, so the only remaining check is for compatible
2175 // pointer categories.
2176
2177 if (SrcType->isFunctionPointerType()) {
2178 if (DestType->isFunctionPointerType()) {
2179 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2180 // a pointer to a function of a different type.
2181 return TC_Success;
2182 }
2183
2184 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2185 // an object type or vice versa is conditionally-supported.
2186 // Compilers support it in C++03 too, though, because it's necessary for
2187 // casting the return value of dlsym() and GetProcAddress().
2188 // FIXME: Conditionally-supported behavior should be configurable in the
2189 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002190 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002191 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002192 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2193 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002194 return TC_Success;
2195 }
2196
2197 if (DestType->isFunctionPointerType()) {
2198 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002199 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002200 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002201 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2202 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002203 return TC_Success;
2204 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002205
Sebastian Redl9f831db2009-07-25 15:41:38 +00002206 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2207 // a pointer to an object of different type.
2208 // Void pointers are not specified, but supported by every compiler out there.
2209 // So we finish by allowing everything that remains - it's got to be two
2210 // object pointers.
2211 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00002212}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002213
Sebastian Redld74dd492012-02-12 18:41:05 +00002214void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2215 bool ListInitialization) {
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002216 assert(Self.getLangOpts().CPlusPlus);
2217
John McCall9776e432011-10-06 23:25:11 +00002218 // Handle placeholders.
2219 if (isPlaceholder()) {
2220 // C-style casts can resolve __unknown_any types.
2221 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2222 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2223 SrcExpr.get(), Kind,
2224 ValueKind, BasePath);
2225 return;
2226 }
John McCallb50451a2011-10-05 07:41:44 +00002227
John McCall9776e432011-10-06 23:25:11 +00002228 checkNonOverloadPlaceholders();
2229 if (SrcExpr.isInvalid())
2230 return;
John McCalla072f5d2011-10-17 17:42:19 +00002231 }
John McCall9776e432011-10-06 23:25:11 +00002232
2233 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002234 // This test is outside everything else because it's the only case where
2235 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002236 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002237 Kind = CK_ToVoid;
2238
John McCall9776e432011-10-06 23:25:11 +00002239 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002240 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2241 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002242 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002243 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002244 if (SrcExpr.isInvalid())
2245 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002246 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002247
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002248 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002249 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002250 }
2251
Sebastian Redl9f831db2009-07-25 15:41:38 +00002252 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002253 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2254 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002255 assert(Kind == CK_Dependent);
2256 return;
John McCall8cb679e2010-11-15 09:13:47 +00002257 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002258
John McCall50a2c2c2011-10-11 23:14:30 +00002259 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2260 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002261 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002262 if (SrcExpr.isInvalid())
2263 return;
John Wiegley01296292011-04-08 18:41:53 +00002264 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002265
John McCall3aef3d82011-04-10 19:13:55 +00002266 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002267 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002268 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002269 && (SrcExpr.get()->getType()->isIntegerType()
2270 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002271 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002272 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002273 return;
John McCall3aef3d82011-04-10 19:13:55 +00002274 }
2275
Sebastian Redl9f831db2009-07-25 15:41:38 +00002276 // C++ [expr.cast]p5: The conversions performed by
2277 // - a const_cast,
2278 // - a static_cast,
2279 // - a static_cast followed by a const_cast,
2280 // - a reinterpret_cast, or
2281 // - a reinterpret_cast followed by a const_cast,
2282 // can be performed using the cast notation of explicit type conversion.
2283 // [...] If a conversion can be interpreted in more than one of the ways
2284 // listed above, the interpretation that appears first in the list is used,
2285 // even if a cast resulting from that interpretation is ill-formed.
2286 // In plain language, this means trying a const_cast ...
2287 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002288 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002289 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002290 if (SrcExpr.isInvalid())
2291 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002292 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002293 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002294
John McCall31168b02011-06-15 23:02:42 +00002295 Sema::CheckedConversionKind CCK
2296 = FunctionalStyle? Sema::CCK_FunctionalCast
2297 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002298 if (tcr == TC_NotApplicable) {
2299 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002300 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002301 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002302 if (SrcExpr.isInvalid())
2303 return;
2304
Sebastian Redl9f831db2009-07-25 15:41:38 +00002305 if (tcr == TC_NotApplicable) {
2306 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002307 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2308 OpRange, msg, Kind);
2309 if (SrcExpr.isInvalid())
2310 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002311 }
2312 }
2313
Brian Kelley11352a82017-03-29 18:09:02 +00002314 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2315 tcr == TC_Success)
2316 checkObjCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002317
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002318 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002319 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002320 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002321 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2322 DestType,
2323 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002324 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002325 if (Fn) {
2326 // If DestType is a function type (not to be confused with the function
2327 // pointer type), it will be possible to resolve the function address,
2328 // but the type cast should be considered as failure.
2329 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2330 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2331 << OE->getName() << DestType << OpRange
2332 << OE->getQualifierLoc().getSourceRange();
2333 Self.NoteAllOverloadCandidates(SrcExpr.get());
2334 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002335 } else {
John McCallb50451a2011-10-05 07:41:44 +00002336 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002337 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002338 }
John McCallb50451a2011-10-05 07:41:44 +00002339 } else if (Kind == CK_BitCast) {
2340 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002341 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002342
John McCallb50451a2011-10-05 07:41:44 +00002343 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002344 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002345 SrcExpr = ExprError();
2346}
2347
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002348/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2349/// non-matching type. Such as enum function call to int, int call to
2350/// pointer; etc. Cast to 'void' is an exception.
2351static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2352 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002353 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2354 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002355 return;
2356
2357 if (!isa<CallExpr>(SrcExpr.get()))
2358 return;
2359
2360 QualType SrcType = SrcExpr.get()->getType();
2361 if (DestType.getUnqualifiedType()->isVoidType())
2362 return;
2363 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2364 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2365 return;
2366 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2367 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2368 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2369 return;
2370 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2371 return;
2372 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2373 return;
2374 if (SrcType->isComplexType() && DestType->isComplexType())
2375 return;
2376 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2377 return;
2378
2379 Self.Diag(SrcExpr.get()->getExprLoc(),
2380 diag::warn_bad_function_cast)
2381 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2382}
2383
John McCall9776e432011-10-06 23:25:11 +00002384/// Check the semantics of a C-style cast operation, in C.
2385void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002386 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002387
John McCall4124c492011-10-17 18:40:02 +00002388 // C-style casts can resolve __unknown_any types.
2389 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2390 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2391 SrcExpr.get(), Kind,
2392 ValueKind, BasePath);
2393 return;
2394 }
John McCall9776e432011-10-06 23:25:11 +00002395
2396 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2397 // type needs to be scalar.
2398 if (DestType->isVoidType()) {
2399 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002400 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002401 if (SrcExpr.isInvalid())
2402 return;
2403
2404 // Cast to void allows any expr type.
2405 Kind = CK_ToVoid;
2406 return;
2407 }
2408
George Burgess IV5f21c712015-10-12 19:57:04 +00002409 // Overloads are allowed with C extensions, so we need to support them.
2410 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2411 DeclAccessPair DAP;
2412 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2413 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2414 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2415 else
2416 return;
2417 assert(SrcExpr.isUsable());
2418 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002419 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002420 if (SrcExpr.isInvalid())
2421 return;
2422 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002423
John McCall4124c492011-10-17 18:40:02 +00002424 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002425
Joey Gouly8fc32f02014-01-14 12:47:29 +00002426 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2427 // address space B is illegal.
2428 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2429 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002430 const PointerType *DestPtr = DestType->getAs<PointerType>();
2431 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002432 Self.Diag(OpRange.getBegin(),
2433 diag::err_typecheck_incompatible_address_space)
2434 << SrcType << DestType << Sema::AA_Casting
2435 << SrcExpr.get()->getSourceRange();
2436 SrcExpr = ExprError();
2437 return;
2438 }
2439 }
2440
John McCall9776e432011-10-06 23:25:11 +00002441 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2442 diag::err_typecheck_cast_to_incomplete)) {
2443 SrcExpr = ExprError();
2444 return;
2445 }
2446
2447 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2448 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2449
2450 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2451 // GCC struct/union extension: allow cast to self.
2452 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2453 << DestType << SrcExpr.get()->getSourceRange();
2454 Kind = CK_NoOp;
2455 return;
2456 }
2457
2458 // GCC's cast to union extension.
2459 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2460 RecordDecl *RD = DestRecordTy->getDecl();
John McCallf1ef7962017-08-15 21:42:47 +00002461 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2462 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2463 << SrcExpr.get()->getSourceRange();
2464 Kind = CK_ToUnion;
2465 return;
2466 } else {
John McCall9776e432011-10-06 23:25:11 +00002467 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2468 << SrcType << SrcExpr.get()->getSourceRange();
2469 SrcExpr = ExprError();
2470 return;
2471 }
John McCall9776e432011-10-06 23:25:11 +00002472 }
2473
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002474 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2475 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2476 llvm::APSInt CastInt;
2477 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2478 if (0 == CastInt) {
2479 Kind = CK_ZeroToOCLEvent;
2480 return;
2481 }
2482 Self.Diag(OpRange.getBegin(),
Richard Smithf8812672016-12-02 22:38:31 +00002483 diag::err_opencl_cast_non_zero_to_event_t)
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002484 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2485 SrcExpr = ExprError();
2486 return;
2487 }
2488 }
2489
John McCall9776e432011-10-06 23:25:11 +00002490 // Reject any other conversions to non-scalar types.
2491 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2492 << DestType << SrcExpr.get()->getSourceRange();
2493 SrcExpr = ExprError();
2494 return;
2495 }
2496
2497 // The type we're casting to is known to be a scalar or vector.
2498
2499 // Require the operand to be a scalar or vector.
2500 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2501 Self.Diag(SrcExpr.get()->getExprLoc(),
2502 diag::err_typecheck_expect_scalar_operand)
2503 << SrcType << SrcExpr.get()->getSourceRange();
2504 SrcExpr = ExprError();
2505 return;
2506 }
2507
2508 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002509 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002510 return;
2511 }
2512
2513 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2514 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2515 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2516 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002517 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002518 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2519 SrcExpr = ExprError();
2520 }
2521 return;
2522 }
2523
2524 if (SrcType->isVectorType()) {
2525 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2526 SrcExpr = ExprError();
2527 return;
2528 }
2529
2530 // The source and target types are both scalars, i.e.
2531 // - arithmetic types (fundamental, enum, and complex)
2532 // - all kinds of pointers
2533 // Note that member pointers were filtered out with C++, above.
2534
2535 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2536 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2537 SrcExpr = ExprError();
2538 return;
2539 }
2540
2541 // If either type is a pointer, the other type has to be either an
2542 // integer or a pointer.
2543 if (!DestType->isArithmeticType()) {
2544 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2545 Self.Diag(SrcExpr.get()->getExprLoc(),
2546 diag::err_cast_pointer_from_non_pointer_int)
2547 << SrcType << SrcExpr.get()->getSourceRange();
2548 SrcExpr = ExprError();
2549 return;
2550 }
David Blaikie282ad872012-10-16 18:53:14 +00002551 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2552 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002553 } else if (!SrcType->isArithmeticType()) {
2554 if (!DestType->isIntegralType(Self.Context) &&
2555 DestType->isArithmeticType()) {
2556 Self.Diag(SrcExpr.get()->getLocStart(),
2557 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002558 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002559 SrcExpr = ExprError();
2560 return;
2561 }
2562 }
2563
Yaxun Liu5b746652016-12-18 05:18:55 +00002564 if (Self.getLangOpts().OpenCL &&
2565 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
Joey Goulydd7f4562013-01-23 11:56:20 +00002566 if (DestType->isHalfType()) {
2567 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2568 << DestType << SrcExpr.get()->getSourceRange();
2569 SrcExpr = ExprError();
2570 return;
2571 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002572 }
2573
John McCall9776e432011-10-06 23:25:11 +00002574 // ARC imposes extra restrictions on casts.
Brian Kelley11352a82017-03-29 18:09:02 +00002575 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2576 checkObjCConversion(Sema::CCK_CStyleCast);
John McCall9776e432011-10-06 23:25:11 +00002577 if (SrcExpr.isInvalid())
2578 return;
Brian Kelley11352a82017-03-29 18:09:02 +00002579
2580 const PointerType *CastPtr = DestType->getAs<PointerType>();
2581 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
John McCall9776e432011-10-06 23:25:11 +00002582 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2583 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2584 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2585 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2586 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2587 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2588 Self.Diag(SrcExpr.get()->getLocStart(),
2589 diag::err_typecheck_incompatible_ownership)
2590 << SrcType << DestType << Sema::AA_Casting
2591 << SrcExpr.get()->getSourceRange();
2592 return;
2593 }
2594 }
2595 }
2596 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2597 Self.Diag(SrcExpr.get()->getLocStart(),
2598 diag::err_arc_convesion_of_weak_unavailable)
2599 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2600 SrcExpr = ExprError();
2601 return;
2602 }
2603 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002604
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002605 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002606 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002607 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002608 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2609 if (SrcExpr.isInvalid())
2610 return;
2611
2612 if (Kind == CK_BitCast)
2613 checkCastAlign();
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002614}
Roman Divackyd5178012014-11-21 21:03:10 +00002615
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002616/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2617/// const, volatile or both.
2618static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2619 QualType DestType) {
2620 if (SrcExpr.isInvalid())
2621 return;
2622
2623 QualType SrcType = SrcExpr.get()->getType();
2624 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2625 DestType->isLValueReferenceType()))
2626 return;
2627
Roman Divackyd5178012014-11-21 21:03:10 +00002628 QualType TheOffendingSrcType, TheOffendingDestType;
2629 Qualifiers CastAwayQualifiers;
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002630 if (!CastsAwayConstness(Self, SrcType, DestType, true, false,
2631 &TheOffendingSrcType, &TheOffendingDestType,
2632 &CastAwayQualifiers))
2633 return;
2634
2635 int qualifiers = -1;
2636 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2637 qualifiers = 0;
2638 } else if (CastAwayQualifiers.hasConst()) {
2639 qualifiers = 1;
2640 } else if (CastAwayQualifiers.hasVolatile()) {
2641 qualifiers = 2;
Roman Divackyd5178012014-11-21 21:03:10 +00002642 }
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002643 // This is a variant of int **x; const int **y = (const int **)x;
2644 if (qualifiers == -1)
2645 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
2646 << SrcType << DestType;
2647 else
2648 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
2649 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
John McCall9776e432011-10-06 23:25:11 +00002650}
2651
2652ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2653 TypeSourceInfo *CastTypeInfo,
2654 SourceLocation RPLoc,
2655 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002656 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2657 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2658 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2659
David Blaikiebbafb8a2012-03-11 07:00:24 +00002660 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002661 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2662 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002663 } else {
2664 Op.CheckCStyleCast();
2665 }
2666
John McCallb50451a2011-10-05 07:41:44 +00002667 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002668 return ExprError();
2669
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002670 // -Wcast-qual
2671 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2672
John McCall4124c492011-10-17 18:40:02 +00002673 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002674 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002675 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002676}
2677
2678ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
Richard Smith60437622017-02-09 19:17:44 +00002679 QualType Type,
John McCallb50451a2011-10-05 07:41:44 +00002680 SourceLocation LPLoc,
2681 Expr *CastExpr,
2682 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002683 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
Richard Smith60437622017-02-09 19:17:44 +00002684 CastOperation Op(*this, Type, CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002685 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2686 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2687
Sebastian Redl2b80af42012-02-13 19:55:43 +00002688 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002689 if (Op.SrcExpr.isInvalid())
2690 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002691
2692 auto *SubExpr = Op.SrcExpr.get();
2693 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2694 SubExpr = BindExpr->getSubExpr();
2695 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002696 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002697
John McCall4124c492011-10-17 18:40:02 +00002698 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002699 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002700 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002701}