blob: 8599fe09a5d61c120b28bc74db31b7d59471a2c8 [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCall3cec19f2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCallcda80832013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer1cdd96d2014-01-17 09:01:00 +000024#include "clang/Basic/TargetInfo.h"
Reid Kleckner9f497332016-05-10 21:00:03 +000025#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000027#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000028#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000029using namespace clang;
30
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Douglas Gregore81f58e2010-11-08 03:40:48 +000032
Sebastian Redl9f831db2009-07-25 15:41:38 +000033enum TryCastResult {
34 TC_NotApplicable, ///< The cast method is not applicable.
35 TC_Success, ///< The cast method is appropriate and successful.
Richard Smithf276e2d2018-07-10 23:04:35 +000036 TC_Extension, ///< The cast method is appropriate and accepted as a
37 ///< language extension.
Sebastian Redl9f831db2009-07-25 15:41:38 +000038 TC_Failed ///< The cast method is appropriate, but failed. A
39 ///< diagnostic has been emitted.
40};
41
Richard Smithf276e2d2018-07-10 23:04:35 +000042static bool isValidCast(TryCastResult TCR) {
43 return TCR == TC_Success || TCR == TC_Extension;
44}
45
Sebastian Redl9f831db2009-07-25 15:41:38 +000046enum CastType {
47 CT_Const, ///< const_cast
48 CT_Static, ///< static_cast
49 CT_Reinterpret, ///< reinterpret_cast
50 CT_Dynamic, ///< dynamic_cast
51 CT_CStyle, ///< (Type)expr
52 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000053};
54
John McCallb50451a2011-10-05 07:41:44 +000055namespace {
56 struct CastOperation {
57 CastOperation(Sema &S, QualType destType, ExprResult src)
58 : Self(S), SrcExpr(src), DestType(destType),
59 ResultType(destType.getNonLValueExprType(S.Context)),
60 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000061 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000062
63 if (const BuiltinType *placeholder =
64 src.get()->getType()->getAsPlaceholderType()) {
65 PlaceholderKind = placeholder->getKind();
66 } else {
67 PlaceholderKind = (BuiltinType::Kind) 0;
68 }
69 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000070
John McCallb50451a2011-10-05 07:41:44 +000071 Sema &Self;
72 ExprResult SrcExpr;
73 QualType DestType;
74 QualType ResultType;
75 ExprValueKind ValueKind;
76 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000077 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000078 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000079 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000080
John McCallb50451a2011-10-05 07:41:44 +000081 SourceRange OpRange;
82 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000083
John McCall9776e432011-10-06 23:25:11 +000084 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000085 void CheckConstCast();
86 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000087 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000088 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000089 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000090 void CheckCStyleCast();
91
Roman Lebedevd55661d2018-07-24 08:16:50 +000092 void updatePartOfExplicitCastFlags(CastExpr *CE) {
93 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
94 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
95 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
Roman Lebedev12216f12018-07-27 07:27:14 +000096 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
97 ICE->setIsPartOfExplicitCast(true);
Roman Lebedevd55661d2018-07-24 08:16:50 +000098 }
99
John McCall4124c492011-10-17 18:40:02 +0000100 /// Complete an apparently-successful cast operation that yields
101 /// the given expression.
102 ExprResult complete(CastExpr *castExpr) {
103 // If this is an unbridged cast, wrap the result in an implicit
104 // cast that yields the unbridged-cast placeholder type.
105 if (IsARCUnbridgedCast) {
106 castExpr = ImplicitCastExpr::Create(Self.Context,
107 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000108 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +0000109 castExpr->getValueKind());
110 }
Roman Lebedevd55661d2018-07-24 08:16:50 +0000111 updatePartOfExplicitCastFlags(castExpr);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000112 return castExpr;
John McCall4124c492011-10-17 18:40:02 +0000113 }
114
John McCall9776e432011-10-06 23:25:11 +0000115 // Internal convenience methods.
116
117 /// Try to handle the given placeholder expression kind. Return
118 /// true if the source expression has the appropriate placeholder
119 /// kind. A placeholder can only be claimed once.
120 bool claimPlaceholder(BuiltinType::Kind K) {
121 if (PlaceholderKind != K) return false;
122
123 PlaceholderKind = (BuiltinType::Kind) 0;
124 return true;
125 }
126
127 bool isPlaceholder() const {
128 return PlaceholderKind != 0;
129 }
130 bool isPlaceholder(BuiltinType::Kind K) const {
131 return PlaceholderKind == K;
132 }
John McCallb50451a2011-10-05 07:41:44 +0000133
134 void checkCastAlign() {
135 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
136 }
137
Brian Kelley11352a82017-03-29 18:09:02 +0000138 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
139 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
John McCall4124c492011-10-17 18:40:02 +0000140
John McCallb50451a2011-10-05 07:41:44 +0000141 Expr *src = SrcExpr.get();
Brian Kelley11352a82017-03-29 18:09:02 +0000142 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
143 Sema::ACR_unbridged)
John McCall4124c492011-10-17 18:40:02 +0000144 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000145 SrcExpr = src;
146 }
John McCall9776e432011-10-06 23:25:11 +0000147
148 /// Check for and handle non-overload placeholder expressions.
149 void checkNonOverloadPlaceholders() {
150 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
151 return;
152
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000153 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000154 if (SrcExpr.isInvalid())
155 return;
156 PlaceholderKind = (BuiltinType::Kind) 0;
157 }
John McCallb50451a2011-10-05 07:41:44 +0000158 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000159}
Sebastian Redl842ef522008-11-08 13:00:26 +0000160
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000161static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
162 QualType DestType);
163
Sebastian Redl9f831db2009-07-25 15:41:38 +0000164// The Try functions attempt a specific way of casting. If they succeed, they
165// return TC_Success. If their way of casting is not appropriate for the given
166// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
167// to emit if no other way succeeds. If their way of casting is appropriate but
168// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
169// they emit a specialized diagnostic.
170// All diagnostics returned by these functions must expect the same three
171// arguments:
172// %0: Cast Type (a value from the CastType enumeration)
173// %1: Source Type
174// %2: Destination Type
175static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000176 QualType DestType, bool CStyle,
177 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000178 CXXCastPath &BasePath,
179 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000180static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000181 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000182 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000183 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000184 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000185 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000186static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
187 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000188 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000189 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000190 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000191 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000192static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
193 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000194 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000195 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000196 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000197 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000198 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000199static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000200 QualType SrcType,
201 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000202 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000203 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000204 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000205 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000206
John Wiegley01296292011-04-08 18:41:53 +0000207static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +0000208 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +0000209 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000210 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000211 unsigned &msg, CastKind &Kind,
212 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000213static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +0000214 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +0000215 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000216 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000217 unsigned &msg, CastKind &Kind,
218 CXXCastPath &BasePath,
219 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000220static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
221 QualType DestType, bool CStyle,
222 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000223static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000224 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000225 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000226 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000227 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000228
Douglas Gregorb491ed32011-02-19 21:32:49 +0000229
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000230/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000231ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000232Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000233 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000234 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000235 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000236 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000237
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000238 assert(!D.isInvalidType());
239
240 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
241 if (D.isInvalidType())
242 return ExprError();
243
David Blaikiebbafb8a2012-03-11 07:00:24 +0000244 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000245 // Check that there are no default arguments (C++ only).
246 CheckExtraCXXDefaultArguments(D);
247 }
248
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000249 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000250 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
251 SourceRange(LParenLoc, RParenLoc));
252}
253
John McCalldadc5752010-08-24 06:29:42 +0000254ExprResult
John McCalld377e042010-01-15 19:13:16 +0000255Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000256 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000257 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000258 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000259 QualType DestType = DestTInfo->getType();
260
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000261 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000262 bool TypeDependent =
263 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000264
John McCallb50451a2011-10-05 07:41:44 +0000265 CastOperation Op(*this, DestType, E);
266 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
267 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000268
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000269 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000270 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000271
272 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000273 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000274 Op.CheckConstCast();
275 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000276 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000277 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000278 }
John McCall4124c492011-10-17 18:40:02 +0000279 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000280 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000281 OpLoc, Parens.getEnd(),
282 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000283
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000284 case tok::kw_dynamic_cast: {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000285 // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
286 if (getLangOpts().OpenCLCPlusPlus) {
287 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
288 << "dynamic_cast");
289 }
290
John Wiegley01296292011-04-08 18:41:53 +0000291 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000292 Op.CheckDynamicCast();
293 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000294 return ExprError();
295 }
John McCall4124c492011-10-17 18:40:02 +0000296 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000297 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000298 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000299 OpLoc, Parens.getEnd(),
300 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000301 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000302 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000303 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000304 Op.CheckReinterpretCast();
305 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000306 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000307 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000308 }
John McCall4124c492011-10-17 18:40:02 +0000309 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000310 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000311 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000312 Parens.getEnd(),
313 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000314 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000315 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000316 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000317 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000318 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000319 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000320 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000321 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000322
John McCall4124c492011-10-17 18:40:02 +0000323 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000324 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000325 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000326 OpLoc, Parens.getEnd(),
327 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000328 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000329 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000330}
331
John McCall909acf82011-02-14 18:34:10 +0000332/// Try to diagnose a failed overloaded cast. Returns true if
333/// diagnostics were emitted.
334static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
335 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000336 QualType destType,
337 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000338 switch (CT) {
339 // These cast kinds don't consider user-defined conversions.
340 case CT_Const:
341 case CT_Reinterpret:
342 case CT_Dynamic:
343 return false;
344
345 // These do.
346 case CT_Static:
347 case CT_CStyle:
348 case CT_Functional:
349 break;
350 }
351
352 QualType srcType = src->getType();
353 if (!destType->isRecordType() && !srcType->isRecordType())
354 return false;
355
356 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
357 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000358 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000359 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000360 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000361 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000362 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000363 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000364
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000365 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000366 switch (sequence.getFailureKind()) {
367 default: return false;
368
369 case InitializationSequence::FK_ConstructorOverloadFailed:
370 case InitializationSequence::FK_UserConversionOverloadFailed:
371 break;
372 }
373
374 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
375
376 unsigned msg = 0;
377 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
378
379 switch (sequence.getFailedOverloadResult()) {
380 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000381 case OR_No_Viable_Function:
382 if (candidates.empty())
383 msg = diag::err_ovl_no_conversion_in_cast;
384 else
385 msg = diag::err_ovl_no_viable_conversion_in_cast;
386 howManyCandidates = OCD_AllCandidates;
387 break;
388
389 case OR_Ambiguous:
390 msg = diag::err_ovl_ambiguous_conversion_in_cast;
391 howManyCandidates = OCD_ViableCandidates;
392 break;
393
394 case OR_Deleted:
395 msg = diag::err_ovl_deleted_conversion_in_cast;
396 howManyCandidates = OCD_ViableCandidates;
397 break;
398 }
399
400 S.Diag(range.getBegin(), msg)
401 << CT << srcType << destType
402 << range << src->getSourceRange();
403
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000404 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000405
406 return true;
407}
408
409/// Diagnose a failed cast.
410static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000411 SourceRange opRange, Expr *src, QualType destType,
412 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000413 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000414 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
415 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000416 return;
417
418 S.Diag(opRange.getBegin(), msg) << castType
419 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000420
421 // Detect if both types are (ptr to) class, and note any incompleteness.
422 int DifferentPtrness = 0;
423 QualType From = destType;
424 if (auto Ptr = From->getAs<PointerType>()) {
425 From = Ptr->getPointeeType();
426 DifferentPtrness++;
427 }
428 QualType To = src->getType();
429 if (auto Ptr = To->getAs<PointerType>()) {
430 To = Ptr->getPointeeType();
431 DifferentPtrness--;
432 }
433 if (!DifferentPtrness) {
434 auto RecFrom = From->getAs<RecordType>();
435 auto RecTo = To->getAs<RecordType>();
436 if (RecFrom && RecTo) {
437 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
438 if (!DeclFrom->isCompleteDefinition())
439 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
440 << DeclFrom->getDeclName();
441 auto DeclTo = RecTo->getAsCXXRecordDecl();
442 if (!DeclTo->isCompleteDefinition())
443 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
444 << DeclTo->getDeclName();
445 }
446 }
John McCall909acf82011-02-14 18:34:10 +0000447}
448
Richard Smithf276e2d2018-07-10 23:04:35 +0000449namespace {
450/// The kind of unwrapping we did when determining whether a conversion casts
451/// away constness.
452enum CastAwayConstnessKind {
453 /// The conversion does not cast away constness.
454 CACK_None = 0,
455 /// We unwrapped similar types.
456 CACK_Similar = 1,
457 /// We unwrapped dissimilar types with similar representations (eg, a pointer
458 /// versus an Objective-C object pointer).
459 CACK_SimilarKind = 2,
460 /// We unwrapped representationally-unrelated types, such as a pointer versus
461 /// a pointer-to-member.
462 CACK_Incoherent = 3,
463};
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000464}
465
Richard Smithf276e2d2018-07-10 23:04:35 +0000466/// Unwrap one level of types for CastsAwayConstness.
467///
Richard Smitha3405ff2018-07-11 00:19:19 +0000468/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
469/// both types, provided that they're both pointer-like or array-like. Unlike
470/// the Sema function, doesn't care if the unwrapped pieces are related.
Richard Smith5407d4f2018-07-18 20:13:36 +0000471///
472/// This function may remove additional levels as necessary for correctness:
473/// the resulting T1 is unwrapped sufficiently that it is never an array type,
474/// so that its qualifiers can be directly compared to those of T2 (which will
475/// have the combined set of qualifiers from all indermediate levels of T2),
476/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
477/// with those from T2.
Richard Smithf276e2d2018-07-10 23:04:35 +0000478static CastAwayConstnessKind
479unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000480 enum { None, Ptr, MemPtr, BlockPtr, Array };
Richard Smithf276e2d2018-07-10 23:04:35 +0000481 auto Classify = [](QualType T) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000482 if (T->isAnyPointerType()) return Ptr;
483 if (T->isMemberPointerType()) return MemPtr;
484 if (T->isBlockPointerType()) return BlockPtr;
Richard Smitha3405ff2018-07-11 00:19:19 +0000485 // We somewhat-arbitrarily don't look through VLA types here. This is at
486 // least consistent with the behavior of UnwrapSimilarTypes.
Richard Smith5407d4f2018-07-18 20:13:36 +0000487 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
488 return None;
Richard Smithf276e2d2018-07-10 23:04:35 +0000489 };
490
Richard Smitha3405ff2018-07-11 00:19:19 +0000491 auto Unwrap = [&](QualType T) {
492 if (auto *AT = Context.getAsArrayType(T))
493 return AT->getElementType();
494 return T->getPointeeType();
495 };
496
Richard Smith5407d4f2018-07-18 20:13:36 +0000497 CastAwayConstnessKind Kind;
498
499 if (T2->isReferenceType()) {
500 // Special case: if the destination type is a reference type, unwrap it as
501 // the first level. (The source will have been an lvalue expression in this
502 // case, so there is no corresponding "reference to" in T1 to remove.) This
503 // simulates removing a "pointer to" from both sides.
504 T2 = T2->getPointeeType();
505 Kind = CastAwayConstnessKind::CACK_Similar;
506 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
507 Kind = CastAwayConstnessKind::CACK_Similar;
508 } else {
509 // Try unwrapping mismatching levels.
510 int T1Class = Classify(T1);
511 if (T1Class == None)
512 return CastAwayConstnessKind::CACK_None;
513
514 int T2Class = Classify(T2);
515 if (T2Class == None)
516 return CastAwayConstnessKind::CACK_None;
517
518 T1 = Unwrap(T1);
519 T2 = Unwrap(T2);
520 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
521 : CastAwayConstnessKind::CACK_Incoherent;
522 }
523
524 // We've unwrapped at least one level. If the resulting T1 is a (possibly
525 // multidimensional) array type, any qualifier on any matching layer of
526 // T2 is considered to correspond to T1. Decompose down to the element
527 // type of T1 so that we can compare properly.
528 while (true) {
529 Context.UnwrapSimilarArrayTypes(T1, T2);
530
531 if (Classify(T1) != Array)
532 break;
533
534 auto T2Class = Classify(T2);
535 if (T2Class == None)
536 break;
537
538 if (T2Class != Array)
539 Kind = CastAwayConstnessKind::CACK_Incoherent;
540 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
541 Kind = CastAwayConstnessKind::CACK_SimilarKind;
542
543 T1 = Unwrap(T1);
544 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
545 }
546
547 return Kind;
Richard Smithf276e2d2018-07-10 23:04:35 +0000548}
549
550/// Check if the pointer conversion from SrcType to DestType casts away
551/// constness as defined in C++ [expr.const.cast]. This is used by the cast
552/// checkers. Both arguments must denote pointer (possibly to member) types.
John McCall31168b02011-06-15 23:02:42 +0000553///
554/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
John McCall31168b02011-06-15 23:02:42 +0000555/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Richard Smithf276e2d2018-07-10 23:04:35 +0000556static CastAwayConstnessKind
John McCall31168b02011-06-15 23:02:42 +0000557CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000558 bool CheckCVR, bool CheckObjCLifetime,
559 QualType *TheOffendingSrcType = nullptr,
560 QualType *TheOffendingDestType = nullptr,
561 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000562 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000563 // and we're not in ObjC mode, there's nothing to check.
Richard Smithf276e2d2018-07-10 23:04:35 +0000564 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC1)
565 return CastAwayConstnessKind::CACK_None;
566
567 if (!DestType->isReferenceType()) {
568 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
569 SrcType->isBlockPointerType()) &&
570 "Source type is not pointer or pointer to member.");
571 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
572 DestType->isBlockPointerType()) &&
573 "Destination type is not pointer or pointer to member.");
574 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000575
Fangrui Song6907ce22018-07-30 19:24:48 +0000576 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000577 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000578
Fangrui Song6907ce22018-07-30 19:24:48 +0000579 // Find the qualifiers. We only care about cvr-qualifiers for the
580 // purpose of this check, because other qualifiers (address spaces,
Douglas Gregorb472e932011-04-15 17:59:54 +0000581 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000582 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
583 QualType PrevUnwrappedDestType = UnwrappedDestType;
Richard Smithf276e2d2018-07-10 23:04:35 +0000584 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
585 bool AllConstSoFar = true;
586 while (auto Kind = unwrapCastAwayConstnessLevel(
587 Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
588 // Track the worst kind of unwrap we needed to do before we found a
589 // problem.
590 if (Kind > WorstKind)
591 WorstKind = Kind;
592
John McCall31168b02011-06-15 23:02:42 +0000593 // Determine the relevant qualifiers at this level.
594 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000595 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000596 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Akira Hatanaka8d7bdf62017-08-11 00:06:49 +0000597
598 // We do not meaningfully track object const-ness of Objective-C object
599 // types. Remove const from the source type if either the source or
600 // the destination is an Objective-C object type.
601 if (UnwrappedSrcType->isObjCObjectType() ||
602 UnwrappedDestType->isObjCObjectType())
603 SrcQuals.removeConst();
604
John McCall31168b02011-06-15 23:02:42 +0000605 if (CheckCVR) {
Richard Smithf276e2d2018-07-10 23:04:35 +0000606 Qualifiers SrcCvrQuals =
607 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
608 Qualifiers DestCvrQuals =
609 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000610
Richard Smithf276e2d2018-07-10 23:04:35 +0000611 if (SrcCvrQuals != DestCvrQuals) {
612 if (CastAwayQualifiers)
613 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
614
615 // If we removed a cvr-qualifier, this is casting away 'constness'.
616 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
617 if (TheOffendingSrcType)
618 *TheOffendingSrcType = PrevUnwrappedSrcType;
619 if (TheOffendingDestType)
620 *TheOffendingDestType = PrevUnwrappedDestType;
621 return WorstKind;
622 }
623
624 // If any prior level was not 'const', this is also casting away
625 // 'constness'. We noted the outermost type missing a 'const' already.
626 if (!AllConstSoFar)
627 return WorstKind;
Roman Divackyd5178012014-11-21 21:03:10 +0000628 }
John McCall31168b02011-06-15 23:02:42 +0000629 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000630
John McCall31168b02011-06-15 23:02:42 +0000631 if (CheckObjCLifetime &&
632 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
Richard Smithf276e2d2018-07-10 23:04:35 +0000633 return WorstKind;
634
635 // If we found our first non-const-qualified type, this may be the place
636 // where things start to go wrong.
637 if (AllConstSoFar && !DestQuals.hasConst()) {
638 AllConstSoFar = false;
639 if (TheOffendingSrcType)
640 *TheOffendingSrcType = PrevUnwrappedSrcType;
641 if (TheOffendingDestType)
642 *TheOffendingDestType = PrevUnwrappedDestType;
643 }
Roman Divackyd5178012014-11-21 21:03:10 +0000644
645 PrevUnwrappedSrcType = UnwrappedSrcType;
646 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000647 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000648
Richard Smithf276e2d2018-07-10 23:04:35 +0000649 return CastAwayConstnessKind::CACK_None;
650}
651
652static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
653 unsigned &DiagID) {
654 switch (CACK) {
655 case CastAwayConstnessKind::CACK_None:
656 llvm_unreachable("did not cast away constness");
657
658 case CastAwayConstnessKind::CACK_Similar:
659 // FIXME: Accept these as an extension too?
660 case CastAwayConstnessKind::CACK_SimilarKind:
661 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
662 return TC_Failed;
663
664 case CastAwayConstnessKind::CACK_Incoherent:
665 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
666 return TC_Extension;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000667 }
668
Richard Smithf276e2d2018-07-10 23:04:35 +0000669 llvm_unreachable("unexpected cast away constness kind");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000670}
671
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000672/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
673/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
674/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000675void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000676 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000677 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000678 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000679 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000680 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
681 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000682
John McCallb50451a2011-10-05 07:41:44 +0000683 QualType OrigSrcType = SrcExpr.get()->getType();
684 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000685
686 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
687 // or "pointer to cv void".
688
689 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000690 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000691 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000692 if (DestPointer) {
693 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000694 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000695 DestPointee = DestReference->getPointeeType();
696 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000697 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000698 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000699 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000700 return;
701 }
702
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000703 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000704 if (DestPointee->isVoidType()) {
705 assert(DestPointer && "Reference to void is not possible");
706 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000707 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000708 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000709 DestRange)) {
710 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000711 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000712 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000713 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000714 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000715 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000716 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000717 return;
718 }
719
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000720 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
721 // complete class type, [...]. If T is an lvalue reference type, v shall be
Fangrui Song6907ce22018-07-30 19:24:48 +0000722 // an lvalue of a complete class type, [...]. If T is an rvalue reference
Douglas Gregor465184a2011-01-22 00:06:57 +0000723 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000724 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000725 QualType SrcPointee;
726 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000727 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000728 SrcPointee = SrcPointer->getPointeeType();
729 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000730 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000731 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000732 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000733 return;
734 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000735 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000736 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000737 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000738 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000739 }
740 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000741 } else {
Richard Smith11330852014-07-08 17:25:14 +0000742 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
743 // to materialize the prvalue before we bind the reference to it.
744 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000745 SrcExpr = Self.CreateMaterializeTemporaryExpr(
746 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000747 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000748 }
749
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000750 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000751 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000752 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000753 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000754 SrcExpr.get())) {
755 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000756 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000757 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000758 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000759 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000760 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000761 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000762 return;
763 }
764
765 assert((DestPointer || DestReference) &&
766 "Bad destination non-ptr/ref slipped through.");
767 assert((DestRecord || DestPointee->isVoidType()) &&
768 "Bad destination pointee slipped through.");
769 assert(SrcRecord && "Bad source pointee slipped through.");
770
771 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
772 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000773 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000774 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000775 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000776 return;
777 }
778
779 // C++ 5.2.7p3: If the type of v is the same as the required result type,
780 // [except for cv].
781 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000782 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000783 return;
784 }
785
786 // C++ 5.2.7p5
787 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000788 if (DestRecord &&
789 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000790 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Fangrui Song6907ce22018-07-30 19:24:48 +0000791 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000792 &BasePath)) {
793 SrcExpr = ExprError();
794 return;
795 }
Richard Smith11330852014-07-08 17:25:14 +0000796
John McCalle3027922010-08-25 11:45:40 +0000797 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000798 return;
799 }
800
801 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000802 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000803 assert(SrcDecl && "Definition missing");
804 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000805 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000806 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000807 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000808 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000809
Eli Friedman3ce27102013-09-24 23:21:41 +0000810 // dynamic_cast is not available with -fno-rtti.
811 // As an exception, dynamic_cast to void* is available because it doesn't
812 // use RTTI.
813 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000814 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
815 SrcExpr = ExprError();
816 return;
817 }
818
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000819 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000820 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000821}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000822
823/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
824/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
825/// like this:
826/// const char *str = "literal";
827/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000828void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000829 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000830 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000831 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000832 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000833 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
834 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000835
836 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smithf276e2d2018-07-10 23:04:35 +0000837 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
838 if (TCR != TC_Success && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000839 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000840 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000841 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000842 if (!isValidCast(TCR))
843 SrcExpr = ExprError();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000844}
845
John McCallcda80832013-03-22 02:58:14 +0000846/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
847/// or downcast between respective pointers or references.
848static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
849 QualType DestType,
850 SourceRange OpRange) {
851 QualType SrcType = SrcExpr->getType();
852 // When casting from pointer or reference, get pointee type; use original
853 // type otherwise.
854 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
855 const CXXRecordDecl *SrcRD =
856 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
857
John McCallf2abe192013-03-27 00:03:48 +0000858 // Examining subobjects for records is only possible if the complete and
859 // valid definition is available. Also, template instantiation is not
860 // allowed here.
861 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000862 return;
863
864 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
865
John McCallf2abe192013-03-27 00:03:48 +0000866 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000867 return;
868
869 enum {
870 ReinterpretUpcast,
871 ReinterpretDowncast
872 } ReinterpretKind;
873
874 CXXBasePaths BasePaths;
875
876 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
877 ReinterpretKind = ReinterpretUpcast;
878 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
879 ReinterpretKind = ReinterpretDowncast;
880 else
881 return;
882
883 bool VirtualBase = true;
884 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000885 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000886 E = BasePaths.end();
887 I != E; ++I) {
888 const CXXBasePath &Path = *I;
889 CharUnits Offset = CharUnits::Zero();
890 bool IsVirtual = false;
891 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
892 IElem != EElem; ++IElem) {
893 IsVirtual = IElem->Base->isVirtual();
894 if (IsVirtual)
895 break;
896 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
897 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000898 // Don't check if any base has invalid declaration or has no definition
899 // since it has no layout info.
900 const CXXRecordDecl *Class = IElem->Class,
901 *ClassDefinition = Class->getDefinition();
902 if (Class->isInvalidDecl() || !ClassDefinition ||
903 !ClassDefinition->isCompleteDefinition())
904 return;
905
John McCallcda80832013-03-22 02:58:14 +0000906 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000907 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000908 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
909 }
910 if (!IsVirtual) {
911 // Don't warn if any path is a non-virtually derived base at offset zero.
912 if (Offset.isZero())
913 return;
914 // Offset makes sense only for non-virtual bases.
915 else
916 NonZeroOffset = true;
917 }
918 VirtualBase = VirtualBase && IsVirtual;
919 }
920
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000921 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000922 assert((VirtualBase || NonZeroOffset) &&
923 "Should have returned if has non-virtual base with zero offset");
924
925 QualType BaseType =
926 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
927 QualType DerivedType =
928 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
929
Jordan Rose04a94d12013-03-28 19:09:40 +0000930 SourceLocation BeginLoc = OpRange.getBegin();
931 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000932 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000933 << OpRange;
934 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000935 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000936 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000937}
938
Sebastian Redl9f831db2009-07-25 15:41:38 +0000939/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
940/// valid.
941/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
942/// like this:
943/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000944void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000945 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000946 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000947 else
948 checkNonOverloadPlaceholders();
949 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
950 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000951
952 unsigned msg = diag::err_bad_cxx_cast_generic;
Fangrui Song6907ce22018-07-30 19:24:48 +0000953 TryCastResult tcr =
954 TryReinterpretCast(Self, SrcExpr, DestType,
John McCall31168b02011-06-15 23:02:42 +0000955 /*CStyle*/false, OpRange, msg, Kind);
Richard Smithf276e2d2018-07-10 23:04:35 +0000956 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000957 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
958 return;
959 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000960 //FIXME: &f<int>; is overloaded and resolvable
961 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000962 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000963 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000964 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000965
John McCall909acf82011-02-14 18:34:10 +0000966 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000967 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
968 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000969 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000970 }
971
972 if (isValidCast(tcr)) {
Brian Kelley762f9282017-03-29 18:16:38 +0000973 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000974 checkObjCConversion(Sema::CCK_OtherCast);
John McCallcda80832013-03-22 02:58:14 +0000975 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
Richard Smithf276e2d2018-07-10 23:04:35 +0000976 } else {
977 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000978 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000979}
980
981
982/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
983/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
984/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000985void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000986 if (isPlaceholder()) {
987 checkNonOverloadPlaceholders();
988 if (SrcExpr.isInvalid())
989 return;
990 }
991
Sebastian Redl9f831db2009-07-25 15:41:38 +0000992 // This test is outside everything else because it's the only case where
993 // a non-lvalue-reference target type does not lead to decay.
994 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000995 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000996 Kind = CK_ToVoid;
997
998 if (claimPlaceholder(BuiltinType::Overload)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000999 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1000 false, // Decay Function to ptr
Douglas Gregorb491ed32011-02-19 21:32:49 +00001001 true, // Complain
1002 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +00001003 if (SrcExpr.isInvalid())
1004 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001005 }
John McCall9776e432011-10-06 23:25:11 +00001006
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001007 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001008 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001009 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001010
John McCall50a2c2c2011-10-11 23:14:30 +00001011 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1012 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001013 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00001014 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1015 return;
1016 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001017
1018 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +00001019 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +00001020 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001021 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +00001022 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +00001023 if (SrcExpr.isInvalid())
1024 return;
1025 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1026 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +00001027 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Fangrui Song6907ce22018-07-30 19:24:48 +00001028 << oe->getName() << DestType << OpRange
Douglas Gregor0da1d432011-02-28 20:01:57 +00001029 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00001030 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +00001031 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +00001032 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1033 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001034 }
Richard Smithf276e2d2018-07-10 23:04:35 +00001035 }
1036
1037 if (isValidCast(tcr)) {
John McCall31168b02011-06-15 23:02:42 +00001038 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +00001039 checkCastAlign();
Brian Kelley762f9282017-03-29 18:16:38 +00001040 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +00001041 checkObjCConversion(Sema::CCK_OtherCast);
Richard Smithf276e2d2018-07-10 23:04:35 +00001042 } else {
1043 SrcExpr = ExprError();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001044 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045}
1046
Yaxun Liu4b06ffe2018-08-03 03:18:56 +00001047static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1048 auto *SrcPtrType = SrcType->getAs<PointerType>();
1049 if (!SrcPtrType)
1050 return false;
1051 auto *DestPtrType = DestType->getAs<PointerType>();
1052 if (!DestPtrType)
1053 return false;
1054 return SrcPtrType->getPointeeType().getAddressSpace() !=
1055 DestPtrType->getPointeeType().getAddressSpace();
1056}
1057
Sebastian Redl9f831db2009-07-25 15:41:38 +00001058/// TryStaticCast - Check if a static cast can be performed, and do so if
1059/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1060/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +00001061static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +00001062 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001063 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001064 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001065 CastKind &Kind, CXXCastPath &BasePath,
1066 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +00001067 // Determine whether we have the semantics of a C-style cast.
Fangrui Song6907ce22018-07-30 19:24:48 +00001068 bool CStyle
John McCall31168b02011-06-15 23:02:42 +00001069 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Fangrui Song6907ce22018-07-30 19:24:48 +00001070
Sebastian Redl9f831db2009-07-25 15:41:38 +00001071 // The order the tests is not entirely arbitrary. There is one conversion
1072 // that can be handled in two different ways. Given:
1073 // struct A {};
1074 // struct B : public A {
1075 // B(); B(const A&);
1076 // };
1077 // const A &a = B();
1078 // the cast static_cast<const B&>(a) could be seen as either a static
1079 // reference downcast, or an explicit invocation of the user-defined
1080 // conversion using B's conversion constructor.
1081 // DR 427 specifies that the downcast is to be applied here.
1082
1083 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1084 // Done outside this function.
1085
1086 TryCastResult tcr;
1087
1088 // C++ 5.2.9p5, reference downcast.
1089 // See the function for details.
1090 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +00001091 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1092 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001093 if (tcr != TC_NotApplicable)
1094 return tcr;
1095
Fangrui Song6907ce22018-07-30 19:24:48 +00001096 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001097 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1098 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001099 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
Sebastian Redld74dd492012-02-12 18:41:05 +00001100 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +00001101 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001102 return tcr;
1103
1104 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1105 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +00001106 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001107 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +00001108 if (SrcExpr.isInvalid())
1109 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001110 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001111 return tcr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001112
Sebastian Redl9f831db2009-07-25 15:41:38 +00001113 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1114 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1115 // conversions, subject to further restrictions.
1116 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1117 // of qualification conversions impossible.
1118 // In the CStyle case, the earlier attempt to const_cast should have taken
1119 // care of reverse qualification conversions.
1120
John Wiegley01296292011-04-08 18:41:53 +00001121 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001122
Douglas Gregor0bf31402010-10-08 23:50:27 +00001123 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001124 // converted to an integral type. [...] A value of a scoped enumeration type
1125 // can also be explicitly converted to a floating-point type [...].
1126 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1127 if (Enum->getDecl()->isScoped()) {
1128 if (DestType->isBooleanType()) {
1129 Kind = CK_IntegralToBoolean;
1130 return TC_Success;
1131 } else if (DestType->isIntegralType(Self.Context)) {
1132 Kind = CK_IntegralCast;
1133 return TC_Success;
1134 } else if (DestType->isRealFloatingType()) {
1135 Kind = CK_IntegralToFloating;
1136 return TC_Success;
1137 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001138 }
1139 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001140
Sebastian Redl9f831db2009-07-25 15:41:38 +00001141 // Reverse integral promotion/conversion. All such conversions are themselves
1142 // again integral promotions or conversions and are thus already handled by
1143 // p2 (TryDirectInitialization above).
1144 // (Note: any data loss warnings should be suppressed.)
1145 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1146 // enum->enum). See also C++ 5.2.9p7.
1147 // The same goes for reverse floating point promotion/conversion and
1148 // floating-integral conversions. Again, only floating->enum is relevant.
1149 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001150 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001151 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001152 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001153 } else if (SrcType->isRealFloatingType()) {
1154 Kind = CK_FloatingToIntegral;
1155 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001156 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001157 }
1158
1159 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1160 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001161 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001162 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001163 if (tcr != TC_NotApplicable)
1164 return tcr;
1165
1166 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1167 // conversion. C++ 5.2.9p9 has additional information.
1168 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001169 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001170 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001171 if (tcr != TC_NotApplicable)
1172 return tcr;
1173
1174 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1175 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1176 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001177 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001178 QualType SrcPointee = SrcPointer->getPointeeType();
1179 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001180 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001181 QualType DestPointee = DestPointer->getPointeeType();
1182 if (DestPointee->isIncompleteOrObjectType()) {
1183 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001184 // to a qualifier violation. Note that we permit Objective-C lifetime
1185 // and GC qualifier mismatches here.
1186 if (!CStyle) {
1187 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1188 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1189 DestPointeeQuals.removeObjCGCAttr();
1190 DestPointeeQuals.removeObjCLifetime();
1191 SrcPointeeQuals.removeObjCGCAttr();
1192 SrcPointeeQuals.removeObjCLifetime();
1193 if (DestPointeeQuals != SrcPointeeQuals &&
1194 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1195 msg = diag::err_bad_cxx_cast_qualifiers_away;
1196 return TC_Failed;
1197 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001198 }
Yaxun Liu4b06ffe2018-08-03 03:18:56 +00001199 Kind = IsAddressSpaceConversion(SrcType, DestType)
1200 ? CK_AddressSpaceConversion
1201 : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001202 return TC_Success;
1203 }
David Majnemer85bd1202015-06-02 22:15:12 +00001204
1205 // Microsoft permits static_cast from 'pointer-to-void' to
1206 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001207 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1208 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001209 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1210 Kind = CK_BitCast;
1211 return TC_Success;
1212 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001213 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001214 else if (DestType->isObjCObjectPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001215 // allow both c-style cast and static_cast of objective-c pointers as
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001216 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001217 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001218 return TC_Success;
1219 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001220 else if (CStyle && DestType->isBlockPointerType()) {
1221 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001222 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001223 return TC_Success;
1224 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001225 }
1226 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001227 // Allow arbitrary objective-c pointer conversion with static casts.
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001228 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001229 DestType->isObjCObjectPointerType()) {
1230 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001231 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001232 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001233 // Allow ns-pointer to cf-pointer conversion in either direction
1234 // with static casts.
1235 if (!CStyle &&
1236 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1237 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001238
1239 // See if it looks like the user is trying to convert between
1240 // related record types, and select a better diagnostic if so.
1241 if (auto SrcPointer = SrcType->getAs<PointerType>())
1242 if (auto DestPointer = DestType->getAs<PointerType>())
1243 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1244 DestPointer->getPointeeType()->getAs<RecordType>())
1245 msg = diag::err_bad_cxx_cast_unrelated_class;
Fangrui Song6907ce22018-07-30 19:24:48 +00001246
Sebastian Redl9f831db2009-07-25 15:41:38 +00001247 // We tried everything. Everything! Nothing works! :-(
1248 return TC_NotApplicable;
1249}
1250
1251/// Tests whether a conversion according to N2844 is valid.
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001252TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1253 QualType DestType, bool CStyle,
1254 CastKind &Kind, CXXCastPath &BasePath,
1255 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001256 // C++11 [expr.static.cast]p3:
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001257 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
Douglas Gregor465184a2011-01-22 00:06:57 +00001258 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001259 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001260 if (!R)
1261 return TC_NotApplicable;
1262
Douglas Gregor465184a2011-01-22 00:06:57 +00001263 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001264 return TC_NotApplicable;
1265
1266 // Because we try the reference downcast before this function, from now on
1267 // this is the only cast possibility, so we issue an error if we fail now.
1268 // FIXME: Should allow casting away constness if CStyle.
1269 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001270 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001271 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001272 QualType FromType = SrcExpr->getType();
1273 QualType ToType = R->getPointeeType();
1274 if (CStyle) {
1275 FromType = FromType.getUnqualifiedType();
1276 ToType = ToType.getUnqualifiedType();
1277 }
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001278
1279 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1280 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
1281 ObjCLifetimeConversion);
1282 if (RefResult != Sema::Ref_Compatible) {
1283 if (CStyle || RefResult == Sema::Ref_Incompatible)
Davide Italianoa2275912015-07-12 22:10:56 +00001284 return TC_NotApplicable;
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001285 // Diagnose types which are reference-related but not compatible here since
1286 // we can provide better diagnostics. In these cases forwarding to
1287 // [expr.static.cast]p4 should never result in a well-formed cast.
1288 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1289 : diag::err_bad_rvalue_to_rvalue_cast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001290 return TC_Failed;
1291 }
1292
Douglas Gregorba278e22011-01-25 16:13:26 +00001293 if (DerivedToBase) {
1294 Kind = CK_DerivedToBase;
1295 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1296 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001297 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1298 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001299 return TC_NotApplicable;
Fangrui Song6907ce22018-07-30 19:24:48 +00001300
Douglas Gregorba278e22011-01-25 16:13:26 +00001301 Self.BuildBasePathArray(Paths, BasePath);
1302 } else
1303 Kind = CK_NoOp;
Fangrui Song6907ce22018-07-30 19:24:48 +00001304
Sebastian Redl9f831db2009-07-25 15:41:38 +00001305 return TC_Success;
1306}
1307
1308/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1309TryCastResult
1310TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001311 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001312 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001313 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001314 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1315 // cast to type "reference to cv2 D", where D is a class derived from B,
1316 // if a valid standard conversion from "pointer to D" to "pointer to B"
1317 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1318 // In addition, DR54 clarifies that the base must be accessible in the
1319 // current context. Although the wording of DR54 only applies to the pointer
1320 // variant of this rule, the intent is clearly for it to apply to the this
1321 // conversion as well.
1322
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001323 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001324 if (!DestReference) {
1325 return TC_NotApplicable;
1326 }
1327 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001328 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001329 // We know the left side is an lvalue reference, so we can suggest a reason.
1330 msg = diag::err_bad_cxx_cast_rvalue;
1331 return TC_NotApplicable;
1332 }
1333
1334 QualType DestPointee = DestReference->getPointeeType();
1335
Richard Smith11330852014-07-08 17:25:14 +00001336 // FIXME: If the source is a prvalue, we should issue a warning (because the
1337 // cast always has undefined behavior), and for AST consistency, we should
1338 // materialize a temporary.
Fangrui Song6907ce22018-07-30 19:24:48 +00001339 return TryStaticDowncast(Self,
1340 Self.Context.getCanonicalType(SrcExpr->getType()),
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001341 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001342 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1343 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001344}
1345
1346/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1347TryCastResult
1348TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001349 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001350 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001351 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001352 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1353 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1354 // is a class derived from B, if a valid standard conversion from "pointer
1355 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1356 // class of D.
1357 // In addition, DR54 clarifies that the base must be accessible in the
1358 // current context.
1359
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001360 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001361 if (!DestPointer) {
1362 return TC_NotApplicable;
1363 }
1364
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001365 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001366 if (!SrcPointer) {
1367 msg = diag::err_bad_static_cast_pointer_nonpointer;
1368 return TC_NotApplicable;
1369 }
1370
Fangrui Song6907ce22018-07-30 19:24:48 +00001371 return TryStaticDowncast(Self,
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001372 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001373 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001374 CStyle, OpRange, SrcType, DestType, msg, Kind,
1375 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001376}
1377
1378/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1379/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001380/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001381TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001382TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001383 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Fangrui Song6907ce22018-07-30 19:24:48 +00001384 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001385 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001386 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001387 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1388 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001389 return TC_NotApplicable;
1390
Sebastian Redl9f831db2009-07-25 15:41:38 +00001391 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001392 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001393 return TC_NotApplicable;
1394 }
1395
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001396 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001397 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001398 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001399 return TC_NotApplicable;
1400 }
1401
1402 // Target type does derive from source type. Now we're serious. If an error
1403 // appears now, it's not ignored.
1404 // This may not be entirely in line with the standard. Take for example:
1405 // struct A {};
1406 // struct B : virtual A {
1407 // B(A&);
1408 // };
Mike Stump11289f42009-09-09 15:08:12 +00001409 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001410 // void f()
1411 // {
1412 // (void)static_cast<const B&>(*((A*)0));
1413 // }
1414 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1415 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1416 // However, both GCC and Comeau reject this example, and accepting it would
1417 // mean more complex code if we're to preserve the nice error message.
1418 // FIXME: Being 100% compliant here would be nice to have.
1419
1420 // Must preserve cv, as always, unless we're in C-style mode.
1421 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001422 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001423 return TC_Failed;
1424 }
1425
1426 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1427 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1428 // that it builds the paths in reverse order.
1429 // To sum up: record all paths to the base and build a nice string from
1430 // them. Use it to spice up the error message.
1431 if (!Paths.isRecordingPaths()) {
1432 Paths.clear();
1433 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001434 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001435 }
1436 std::string PathDisplayStr;
1437 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001438 for (clang::CXXBasePath &Path : Paths) {
1439 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001440 // We haven't displayed a path to this particular base
1441 // class subobject yet.
1442 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001443 for (CXXBasePathElement &PE : llvm::reverse(Path))
1444 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001445 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001446 }
1447 }
1448
1449 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Fangrui Song6907ce22018-07-30 19:24:48 +00001450 << QualType(SrcType).getUnqualifiedType()
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001451 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001452 << PathDisplayStr << OpRange;
1453 msg = 0;
1454 return TC_Failed;
1455 }
1456
Craig Topperc3ec1492014-05-26 06:22:03 +00001457 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001458 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1459 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1460 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1461 msg = 0;
1462 return TC_Failed;
1463 }
1464
John McCallfe9cf0a2011-02-14 23:21:33 +00001465 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001466 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1467 SrcType, DestType,
1468 Paths.front(),
1469 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001470 case Sema::AR_accessible:
1471 case Sema::AR_delayed: // be optimistic
1472 case Sema::AR_dependent: // be optimistic
1473 break;
1474
1475 case Sema::AR_inaccessible:
1476 msg = 0;
1477 return TC_Failed;
1478 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001479 }
1480
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001481 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001482 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001483 return TC_Success;
1484}
1485
1486/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1487/// C++ 5.2.9p9 is valid:
1488///
1489/// An rvalue of type "pointer to member of D of type cv1 T" can be
1490/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1491/// where B is a base class of D [...].
1492///
1493TryCastResult
Fangrui Song6907ce22018-07-30 19:24:48 +00001494TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1495 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001496 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001497 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001498 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001499 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001500 if (!DestMemPtr)
1501 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001502
1503 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001504 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001505 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001506 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001507 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001508 FoundOverload)) {
1509 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1510 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1511 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1512 WasOverloadedFunction = true;
1513 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001514 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001515
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001516 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001517 if (!SrcMemPtr) {
1518 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1519 return TC_NotApplicable;
1520 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001521
1522 // Lock down the inheritance model right now in MS ABI, whether or not the
1523 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001524 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001525 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001526 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1527 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001528
1529 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001530 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1531 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001532 return TC_NotApplicable;
1533
1534 // B base of D
1535 QualType SrcClass(SrcMemPtr->getClass(), 0);
1536 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001537 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001538 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001539 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001540 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001541
1542 // 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 +00001543 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001544 Paths.clear();
1545 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001546 bool StillOkay =
1547 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001548 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001549 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001550 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1551 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1552 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1553 msg = 0;
1554 return TC_Failed;
1555 }
1556
1557 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1558 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1559 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1560 msg = 0;
1561 return TC_Failed;
1562 }
1563
John McCallfe9cf0a2011-02-14 23:21:33 +00001564 if (!CStyle) {
1565 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1566 DestClass, SrcClass,
1567 Paths.front(),
1568 diag::err_upcast_to_inaccessible_base)) {
1569 case Sema::AR_accessible:
1570 case Sema::AR_delayed:
1571 case Sema::AR_dependent:
1572 // Optimistically assume that the delayed and dependent cases
1573 // will work out.
1574 break;
1575
1576 case Sema::AR_inaccessible:
1577 msg = 0;
1578 return TC_Failed;
1579 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001580 }
1581
Douglas Gregorc934bc82010-03-07 23:24:59 +00001582 if (WasOverloadedFunction) {
1583 // Resolve the address of the overloaded function again, this time
1584 // allowing complaints if something goes wrong.
Fangrui Song6907ce22018-07-30 19:24:48 +00001585 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1586 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001587 true,
1588 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001589 if (!Fn) {
1590 msg = 0;
1591 return TC_Failed;
1592 }
1593
John McCall16df1e52010-03-30 21:47:33 +00001594 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001595 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001596 msg = 0;
1597 return TC_Failed;
1598 }
1599 }
1600
Anders Carlssonb78feca2010-04-24 19:22:20 +00001601 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001602 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001603 return TC_Success;
1604}
1605
1606/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1607/// is valid:
1608///
1609/// An expression e can be explicitly converted to a type T using a
1610/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1611TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001612TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Fangrui Song6907ce22018-07-30 19:24:48 +00001613 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001614 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001615 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001616 if (DestType->isRecordType()) {
1617 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001618 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001619 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001620 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001621 msg = 0;
1622 return TC_Failed;
1623 }
1624 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001625
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001626 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1627 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001628 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001629 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001630 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001631 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001632 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001633 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001634 Expr *SrcExprRaw = SrcExpr.get();
Richard Smithb8c0f552016-12-09 18:49:13 +00001635 // FIXME: Per DR242, we should check for an implicit conversion sequence
1636 // or for a constructor that could be invoked by direct-initialization
1637 // here, not for an initialization sequence.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001638 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001639
1640 // At this point of CheckStaticCast, if the destination is a reference,
Fangrui Song6907ce22018-07-30 19:24:48 +00001641 // or the expression is an overload expression this has to work.
Douglas Gregore81f58e2010-11-08 03:40:48 +00001642 // There is no other way that works.
1643 // On the other hand, if we're checking a C-style cast, we've still got
1644 // the reinterpret_cast way.
Fangrui Song6907ce22018-07-30 19:24:48 +00001645 bool CStyle
John McCall31168b02011-06-15 23:02:42 +00001646 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001647 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001648 return TC_NotApplicable;
Fangrui Song6907ce22018-07-30 19:24:48 +00001649
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001650 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001651 if (Result.isInvalid()) {
1652 msg = 0;
1653 return TC_Failed;
1654 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001655
Douglas Gregorb33eed02010-04-16 22:09:46 +00001656 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001657 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001658 else
John McCalle3027922010-08-25 11:45:40 +00001659 Kind = CK_NoOp;
Fangrui Song6907ce22018-07-30 19:24:48 +00001660
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001661 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001662 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001663}
1664
1665/// TryConstCast - See if a const_cast from source to destination is allowed,
1666/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001667static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1668 QualType DestType, bool CStyle,
1669 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001670 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001671 QualType SrcType = SrcExpr.get()->getType();
1672 bool NeedToMaterializeTemporary = false;
1673
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001674 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001675 // C++11 5.2.11p4:
1676 // if a pointer to T1 can be explicitly converted to the type "pointer to
1677 // T2" using a const_cast, then the following conversions can also be
1678 // made:
1679 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1680 // type T2 using the cast const_cast<T2&>;
1681 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1682 // type T2 using the cast const_cast<T2&&>; and
1683 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1684 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1685
1686 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001687 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1688 // is C-style, static_cast might find a way, so we simply suggest a
1689 // message and tell the parent to keep searching.
1690 msg = diag::err_bad_cxx_cast_rvalue;
1691 return TC_NotApplicable;
1692 }
1693
Richard Smith82c9b512013-06-14 22:27:52 +00001694 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1695 if (!SrcType->isRecordType()) {
1696 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1697 // this is C-style, static_cast can do this.
1698 msg = diag::err_bad_cxx_cast_rvalue;
1699 return TC_NotApplicable;
1700 }
1701
1702 // Materialize the class prvalue so that the const_cast can bind a
1703 // reference to it.
1704 NeedToMaterializeTemporary = true;
1705 }
1706
John McCalld25db7e2013-05-06 21:39:12 +00001707 // It's not completely clear under the standard whether we can
1708 // const_cast bit-field gl-values. Doing so would not be
1709 // intrinsically complicated, but for now, we say no for
1710 // consistency with other compilers and await the word of the
1711 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001712 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001713 msg = diag::err_bad_cxx_cast_bitfield;
1714 return TC_NotApplicable;
1715 }
1716
Sebastian Redl9f831db2009-07-25 15:41:38 +00001717 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1718 SrcType = Self.Context.getPointerType(SrcType);
1719 }
1720
1721 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1722 // the rules for const_cast are the same as those used for pointers.
1723
John McCall0e704f72010-05-18 09:35:29 +00001724 if (!DestType->isPointerType() &&
1725 !DestType->isMemberPointerType() &&
1726 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001727 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1728 // was a reference type, we converted it to a pointer above.
1729 // The status of rvalue references isn't entirely clear, but it looks like
1730 // conversion to them is simply invalid.
1731 // C++ 5.2.11p3: For two pointer types [...]
1732 if (!CStyle)
1733 msg = diag::err_bad_const_cast_dest;
1734 return TC_NotApplicable;
1735 }
1736 if (DestType->isFunctionPointerType() ||
1737 DestType->isMemberFunctionPointerType()) {
1738 // Cannot cast direct function pointers.
1739 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1740 // T is the ultimate pointee of source and target type.
1741 if (!CStyle)
1742 msg = diag::err_bad_const_cast_dest;
1743 return TC_NotApplicable;
1744 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001745
Richard Smitha3405ff2018-07-11 00:19:19 +00001746 // C++ [expr.const.cast]p3:
1747 // "For two similar types T1 and T2, [...]"
1748 //
1749 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1750 // type qualifiers. (Likewise, we ignore other changes when determining
1751 // whether a cast casts away constness.)
1752 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001753 return TC_NotApplicable;
1754
Richard Smith82c9b512013-06-14 22:27:52 +00001755 if (NeedToMaterializeTemporary)
1756 // This is a const_cast from a class prvalue to an rvalue reference type.
1757 // Materialize a temporary to store the result of the conversion.
Richard Smithb8c0f552016-12-09 18:49:13 +00001758 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1759 SrcExpr.get(),
Tim Shen4a05bb82016-06-21 20:29:17 +00001760 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001761
Sebastian Redl9f831db2009-07-25 15:41:38 +00001762 return TC_Success;
1763}
1764
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001765// Checks for undefined behavior in reinterpret_cast.
1766// The cases that is checked for is:
1767// *reinterpret_cast<T*>(&a)
1768// reinterpret_cast<T&>(a)
1769// where accessing 'a' as type 'T' will result in undefined behavior.
1770void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1771 bool IsDereference,
1772 SourceRange Range) {
1773 unsigned DiagID = IsDereference ?
1774 diag::warn_pointer_indirection_from_incompatible_type :
1775 diag::warn_undefined_reinterpret_cast;
1776
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001777 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001778 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001779
1780 QualType SrcTy, DestTy;
1781 if (IsDereference) {
1782 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1783 return;
1784 }
1785 SrcTy = SrcType->getPointeeType();
1786 DestTy = DestType->getPointeeType();
1787 } else {
1788 if (!DestType->getAs<ReferenceType>()) {
1789 return;
1790 }
1791 SrcTy = SrcType;
1792 DestTy = DestType->getPointeeType();
1793 }
1794
1795 // Cast is compatible if the types are the same.
1796 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1797 return;
1798 }
1799 // or one of the types is a char or void type
1800 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1801 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1802 return;
1803 }
1804 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001805 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001806 return;
1807 }
1808
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001809 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001810 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1811 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1812 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1813 return;
1814 }
1815 }
1816
1817 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1818}
Douglas Gregor1beec452011-03-12 01:48:56 +00001819
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001820static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1821 QualType DestType) {
1822 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001823 if (Self.Context.hasSameType(SrcType, DestType))
1824 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001825 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1826 if (SrcPtrTy->isObjCSelType()) {
1827 QualType DT = DestType;
1828 if (isa<PointerType>(DestType))
1829 DT = DestType->getPointeeType();
1830 if (!DT.getUnqualifiedType()->isVoidType())
1831 Self.Diag(SrcExpr.get()->getExprLoc(),
1832 diag::warn_cast_pointer_from_sel)
1833 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1834 }
1835}
1836
Reid Kleckner9f497332016-05-10 21:00:03 +00001837/// Diagnose casts that change the calling convention of a pointer to a function
1838/// defined in the current TU.
1839static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1840 QualType DstType, SourceRange OpRange) {
1841 // Check if this cast would change the calling convention of a function
1842 // pointer type.
1843 QualType SrcType = SrcExpr.get()->getType();
1844 if (Self.Context.hasSameType(SrcType, DstType) ||
1845 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1846 return;
1847 const auto *SrcFTy =
1848 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1849 const auto *DstFTy =
1850 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1851 CallingConv SrcCC = SrcFTy->getCallConv();
1852 CallingConv DstCC = DstFTy->getCallConv();
1853 if (SrcCC == DstCC)
1854 return;
1855
1856 // We have a calling convention cast. Check if the source is a pointer to a
1857 // known, specific function that has already been defined.
1858 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1859 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1860 if (UO->getOpcode() == UO_AddrOf)
1861 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1862 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1863 if (!DRE)
1864 return;
1865 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Reid Kleckner0b009e82017-01-31 19:37:45 +00001866 if (!FD)
Reid Kleckner9f497332016-05-10 21:00:03 +00001867 return;
1868
Reid Kleckner43be52a2016-05-11 17:43:13 +00001869 // Only warn if we are casting from the default convention to a non-default
1870 // convention. This can happen when the programmer forgot to apply the calling
Reid Kleckner0b009e82017-01-31 19:37:45 +00001871 // convention to the function declaration and then inserted this cast to
Reid Kleckner43be52a2016-05-11 17:43:13 +00001872 // satisfy the type system.
1873 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1874 FD->isVariadic(), FD->isCXXInstanceMember());
1875 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1876 return;
1877
Reid Kleckner9f497332016-05-10 21:00:03 +00001878 // Diagnose this cast, as it is probably bad.
1879 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1880 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1881 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1882 << SrcCCName << DstCCName << OpRange;
1883
1884 // The checks above are cheaper than checking if the diagnostic is enabled.
1885 // However, it's worth checking if the warning is enabled before we construct
1886 // a fixit.
1887 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1888 return;
1889
1890 // Try to suggest a fixit to change the calling convention of the function
1891 // whose address was taken. Try to use the latest macro for the convention.
1892 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1893 // to match the Windows header declarations.
Reid Kleckner0b009e82017-01-31 19:37:45 +00001894 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
Reid Kleckner9f497332016-05-10 21:00:03 +00001895 Preprocessor &PP = Self.getPreprocessor();
1896 SmallVector<TokenValue, 6> AttrTokens;
1897 SmallString<64> CCAttrText;
1898 llvm::raw_svector_ostream OS(CCAttrText);
1899 if (Self.getLangOpts().MicrosoftExt) {
1900 // __stdcall or __vectorcall
1901 OS << "__" << DstCCName;
1902 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1903 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1904 ? TokenValue(II->getTokenID())
1905 : TokenValue(II));
1906 } else {
1907 // __attribute__((stdcall)) or __attribute__((vectorcall))
1908 OS << "__attribute__((" << DstCCName << "))";
1909 AttrTokens.push_back(tok::kw___attribute);
1910 AttrTokens.push_back(tok::l_paren);
1911 AttrTokens.push_back(tok::l_paren);
1912 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1913 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1914 ? TokenValue(II->getTokenID())
1915 : TokenValue(II));
1916 AttrTokens.push_back(tok::r_paren);
1917 AttrTokens.push_back(tok::r_paren);
1918 }
1919 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1920 if (!AttrSpelling.empty())
1921 CCAttrText = AttrSpelling;
1922 OS << ' ';
1923 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1924 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1925}
1926
David Blaikie282ad872012-10-16 18:53:14 +00001927static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1928 const Expr *SrcExpr, QualType DestType,
1929 Sema &Self) {
1930 QualType SrcType = SrcExpr->getType();
1931
1932 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1933 // are not explicit design choices, but consistent with GCC's behavior.
1934 // Feel free to modify them if you've reason/evidence for an alternative.
1935 if (CStyle && SrcType->isIntegralType(Self.Context)
1936 && !SrcType->isBooleanType()
1937 && !SrcType->isEnumeralType()
1938 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001939 && Self.Context.getTypeSize(DestType) >
1940 Self.Context.getTypeSize(SrcType)) {
1941 // Separate between casts to void* and non-void* pointers.
1942 // Some APIs use (abuse) void* for something like a user context,
1943 // and often that value is an integer even if it isn't a pointer itself.
1944 // Having a separate warning flag allows users to control the warning
1945 // for their workflow.
1946 unsigned Diag = DestType->isVoidPointerType() ?
1947 diag::warn_int_to_void_pointer_cast
1948 : diag::warn_int_to_pointer_cast;
1949 Self.Diag(Loc, Diag) << SrcType << DestType;
1950 }
David Blaikie282ad872012-10-16 18:53:14 +00001951}
1952
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001953static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1954 ExprResult &Result) {
1955 // We can only fix an overloaded reinterpret_cast if
1956 // - it is a template with explicit arguments that resolves to an lvalue
1957 // unambiguously, or
1958 // - it is the only function in an overload set that may have its address
1959 // taken.
1960
1961 Expr *E = Result.get();
1962 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1963 // like it?
1964 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1965 Result,
1966 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1967 ) &&
1968 Result.isUsable())
1969 return true;
1970
George Burgess IVbeca4a32016-06-08 00:34:22 +00001971 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1972 // preserves Result.
1973 Result = E;
George Burgess IV1dbfa852017-05-09 04:06:24 +00001974 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1975 Result, /*DoFunctionPointerConversion=*/true))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001976 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00001977 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001978}
1979
John Wiegley01296292011-04-08 18:41:53 +00001980static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001981 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001982 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001983 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001984 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001985 bool IsLValueCast = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001986
Sebastian Redl9f831db2009-07-25 15:41:38 +00001987 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001988 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001989
1990 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001991 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001992 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001993 ExprResult FixedExpr = SrcExpr;
1994 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001995 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001996
1997 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1998 SrcExpr = FixedExpr;
1999 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00002000 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00002001
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002002 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00002003 if (!SrcExpr.get()->isGLValue()) {
2004 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2005 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00002006 msg = diag::err_bad_cxx_cast_rvalue;
2007 return TC_NotApplicable;
2008 }
2009
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00002010 if (!CStyle) {
2011 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2012 /*isDereference=*/false, OpRange);
2013 }
2014
Sebastian Redl9f831db2009-07-25 15:41:38 +00002015 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2016 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2017 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002018
Craig Topperc3ec1492014-05-26 06:22:03 +00002019 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002020 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00002021 case OK_Ordinary:
2022 break;
Richard Smithb8c0f552016-12-09 18:49:13 +00002023 case OK_BitField:
2024 msg = diag::err_bad_cxx_cast_bitfield;
2025 return TC_NotApplicable;
2026 // FIXME: Use a specific diagnostic for the rest of these cases.
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002027 case OK_VectorComponent: inappropriate = "vector element"; break;
2028 case OK_ObjCProperty: inappropriate = "property expression"; break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002029 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
Ted Kremeneke65b0862012-03-06 20:05:56 +00002030 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002031 }
2032 if (inappropriate) {
2033 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2034 << inappropriate << DestType
2035 << OpRange << SrcExpr.get()->getSourceRange();
2036 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002037 return TC_NotApplicable;
2038 }
2039
Sebastian Redl9f831db2009-07-25 15:41:38 +00002040 // This code does this transformation for the checked types.
2041 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2042 SrcType = Self.Context.getPointerType(SrcType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002043
Douglas Gregor51954272010-07-13 23:17:26 +00002044 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002045 }
2046
2047 // Canonicalize source for comparison.
2048 SrcType = Self.Context.getCanonicalType(SrcType);
2049
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002050 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2051 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002052 if (DestMemPtr && SrcMemPtr) {
2053 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2054 // can be explicitly converted to an rvalue of type "pointer to member
2055 // of Y of type T2" if T1 and T2 are both function types or both object
2056 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00002057 if (DestMemPtr->isMemberFunctionPointer() !=
2058 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00002059 return TC_NotApplicable;
2060
David Majnemer1cdd96d2014-01-17 09:01:00 +00002061 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2062 // We need to determine the inheritance model that the class will use if
2063 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00002064 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2065 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00002066 }
2067
Charles Davisebab1ed2010-08-16 05:30:44 +00002068 // Don't allow casting between member pointers of different sizes.
2069 if (Self.Context.getTypeSize(DestMemPtr) !=
2070 Self.Context.getTypeSize(SrcMemPtr)) {
2071 msg = diag::err_bad_cxx_cast_member_pointer_size;
2072 return TC_Failed;
2073 }
2074
Richard Smithf276e2d2018-07-10 23:04:35 +00002075 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2076 // constness.
2077 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2078 // we accept it.
2079 if (auto CACK =
2080 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2081 /*CheckObjCLifetime=*/CStyle))
2082 return getCastAwayConstnessCastKind(CACK, msg);
2083
Sebastian Redl9f831db2009-07-25 15:41:38 +00002084 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00002085 assert(!IsLValueCast);
2086 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002087 return TC_Success;
2088 }
2089
2090 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00002091 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002092 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2093 // type large enough to hold it. A value of std::nullptr_t can be
2094 // converted to an integral type; the conversion has the same meaning
2095 // and validity as a conversion of (void*)0 to the integral type.
2096 if (Self.Context.getTypeSize(SrcType) >
2097 Self.Context.getTypeSize(DestType)) {
2098 msg = diag::err_bad_reinterpret_cast_small_int;
2099 return TC_Failed;
2100 }
John McCalle3027922010-08-25 11:45:40 +00002101 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002102 return TC_Success;
2103 }
2104
John McCall1c78f082015-07-23 23:54:07 +00002105 // Allow reinterpret_casts between vectors of the same size and
2106 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00002107 bool destIsVector = DestType->isVectorType();
2108 bool srcIsVector = SrcType->isVectorType();
2109 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00002110 // The non-vector type, if any, must have integral type. This is
2111 // the same rule that C vector casts use; note, however, that enum
2112 // types are not integral in C++.
2113 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2114 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002115 return TC_NotApplicable;
2116
John McCall1c78f082015-07-23 23:54:07 +00002117 // The size we want to consider is eltCount * eltSize.
2118 // That's exactly what the lax-conversion rules will check.
2119 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002120 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002121 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002122 }
John McCall1c78f082015-07-23 23:54:07 +00002123
2124 // Otherwise, pick a reasonable diagnostic.
2125 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002126 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002127 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002128 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2129 else
2130 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
Fangrui Song6907ce22018-07-30 19:24:48 +00002131
Anders Carlsson570af5d2009-09-16 19:19:43 +00002132 return TC_Failed;
2133 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002134
2135 if (SrcType == DestType) {
2136 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2137 // restrictions, a cast to the same type is allowed so long as it does not
Fangrui Song6907ce22018-07-30 19:24:48 +00002138 // cast away constness. In C++98, the intent was not entirely clear here,
Chad Rosier96c755d12012-02-03 02:54:37 +00002139 // since all other paragraphs explicitly forbid casts to the same type.
2140 // C++11 clarifies this case with p2.
2141 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002142 // The only allowed types are: integral, enumeration, pointer, or
Chad Rosier96c755d12012-02-03 02:54:37 +00002143 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2144 Kind = CK_NoOp;
2145 TryCastResult Result = TC_NotApplicable;
2146 if (SrcType->isIntegralOrEnumerationType() ||
2147 SrcType->isAnyPointerType() ||
2148 SrcType->isMemberPointerType() ||
2149 SrcType->isBlockPointerType()) {
2150 Result = TC_Success;
2151 }
2152 return Result;
2153 }
2154
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002155 bool destIsPtr = DestType->isAnyPointerType() ||
2156 DestType->isBlockPointerType();
2157 bool srcIsPtr = SrcType->isAnyPointerType() ||
2158 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002159 if (!destIsPtr && !srcIsPtr) {
2160 // Except for std::nullptr_t->integer and lvalue->reference, which are
2161 // handled above, at least one of the two arguments must be a pointer.
2162 return TC_NotApplicable;
2163 }
2164
Douglas Gregor6972a622010-06-16 00:35:25 +00002165 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002166 assert(srcIsPtr && "One type must be a pointer");
2167 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002168 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002169 // integral type size doesn't matter (except we don't allow bool).
2170 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2171 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002172 if ((Self.Context.getTypeSize(SrcType) >
2173 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002174 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002175 msg = diag::err_bad_reinterpret_cast_small_int;
2176 return TC_Failed;
2177 }
John McCalle3027922010-08-25 11:45:40 +00002178 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002179 return TC_Success;
2180 }
2181
Douglas Gregorb90df602010-06-16 00:17:44 +00002182 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002183 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002184 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2185 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002186 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2187 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002188 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2189 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002190 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002191 return TC_Success;
2192 }
2193
2194 if (!destIsPtr || !srcIsPtr) {
2195 // With the valid non-pointer conversions out of the way, we can be even
2196 // more stringent.
2197 return TC_NotApplicable;
2198 }
2199
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002200 // Cannot convert between block pointers and Objective-C object pointers.
2201 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2202 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2203 return TC_NotApplicable;
2204
Richard Smithf276e2d2018-07-10 23:04:35 +00002205 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2206 // The C-style cast operator can.
2207 TryCastResult SuccessResult = TC_Success;
2208 if (auto CACK =
2209 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2210 /*CheckObjCLifetime=*/CStyle))
2211 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2212
John McCall9320b872011-09-09 05:25:32 +00002213 if (IsLValueCast) {
2214 Kind = CK_LValueBitCast;
2215 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002216 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002217 } else if (DestType->isBlockPointerType()) {
2218 if (!SrcType->isBlockPointerType()) {
2219 Kind = CK_AnyPointerToBlockPointerCast;
2220 } else {
2221 Kind = CK_BitCast;
2222 }
Yaxun Liu99a9f752018-07-20 11:32:51 +00002223 } else if (IsAddressSpaceConversion(SrcType, DestType)) {
2224 Kind = CK_AddressSpaceConversion;
John McCall9320b872011-09-09 05:25:32 +00002225 } else {
2226 Kind = CK_BitCast;
2227 }
2228
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002229 // Any pointer can be cast to an Objective-C pointer type with a C-style
2230 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002231 if (CStyle && DestType->isObjCObjectPointerType()) {
Richard Smithf276e2d2018-07-10 23:04:35 +00002232 return SuccessResult;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002233 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002234 if (CStyle)
2235 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002236
2237 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2238
Sebastian Redl9f831db2009-07-25 15:41:38 +00002239 // Not casting away constness, so the only remaining check is for compatible
2240 // pointer categories.
2241
2242 if (SrcType->isFunctionPointerType()) {
2243 if (DestType->isFunctionPointerType()) {
2244 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2245 // a pointer to a function of a different type.
Richard Smithf276e2d2018-07-10 23:04:35 +00002246 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002247 }
2248
2249 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2250 // an object type or vice versa is conditionally-supported.
2251 // Compilers support it in C++03 too, though, because it's necessary for
2252 // casting the return value of dlsym() and GetProcAddress().
2253 // FIXME: Conditionally-supported behavior should be configurable in the
2254 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002255 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002256 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002257 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2258 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002259 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002260 }
2261
2262 if (DestType->isFunctionPointerType()) {
2263 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002264 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002265 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002266 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2267 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002268 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002270
Sebastian Redl9f831db2009-07-25 15:41:38 +00002271 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2272 // a pointer to an object of different type.
2273 // Void pointers are not specified, but supported by every compiler out there.
2274 // So we finish by allowing everything that remains - it's got to be two
2275 // object pointers.
Richard Smithf276e2d2018-07-10 23:04:35 +00002276 return SuccessResult;
2277}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002278
Sebastian Redld74dd492012-02-12 18:41:05 +00002279void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2280 bool ListInitialization) {
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002281 assert(Self.getLangOpts().CPlusPlus);
2282
John McCall9776e432011-10-06 23:25:11 +00002283 // Handle placeholders.
2284 if (isPlaceholder()) {
2285 // C-style casts can resolve __unknown_any types.
2286 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2287 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2288 SrcExpr.get(), Kind,
2289 ValueKind, BasePath);
2290 return;
2291 }
John McCallb50451a2011-10-05 07:41:44 +00002292
John McCall9776e432011-10-06 23:25:11 +00002293 checkNonOverloadPlaceholders();
2294 if (SrcExpr.isInvalid())
2295 return;
John McCalla072f5d2011-10-17 17:42:19 +00002296 }
John McCall9776e432011-10-06 23:25:11 +00002297
2298 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002299 // This test is outside everything else because it's the only case where
2300 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002301 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002302 Kind = CK_ToVoid;
2303
John McCall9776e432011-10-06 23:25:11 +00002304 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002305 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
Fangrui Song6907ce22018-07-30 19:24:48 +00002306 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002307 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002308 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002309 if (SrcExpr.isInvalid())
2310 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002311 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002312
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002313 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002314 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002315 }
2316
Sebastian Redl9f831db2009-07-25 15:41:38 +00002317 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002318 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2319 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002320 assert(Kind == CK_Dependent);
2321 return;
John McCall8cb679e2010-11-15 09:13:47 +00002322 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002323
John McCall50a2c2c2011-10-11 23:14:30 +00002324 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2325 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002326 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002327 if (SrcExpr.isInvalid())
2328 return;
John Wiegley01296292011-04-08 18:41:53 +00002329 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002330
John McCall3aef3d82011-04-10 19:13:55 +00002331 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002332 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002333 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002334 && (SrcExpr.get()->getType()->isIntegerType()
2335 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002336 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002337 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002338 return;
John McCall3aef3d82011-04-10 19:13:55 +00002339 }
2340
Sebastian Redl9f831db2009-07-25 15:41:38 +00002341 // C++ [expr.cast]p5: The conversions performed by
2342 // - a const_cast,
2343 // - a static_cast,
2344 // - a static_cast followed by a const_cast,
2345 // - a reinterpret_cast, or
2346 // - a reinterpret_cast followed by a const_cast,
2347 // can be performed using the cast notation of explicit type conversion.
2348 // [...] If a conversion can be interpreted in more than one of the ways
2349 // listed above, the interpretation that appears first in the list is used,
2350 // even if a cast resulting from that interpretation is ill-formed.
2351 // In plain language, this means trying a const_cast ...
2352 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002353 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002354 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002355 if (SrcExpr.isInvalid())
2356 return;
Richard Smithf276e2d2018-07-10 23:04:35 +00002357 if (isValidCast(tcr))
John McCalle3027922010-08-25 11:45:40 +00002358 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002359
John McCall31168b02011-06-15 23:02:42 +00002360 Sema::CheckedConversionKind CCK
2361 = FunctionalStyle? Sema::CCK_FunctionalCast
2362 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002363 if (tcr == TC_NotApplicable) {
2364 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002365 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002366 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002367 if (SrcExpr.isInvalid())
2368 return;
2369
Sebastian Redl9f831db2009-07-25 15:41:38 +00002370 if (tcr == TC_NotApplicable) {
2371 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002372 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2373 OpRange, msg, Kind);
2374 if (SrcExpr.isInvalid())
2375 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002376 }
2377 }
2378
Brian Kelley11352a82017-03-29 18:09:02 +00002379 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
Richard Smithf276e2d2018-07-10 23:04:35 +00002380 isValidCast(tcr))
Brian Kelley11352a82017-03-29 18:09:02 +00002381 checkObjCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002382
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002383 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002384 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002385 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002386 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2387 DestType,
2388 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002389 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002390 if (Fn) {
2391 // If DestType is a function type (not to be confused with the function
2392 // pointer type), it will be possible to resolve the function address,
2393 // but the type cast should be considered as failure.
2394 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2395 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2396 << OE->getName() << DestType << OpRange
2397 << OE->getQualifierLoc().getSourceRange();
2398 Self.NoteAllOverloadCandidates(SrcExpr.get());
2399 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002400 } else {
John McCallb50451a2011-10-05 07:41:44 +00002401 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002402 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002403 }
2404 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002405
Richard Smithf276e2d2018-07-10 23:04:35 +00002406 if (isValidCast(tcr)) {
2407 if (Kind == CK_BitCast)
2408 checkCastAlign();
2409 } else {
John McCallb50451a2011-10-05 07:41:44 +00002410 SrcExpr = ExprError();
Richard Smithf276e2d2018-07-10 23:04:35 +00002411 }
John McCallb50451a2011-10-05 07:41:44 +00002412}
2413
Fangrui Song6907ce22018-07-30 19:24:48 +00002414/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002415/// non-matching type. Such as enum function call to int, int call to
2416/// pointer; etc. Cast to 'void' is an exception.
2417static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2418 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002419 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2420 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002421 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002422
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002423 if (!isa<CallExpr>(SrcExpr.get()))
2424 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002425
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002426 QualType SrcType = SrcExpr.get()->getType();
2427 if (DestType.getUnqualifiedType()->isVoidType())
2428 return;
2429 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2430 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2431 return;
2432 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2433 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2434 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2435 return;
2436 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2437 return;
2438 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2439 return;
2440 if (SrcType->isComplexType() && DestType->isComplexType())
2441 return;
2442 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2443 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002444
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002445 Self.Diag(SrcExpr.get()->getExprLoc(),
2446 diag::warn_bad_function_cast)
2447 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2448}
2449
John McCall9776e432011-10-06 23:25:11 +00002450/// Check the semantics of a C-style cast operation, in C.
2451void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002452 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002453
John McCall4124c492011-10-17 18:40:02 +00002454 // C-style casts can resolve __unknown_any types.
2455 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2456 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2457 SrcExpr.get(), Kind,
2458 ValueKind, BasePath);
2459 return;
2460 }
John McCall9776e432011-10-06 23:25:11 +00002461
2462 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2463 // type needs to be scalar.
2464 if (DestType->isVoidType()) {
2465 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002466 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002467 if (SrcExpr.isInvalid())
2468 return;
2469
2470 // Cast to void allows any expr type.
2471 Kind = CK_ToVoid;
2472 return;
2473 }
2474
George Burgess IV5f21c712015-10-12 19:57:04 +00002475 // Overloads are allowed with C extensions, so we need to support them.
2476 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2477 DeclAccessPair DAP;
2478 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2479 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2480 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2481 else
2482 return;
2483 assert(SrcExpr.isUsable());
2484 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002485 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002486 if (SrcExpr.isInvalid())
2487 return;
2488 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002489
John McCall4124c492011-10-17 18:40:02 +00002490 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002491
Joey Gouly8fc32f02014-01-14 12:47:29 +00002492 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2493 // address space B is illegal.
2494 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2495 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002496 const PointerType *DestPtr = DestType->getAs<PointerType>();
2497 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002498 Self.Diag(OpRange.getBegin(),
2499 diag::err_typecheck_incompatible_address_space)
2500 << SrcType << DestType << Sema::AA_Casting
2501 << SrcExpr.get()->getSourceRange();
2502 SrcExpr = ExprError();
2503 return;
2504 }
2505 }
2506
John McCall9776e432011-10-06 23:25:11 +00002507 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2508 diag::err_typecheck_cast_to_incomplete)) {
2509 SrcExpr = ExprError();
2510 return;
2511 }
2512
2513 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2514 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2515
2516 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2517 // GCC struct/union extension: allow cast to self.
2518 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2519 << DestType << SrcExpr.get()->getSourceRange();
2520 Kind = CK_NoOp;
2521 return;
2522 }
2523
2524 // GCC's cast to union extension.
2525 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2526 RecordDecl *RD = DestRecordTy->getDecl();
John McCallf1ef7962017-08-15 21:42:47 +00002527 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2528 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2529 << SrcExpr.get()->getSourceRange();
2530 Kind = CK_ToUnion;
2531 return;
2532 } else {
John McCall9776e432011-10-06 23:25:11 +00002533 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2534 << SrcType << SrcExpr.get()->getSourceRange();
2535 SrcExpr = ExprError();
2536 return;
2537 }
John McCall9776e432011-10-06 23:25:11 +00002538 }
2539
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002540 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2541 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2542 llvm::APSInt CastInt;
2543 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2544 if (0 == CastInt) {
2545 Kind = CK_ZeroToOCLEvent;
2546 return;
2547 }
2548 Self.Diag(OpRange.getBegin(),
Richard Smithf8812672016-12-02 22:38:31 +00002549 diag::err_opencl_cast_non_zero_to_event_t)
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002550 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2551 SrcExpr = ExprError();
2552 return;
2553 }
2554 }
2555
John McCall9776e432011-10-06 23:25:11 +00002556 // Reject any other conversions to non-scalar types.
2557 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2558 << DestType << SrcExpr.get()->getSourceRange();
2559 SrcExpr = ExprError();
2560 return;
2561 }
2562
2563 // The type we're casting to is known to be a scalar or vector.
2564
2565 // Require the operand to be a scalar or vector.
2566 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2567 Self.Diag(SrcExpr.get()->getExprLoc(),
2568 diag::err_typecheck_expect_scalar_operand)
2569 << SrcType << SrcExpr.get()->getSourceRange();
2570 SrcExpr = ExprError();
2571 return;
2572 }
2573
2574 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002575 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002576 return;
2577 }
2578
2579 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2580 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2581 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2582 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002583 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002584 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2585 SrcExpr = ExprError();
2586 }
2587 return;
2588 }
2589
2590 if (SrcType->isVectorType()) {
2591 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2592 SrcExpr = ExprError();
2593 return;
2594 }
2595
2596 // The source and target types are both scalars, i.e.
2597 // - arithmetic types (fundamental, enum, and complex)
2598 // - all kinds of pointers
2599 // Note that member pointers were filtered out with C++, above.
2600
2601 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2602 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2603 SrcExpr = ExprError();
2604 return;
2605 }
2606
2607 // If either type is a pointer, the other type has to be either an
2608 // integer or a pointer.
2609 if (!DestType->isArithmeticType()) {
2610 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2611 Self.Diag(SrcExpr.get()->getExprLoc(),
2612 diag::err_cast_pointer_from_non_pointer_int)
2613 << SrcType << SrcExpr.get()->getSourceRange();
2614 SrcExpr = ExprError();
2615 return;
2616 }
David Blaikie282ad872012-10-16 18:53:14 +00002617 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2618 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002619 } else if (!SrcType->isArithmeticType()) {
2620 if (!DestType->isIntegralType(Self.Context) &&
2621 DestType->isArithmeticType()) {
2622 Self.Diag(SrcExpr.get()->getLocStart(),
2623 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002624 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002625 SrcExpr = ExprError();
2626 return;
2627 }
2628 }
2629
Yaxun Liu5b746652016-12-18 05:18:55 +00002630 if (Self.getLangOpts().OpenCL &&
2631 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
Joey Goulydd7f4562013-01-23 11:56:20 +00002632 if (DestType->isHalfType()) {
2633 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2634 << DestType << SrcExpr.get()->getSourceRange();
2635 SrcExpr = ExprError();
2636 return;
2637 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002638 }
2639
John McCall9776e432011-10-06 23:25:11 +00002640 // ARC imposes extra restrictions on casts.
Brian Kelley11352a82017-03-29 18:09:02 +00002641 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2642 checkObjCConversion(Sema::CCK_CStyleCast);
John McCall9776e432011-10-06 23:25:11 +00002643 if (SrcExpr.isInvalid())
2644 return;
Brian Kelley11352a82017-03-29 18:09:02 +00002645
2646 const PointerType *CastPtr = DestType->getAs<PointerType>();
2647 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
John McCall9776e432011-10-06 23:25:11 +00002648 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2649 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2650 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00002651 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
John McCall9776e432011-10-06 23:25:11 +00002652 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2653 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002654 Self.Diag(SrcExpr.get()->getLocStart(),
John McCall9776e432011-10-06 23:25:11 +00002655 diag::err_typecheck_incompatible_ownership)
2656 << SrcType << DestType << Sema::AA_Casting
2657 << SrcExpr.get()->getSourceRange();
2658 return;
2659 }
2660 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002661 }
John McCall9776e432011-10-06 23:25:11 +00002662 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002663 Self.Diag(SrcExpr.get()->getLocStart(),
John McCall9776e432011-10-06 23:25:11 +00002664 diag::err_arc_convesion_of_weak_unavailable)
2665 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2666 SrcExpr = ExprError();
2667 return;
2668 }
2669 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002670
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002671 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002672 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002673 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002674 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2675 if (SrcExpr.isInvalid())
2676 return;
2677
2678 if (Kind == CK_BitCast)
2679 checkCastAlign();
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002680}
Roman Divackyd5178012014-11-21 21:03:10 +00002681
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002682/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2683/// const, volatile or both.
2684static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2685 QualType DestType) {
2686 if (SrcExpr.isInvalid())
2687 return;
2688
2689 QualType SrcType = SrcExpr.get()->getType();
2690 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2691 DestType->isLValueReferenceType()))
2692 return;
2693
Roman Divackyd5178012014-11-21 21:03:10 +00002694 QualType TheOffendingSrcType, TheOffendingDestType;
2695 Qualifiers CastAwayQualifiers;
Richard Smithf276e2d2018-07-10 23:04:35 +00002696 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
2697 &TheOffendingSrcType, &TheOffendingDestType,
2698 &CastAwayQualifiers) !=
2699 CastAwayConstnessKind::CACK_Similar)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002700 return;
2701
Richard Smithf276e2d2018-07-10 23:04:35 +00002702 // FIXME: 'restrict' is not properly handled here.
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002703 int qualifiers = -1;
2704 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2705 qualifiers = 0;
2706 } else if (CastAwayQualifiers.hasConst()) {
2707 qualifiers = 1;
2708 } else if (CastAwayQualifiers.hasVolatile()) {
2709 qualifiers = 2;
Roman Divackyd5178012014-11-21 21:03:10 +00002710 }
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002711 // This is a variant of int **x; const int **y = (const int **)x;
2712 if (qualifiers == -1)
2713 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
2714 << SrcType << DestType;
2715 else
2716 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
2717 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
John McCall9776e432011-10-06 23:25:11 +00002718}
2719
2720ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2721 TypeSourceInfo *CastTypeInfo,
2722 SourceLocation RPLoc,
2723 Expr *CastExpr) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002724 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002725 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2726 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2727
David Blaikiebbafb8a2012-03-11 07:00:24 +00002728 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002729 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2730 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002731 } else {
2732 Op.CheckCStyleCast();
2733 }
2734
John McCallb50451a2011-10-05 07:41:44 +00002735 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002736 return ExprError();
2737
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002738 // -Wcast-qual
2739 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2740
John McCall4124c492011-10-17 18:40:02 +00002741 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002742 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002743 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002744}
2745
2746ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
Richard Smith60437622017-02-09 19:17:44 +00002747 QualType Type,
John McCallb50451a2011-10-05 07:41:44 +00002748 SourceLocation LPLoc,
2749 Expr *CastExpr,
2750 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002751 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
Richard Smith60437622017-02-09 19:17:44 +00002752 CastOperation Op(*this, Type, CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002753 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2754 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2755
Sebastian Redl2b80af42012-02-13 19:55:43 +00002756 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002757 if (Op.SrcExpr.isInvalid())
2758 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002759
2760 auto *SubExpr = Op.SrcExpr.get();
2761 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2762 SubExpr = BindExpr->getSubExpr();
2763 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002764 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002765
John McCall4124c492011-10-17 18:40:02 +00002766 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002767 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002768 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002769}