blob: 8c6abc448d977bbf7fdf1cefc3af1ff1b5628992 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00006//
7//===----------------------------------------------------------------------===//
8//
John McCall3cec19f2011-10-11 17:38:55 +00009// This file implements semantic analysis for cast expressions, including
10// 1) C-style casts like '(int) x'
11// 2) C++ functional casts like 'int(x)'
12// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000013//
14//===----------------------------------------------------------------------===//
15
John McCall83024632010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
John McCallcda80832013-03-22 02:58:14 +000021#include "clang/AST/RecordLayout.h"
Anders Carlssond624e162009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer1cdd96d2014-01-17 09:01:00 +000023#include "clang/Basic/TargetInfo.h"
Reid Kleckner9f497332016-05-10 21:00:03 +000024#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000027#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000028using namespace clang;
29
Douglas Gregore81f58e2010-11-08 03:40:48 +000030
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Sebastian Redl9f831db2009-07-25 15:41:38 +000032enum TryCastResult {
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
Richard Smithf276e2d2018-07-10 23:04:35 +000035 TC_Extension, ///< The cast method is appropriate and accepted as a
36 ///< language extension.
Sebastian Redl9f831db2009-07-25 15:41:38 +000037 TC_Failed ///< The cast method is appropriate, but failed. A
38 ///< diagnostic has been emitted.
39};
40
Richard Smithf276e2d2018-07-10 23:04:35 +000041static bool isValidCast(TryCastResult TCR) {
42 return TCR == TC_Success || TCR == TC_Extension;
43}
44
Sebastian Redl9f831db2009-07-25 15:41:38 +000045enum CastType {
46 CT_Const, ///< const_cast
47 CT_Static, ///< static_cast
48 CT_Reinterpret, ///< reinterpret_cast
49 CT_Dynamic, ///< dynamic_cast
50 CT_CStyle, ///< (Type)expr
51 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000052};
53
John McCallb50451a2011-10-05 07:41:44 +000054namespace {
55 struct CastOperation {
56 CastOperation(Sema &S, QualType destType, ExprResult src)
57 : Self(S), SrcExpr(src), DestType(destType),
58 ResultType(destType.getNonLValueExprType(S.Context)),
59 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000060 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000061
62 if (const BuiltinType *placeholder =
63 src.get()->getType()->getAsPlaceholderType()) {
64 PlaceholderKind = placeholder->getKind();
65 } else {
66 PlaceholderKind = (BuiltinType::Kind) 0;
67 }
68 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000069
John McCallb50451a2011-10-05 07:41:44 +000070 Sema &Self;
71 ExprResult SrcExpr;
72 QualType DestType;
73 QualType ResultType;
74 ExprValueKind ValueKind;
75 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000076 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000077 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000078 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000079
John McCallb50451a2011-10-05 07:41:44 +000080 SourceRange OpRange;
81 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000082
John McCall9776e432011-10-06 23:25:11 +000083 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000084 void CheckConstCast();
85 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000086 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000087 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000088 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000089 void CheckCStyleCast();
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000090 void CheckBuiltinBitCast();
John McCall9776e432011-10-06 23:25:11 +000091
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
Anastasia Stulova5325f832018-10-10 16:05:22 +0000134 // Language specific cast restrictions for address spaces.
135 void checkAddressSpaceCast(QualType SrcType, QualType DestType);
136
John McCallb50451a2011-10-05 07:41:44 +0000137 void checkCastAlign() {
138 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
139 }
140
Brian Kelley11352a82017-03-29 18:09:02 +0000141 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
142 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
John McCall4124c492011-10-17 18:40:02 +0000143
John McCallb50451a2011-10-05 07:41:44 +0000144 Expr *src = SrcExpr.get();
Brian Kelley11352a82017-03-29 18:09:02 +0000145 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
146 Sema::ACR_unbridged)
John McCall4124c492011-10-17 18:40:02 +0000147 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000148 SrcExpr = src;
149 }
John McCall9776e432011-10-06 23:25:11 +0000150
151 /// Check for and handle non-overload placeholder expressions.
152 void checkNonOverloadPlaceholders() {
153 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
154 return;
155
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000156 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000157 if (SrcExpr.isInvalid())
158 return;
159 PlaceholderKind = (BuiltinType::Kind) 0;
160 }
John McCallb50451a2011-10-05 07:41:44 +0000161 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000162}
Sebastian Redl842ef522008-11-08 13:00:26 +0000163
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000164static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
165 QualType DestType);
166
Sebastian Redl9f831db2009-07-25 15:41:38 +0000167// The Try functions attempt a specific way of casting. If they succeed, they
168// return TC_Success. If their way of casting is not appropriate for the given
169// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
170// to emit if no other way succeeds. If their way of casting is appropriate but
171// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
172// they emit a specialized diagnostic.
173// All diagnostics returned by these functions must expect the same three
174// arguments:
175// %0: Cast Type (a value from the CastType enumeration)
176// %1: Source Type
177// %2: Destination Type
178static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000179 QualType DestType, bool CStyle,
180 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000181 CXXCastPath &BasePath,
182 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000183static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000184 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000185 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000186 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000187 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000188 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000189static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
190 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000191 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000192 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000193 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000194 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000195static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
196 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000197 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000198 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000199 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000200 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000201 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000202static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000203 QualType SrcType,
204 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000205 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000206 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000207 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000208 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000209
John Wiegley01296292011-04-08 18:41:53 +0000210static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +0000211 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +0000212 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000213 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000214 unsigned &msg, CastKind &Kind,
215 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000216static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +0000217 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +0000218 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000219 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000220 unsigned &msg, CastKind &Kind,
221 CXXCastPath &BasePath,
222 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000223static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
224 QualType DestType, bool CStyle,
225 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000226static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000227 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000228 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000229 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000230 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000231
Douglas Gregorb491ed32011-02-19 21:32:49 +0000232
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000233/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000234ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000235Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000236 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000237 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000238 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000239 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000240
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000241 assert(!D.isInvalidType());
242
243 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
244 if (D.isInvalidType())
245 return ExprError();
246
David Blaikiebbafb8a2012-03-11 07:00:24 +0000247 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000248 // Check that there are no default arguments (C++ only).
249 CheckExtraCXXDefaultArguments(D);
250 }
251
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000252 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000253 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
254 SourceRange(LParenLoc, RParenLoc));
255}
256
John McCalldadc5752010-08-24 06:29:42 +0000257ExprResult
John McCalld377e042010-01-15 19:13:16 +0000258Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000259 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000260 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000261 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000262 QualType DestType = DestTInfo->getType();
263
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000264 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000265 bool TypeDependent =
266 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000267
John McCallb50451a2011-10-05 07:41:44 +0000268 CastOperation Op(*this, DestType, E);
269 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
270 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000271
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000272 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000273 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000274
275 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000276 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000277 Op.CheckConstCast();
278 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000279 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000280 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000281 }
John McCall4124c492011-10-17 18:40:02 +0000282 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000283 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000284 OpLoc, Parens.getEnd(),
285 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000286
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000287 case tok::kw_dynamic_cast: {
Anastasia Stulova46b55fa2019-07-18 10:02:35 +0000288 // dynamic_cast is not supported in C++ for OpenCL.
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000289 if (getLangOpts().OpenCLCPlusPlus) {
290 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
291 << "dynamic_cast");
292 }
293
John Wiegley01296292011-04-08 18:41:53 +0000294 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000295 Op.CheckDynamicCast();
296 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000297 return ExprError();
298 }
John McCall4124c492011-10-17 18:40:02 +0000299 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000300 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000301 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000302 OpLoc, Parens.getEnd(),
303 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000304 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000305 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000306 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000307 Op.CheckReinterpretCast();
308 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000309 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000310 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000311 }
John McCall4124c492011-10-17 18:40:02 +0000312 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000313 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000314 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000315 Parens.getEnd(),
316 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000317 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000318 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000319 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000320 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000321 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000322 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000323 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000324 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000325
John McCall4124c492011-10-17 18:40:02 +0000326 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000327 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000328 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000329 OpLoc, Parens.getEnd(),
330 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000331 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000332 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000333}
334
Erik Pilkingtoneee944e2019-07-02 18:28:13 +0000335ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
336 ExprResult Operand,
337 SourceLocation RParenLoc) {
338 assert(!D.isInvalidType());
339
340 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
341 if (D.isInvalidType())
342 return ExprError();
343
344 return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
345}
346
347ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
348 TypeSourceInfo *TSI, Expr *Operand,
349 SourceLocation RParenLoc) {
350 CastOperation Op(*this, TSI->getType(), Operand);
351 Op.OpRange = SourceRange(KWLoc, RParenLoc);
352 TypeLoc TL = TSI->getTypeLoc();
353 Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
354
355 if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
356 Op.CheckBuiltinBitCast();
357 if (Op.SrcExpr.isInvalid())
358 return ExprError();
359 }
360
361 BuiltinBitCastExpr *BCE =
362 new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
363 Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
364 return Op.complete(BCE);
365}
366
John McCall909acf82011-02-14 18:34:10 +0000367/// Try to diagnose a failed overloaded cast. Returns true if
368/// diagnostics were emitted.
369static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
370 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000371 QualType destType,
372 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000373 switch (CT) {
374 // These cast kinds don't consider user-defined conversions.
375 case CT_Const:
376 case CT_Reinterpret:
377 case CT_Dynamic:
378 return false;
379
380 // These do.
381 case CT_Static:
382 case CT_CStyle:
383 case CT_Functional:
384 break;
385 }
386
387 QualType srcType = src->getType();
388 if (!destType->isRecordType() && !srcType->isRecordType())
389 return false;
390
391 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
392 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000393 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000394 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000395 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000396 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000397 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000398 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000399
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000400 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000401 switch (sequence.getFailureKind()) {
402 default: return false;
403
404 case InitializationSequence::FK_ConstructorOverloadFailed:
405 case InitializationSequence::FK_UserConversionOverloadFailed:
406 break;
407 }
408
409 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
410
411 unsigned msg = 0;
412 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
413
414 switch (sequence.getFailedOverloadResult()) {
415 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000416 case OR_No_Viable_Function:
417 if (candidates.empty())
418 msg = diag::err_ovl_no_conversion_in_cast;
419 else
420 msg = diag::err_ovl_no_viable_conversion_in_cast;
421 howManyCandidates = OCD_AllCandidates;
422 break;
423
424 case OR_Ambiguous:
425 msg = diag::err_ovl_ambiguous_conversion_in_cast;
426 howManyCandidates = OCD_ViableCandidates;
427 break;
428
429 case OR_Deleted:
430 msg = diag::err_ovl_deleted_conversion_in_cast;
431 howManyCandidates = OCD_ViableCandidates;
432 break;
433 }
434
David Blaikie5e328052019-05-03 00:44:50 +0000435 candidates.NoteCandidates(
436 PartialDiagnosticAt(range.getBegin(),
437 S.PDiag(msg) << CT << srcType << destType << range
438 << src->getSourceRange()),
439 S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000440
441 return true;
442}
443
444/// Diagnose a failed cast.
445static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000446 SourceRange opRange, Expr *src, QualType destType,
447 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000448 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000449 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
450 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000451 return;
452
453 S.Diag(opRange.getBegin(), msg) << castType
454 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000455
456 // Detect if both types are (ptr to) class, and note any incompleteness.
457 int DifferentPtrness = 0;
458 QualType From = destType;
459 if (auto Ptr = From->getAs<PointerType>()) {
460 From = Ptr->getPointeeType();
461 DifferentPtrness++;
462 }
463 QualType To = src->getType();
464 if (auto Ptr = To->getAs<PointerType>()) {
465 To = Ptr->getPointeeType();
466 DifferentPtrness--;
467 }
468 if (!DifferentPtrness) {
469 auto RecFrom = From->getAs<RecordType>();
470 auto RecTo = To->getAs<RecordType>();
471 if (RecFrom && RecTo) {
472 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
473 if (!DeclFrom->isCompleteDefinition())
474 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
475 << DeclFrom->getDeclName();
476 auto DeclTo = RecTo->getAsCXXRecordDecl();
477 if (!DeclTo->isCompleteDefinition())
478 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
479 << DeclTo->getDeclName();
480 }
481 }
John McCall909acf82011-02-14 18:34:10 +0000482}
483
Richard Smithf276e2d2018-07-10 23:04:35 +0000484namespace {
485/// The kind of unwrapping we did when determining whether a conversion casts
486/// away constness.
487enum CastAwayConstnessKind {
488 /// The conversion does not cast away constness.
489 CACK_None = 0,
490 /// We unwrapped similar types.
491 CACK_Similar = 1,
492 /// We unwrapped dissimilar types with similar representations (eg, a pointer
493 /// versus an Objective-C object pointer).
494 CACK_SimilarKind = 2,
495 /// We unwrapped representationally-unrelated types, such as a pointer versus
496 /// a pointer-to-member.
497 CACK_Incoherent = 3,
498};
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000499}
500
Richard Smithf276e2d2018-07-10 23:04:35 +0000501/// Unwrap one level of types for CastsAwayConstness.
502///
Richard Smitha3405ff2018-07-11 00:19:19 +0000503/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
504/// both types, provided that they're both pointer-like or array-like. Unlike
505/// the Sema function, doesn't care if the unwrapped pieces are related.
Richard Smith5407d4f2018-07-18 20:13:36 +0000506///
507/// This function may remove additional levels as necessary for correctness:
508/// the resulting T1 is unwrapped sufficiently that it is never an array type,
509/// so that its qualifiers can be directly compared to those of T2 (which will
510/// have the combined set of qualifiers from all indermediate levels of T2),
511/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
512/// with those from T2.
Richard Smithf276e2d2018-07-10 23:04:35 +0000513static CastAwayConstnessKind
514unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000515 enum { None, Ptr, MemPtr, BlockPtr, Array };
Richard Smithf276e2d2018-07-10 23:04:35 +0000516 auto Classify = [](QualType T) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000517 if (T->isAnyPointerType()) return Ptr;
518 if (T->isMemberPointerType()) return MemPtr;
519 if (T->isBlockPointerType()) return BlockPtr;
Richard Smitha3405ff2018-07-11 00:19:19 +0000520 // We somewhat-arbitrarily don't look through VLA types here. This is at
521 // least consistent with the behavior of UnwrapSimilarTypes.
Richard Smith5407d4f2018-07-18 20:13:36 +0000522 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
523 return None;
Richard Smithf276e2d2018-07-10 23:04:35 +0000524 };
525
Richard Smitha3405ff2018-07-11 00:19:19 +0000526 auto Unwrap = [&](QualType T) {
527 if (auto *AT = Context.getAsArrayType(T))
528 return AT->getElementType();
529 return T->getPointeeType();
530 };
531
Richard Smith5407d4f2018-07-18 20:13:36 +0000532 CastAwayConstnessKind Kind;
533
534 if (T2->isReferenceType()) {
535 // Special case: if the destination type is a reference type, unwrap it as
536 // the first level. (The source will have been an lvalue expression in this
537 // case, so there is no corresponding "reference to" in T1 to remove.) This
538 // simulates removing a "pointer to" from both sides.
539 T2 = T2->getPointeeType();
540 Kind = CastAwayConstnessKind::CACK_Similar;
541 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
542 Kind = CastAwayConstnessKind::CACK_Similar;
543 } else {
544 // Try unwrapping mismatching levels.
545 int T1Class = Classify(T1);
546 if (T1Class == None)
547 return CastAwayConstnessKind::CACK_None;
548
549 int T2Class = Classify(T2);
550 if (T2Class == None)
551 return CastAwayConstnessKind::CACK_None;
552
553 T1 = Unwrap(T1);
554 T2 = Unwrap(T2);
555 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
556 : CastAwayConstnessKind::CACK_Incoherent;
557 }
558
559 // We've unwrapped at least one level. If the resulting T1 is a (possibly
560 // multidimensional) array type, any qualifier on any matching layer of
561 // T2 is considered to correspond to T1. Decompose down to the element
562 // type of T1 so that we can compare properly.
563 while (true) {
564 Context.UnwrapSimilarArrayTypes(T1, T2);
565
566 if (Classify(T1) != Array)
567 break;
568
569 auto T2Class = Classify(T2);
570 if (T2Class == None)
571 break;
572
573 if (T2Class != Array)
574 Kind = CastAwayConstnessKind::CACK_Incoherent;
575 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
576 Kind = CastAwayConstnessKind::CACK_SimilarKind;
577
578 T1 = Unwrap(T1);
579 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
580 }
581
582 return Kind;
Richard Smithf276e2d2018-07-10 23:04:35 +0000583}
584
585/// Check if the pointer conversion from SrcType to DestType casts away
586/// constness as defined in C++ [expr.const.cast]. This is used by the cast
587/// checkers. Both arguments must denote pointer (possibly to member) types.
John McCall31168b02011-06-15 23:02:42 +0000588///
589/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
John McCall31168b02011-06-15 23:02:42 +0000590/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Richard Smithf276e2d2018-07-10 23:04:35 +0000591static CastAwayConstnessKind
John McCall31168b02011-06-15 23:02:42 +0000592CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000593 bool CheckCVR, bool CheckObjCLifetime,
594 QualType *TheOffendingSrcType = nullptr,
595 QualType *TheOffendingDestType = nullptr,
596 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000597 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000598 // and we're not in ObjC mode, there's nothing to check.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000599 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
Richard Smithf276e2d2018-07-10 23:04:35 +0000600 return CastAwayConstnessKind::CACK_None;
601
602 if (!DestType->isReferenceType()) {
603 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
604 SrcType->isBlockPointerType()) &&
605 "Source type is not pointer or pointer to member.");
606 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
607 DestType->isBlockPointerType()) &&
608 "Destination type is not pointer or pointer to member.");
609 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000610
Fangrui Song6907ce22018-07-30 19:24:48 +0000611 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000612 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000613
Fangrui Song6907ce22018-07-30 19:24:48 +0000614 // Find the qualifiers. We only care about cvr-qualifiers for the
615 // purpose of this check, because other qualifiers (address spaces,
Douglas Gregorb472e932011-04-15 17:59:54 +0000616 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000617 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
618 QualType PrevUnwrappedDestType = UnwrappedDestType;
Richard Smithf276e2d2018-07-10 23:04:35 +0000619 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
620 bool AllConstSoFar = true;
621 while (auto Kind = unwrapCastAwayConstnessLevel(
622 Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
623 // Track the worst kind of unwrap we needed to do before we found a
624 // problem.
625 if (Kind > WorstKind)
626 WorstKind = Kind;
627
John McCall31168b02011-06-15 23:02:42 +0000628 // Determine the relevant qualifiers at this level.
629 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000630 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000631 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Akira Hatanaka8d7bdf62017-08-11 00:06:49 +0000632
633 // We do not meaningfully track object const-ness of Objective-C object
634 // types. Remove const from the source type if either the source or
635 // the destination is an Objective-C object type.
636 if (UnwrappedSrcType->isObjCObjectType() ||
637 UnwrappedDestType->isObjCObjectType())
638 SrcQuals.removeConst();
639
John McCall31168b02011-06-15 23:02:42 +0000640 if (CheckCVR) {
Richard Smithf276e2d2018-07-10 23:04:35 +0000641 Qualifiers SrcCvrQuals =
642 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
643 Qualifiers DestCvrQuals =
644 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000645
Richard Smithf276e2d2018-07-10 23:04:35 +0000646 if (SrcCvrQuals != DestCvrQuals) {
647 if (CastAwayQualifiers)
648 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
649
650 // If we removed a cvr-qualifier, this is casting away 'constness'.
651 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
652 if (TheOffendingSrcType)
653 *TheOffendingSrcType = PrevUnwrappedSrcType;
654 if (TheOffendingDestType)
655 *TheOffendingDestType = PrevUnwrappedDestType;
656 return WorstKind;
657 }
658
659 // If any prior level was not 'const', this is also casting away
660 // 'constness'. We noted the outermost type missing a 'const' already.
661 if (!AllConstSoFar)
662 return WorstKind;
Roman Divackyd5178012014-11-21 21:03:10 +0000663 }
John McCall31168b02011-06-15 23:02:42 +0000664 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000665
John McCall31168b02011-06-15 23:02:42 +0000666 if (CheckObjCLifetime &&
667 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
Richard Smithf276e2d2018-07-10 23:04:35 +0000668 return WorstKind;
669
670 // If we found our first non-const-qualified type, this may be the place
671 // where things start to go wrong.
672 if (AllConstSoFar && !DestQuals.hasConst()) {
673 AllConstSoFar = false;
674 if (TheOffendingSrcType)
675 *TheOffendingSrcType = PrevUnwrappedSrcType;
676 if (TheOffendingDestType)
677 *TheOffendingDestType = PrevUnwrappedDestType;
678 }
Roman Divackyd5178012014-11-21 21:03:10 +0000679
680 PrevUnwrappedSrcType = UnwrappedSrcType;
681 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000682 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000683
Richard Smithf276e2d2018-07-10 23:04:35 +0000684 return CastAwayConstnessKind::CACK_None;
685}
686
687static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
688 unsigned &DiagID) {
689 switch (CACK) {
690 case CastAwayConstnessKind::CACK_None:
691 llvm_unreachable("did not cast away constness");
692
693 case CastAwayConstnessKind::CACK_Similar:
694 // FIXME: Accept these as an extension too?
695 case CastAwayConstnessKind::CACK_SimilarKind:
696 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
697 return TC_Failed;
698
699 case CastAwayConstnessKind::CACK_Incoherent:
700 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
701 return TC_Extension;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000702 }
703
Richard Smithf276e2d2018-07-10 23:04:35 +0000704 llvm_unreachable("unexpected cast away constness kind");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000705}
706
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000707/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
708/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
709/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000710void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000711 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000712 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000713 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000714 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000715 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
716 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000717
John McCallb50451a2011-10-05 07:41:44 +0000718 QualType OrigSrcType = SrcExpr.get()->getType();
719 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000720
721 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
722 // or "pointer to cv void".
723
724 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000725 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000726 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000727 if (DestPointer) {
728 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000729 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000730 DestPointee = DestReference->getPointeeType();
731 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000732 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000733 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000734 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000735 return;
736 }
737
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000738 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000739 if (DestPointee->isVoidType()) {
740 assert(DestPointer && "Reference to void is not possible");
741 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000742 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000743 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000744 DestRange)) {
745 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000746 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000747 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000748 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000749 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000750 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000751 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000752 return;
753 }
754
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000755 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
756 // complete class type, [...]. If T is an lvalue reference type, v shall be
Fangrui Song6907ce22018-07-30 19:24:48 +0000757 // an lvalue of a complete class type, [...]. If T is an rvalue reference
Douglas Gregor465184a2011-01-22 00:06:57 +0000758 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000759 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000760 QualType SrcPointee;
761 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000762 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000763 SrcPointee = SrcPointer->getPointeeType();
764 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000765 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000766 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000767 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000768 return;
769 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000770 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000771 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000772 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000773 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000774 }
775 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000776 } else {
Richard Smith11330852014-07-08 17:25:14 +0000777 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
778 // to materialize the prvalue before we bind the reference to it.
779 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000780 SrcExpr = Self.CreateMaterializeTemporaryExpr(
781 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000782 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000783 }
784
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000785 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000786 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000787 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000788 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000789 SrcExpr.get())) {
790 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000791 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000792 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000793 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000794 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000795 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000796 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000797 return;
798 }
799
800 assert((DestPointer || DestReference) &&
801 "Bad destination non-ptr/ref slipped through.");
802 assert((DestRecord || DestPointee->isVoidType()) &&
803 "Bad destination pointee slipped through.");
804 assert(SrcRecord && "Bad source pointee slipped through.");
805
806 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
807 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000808 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000809 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000810 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000811 return;
812 }
813
814 // C++ 5.2.7p3: If the type of v is the same as the required result type,
815 // [except for cv].
816 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000817 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000818 return;
819 }
820
821 // C++ 5.2.7p5
822 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000823 if (DestRecord &&
824 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000825 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Fangrui Song6907ce22018-07-30 19:24:48 +0000826 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000827 &BasePath)) {
828 SrcExpr = ExprError();
829 return;
830 }
Richard Smith11330852014-07-08 17:25:14 +0000831
John McCalle3027922010-08-25 11:45:40 +0000832 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000833 return;
834 }
835
836 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000837 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000838 assert(SrcDecl && "Definition missing");
839 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000840 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000841 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000842 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000843 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000844
Eli Friedman3ce27102013-09-24 23:21:41 +0000845 // dynamic_cast is not available with -fno-rtti.
846 // As an exception, dynamic_cast to void* is available because it doesn't
847 // use RTTI.
848 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000849 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
850 SrcExpr = ExprError();
851 return;
852 }
853
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000854 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000855 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000856}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000857
858/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
859/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
860/// like this:
861/// const char *str = "literal";
862/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000863void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000864 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000865 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000866 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000867 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000868 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
869 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000870
871 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smithf276e2d2018-07-10 23:04:35 +0000872 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
873 if (TCR != TC_Success && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000874 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000875 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000876 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000877 if (!isValidCast(TCR))
878 SrcExpr = ExprError();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000879}
880
John McCallcda80832013-03-22 02:58:14 +0000881/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
882/// or downcast between respective pointers or references.
883static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
884 QualType DestType,
885 SourceRange OpRange) {
886 QualType SrcType = SrcExpr->getType();
887 // When casting from pointer or reference, get pointee type; use original
888 // type otherwise.
889 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
890 const CXXRecordDecl *SrcRD =
891 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
892
John McCallf2abe192013-03-27 00:03:48 +0000893 // Examining subobjects for records is only possible if the complete and
894 // valid definition is available. Also, template instantiation is not
895 // allowed here.
896 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000897 return;
898
899 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
900
John McCallf2abe192013-03-27 00:03:48 +0000901 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000902 return;
903
904 enum {
905 ReinterpretUpcast,
906 ReinterpretDowncast
907 } ReinterpretKind;
908
909 CXXBasePaths BasePaths;
910
911 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
912 ReinterpretKind = ReinterpretUpcast;
913 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
914 ReinterpretKind = ReinterpretDowncast;
915 else
916 return;
917
918 bool VirtualBase = true;
919 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000920 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000921 E = BasePaths.end();
922 I != E; ++I) {
923 const CXXBasePath &Path = *I;
924 CharUnits Offset = CharUnits::Zero();
925 bool IsVirtual = false;
926 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
927 IElem != EElem; ++IElem) {
928 IsVirtual = IElem->Base->isVirtual();
929 if (IsVirtual)
930 break;
931 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
932 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000933 // Don't check if any base has invalid declaration or has no definition
934 // since it has no layout info.
935 const CXXRecordDecl *Class = IElem->Class,
936 *ClassDefinition = Class->getDefinition();
937 if (Class->isInvalidDecl() || !ClassDefinition ||
938 !ClassDefinition->isCompleteDefinition())
939 return;
940
John McCallcda80832013-03-22 02:58:14 +0000941 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000942 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000943 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
944 }
945 if (!IsVirtual) {
946 // Don't warn if any path is a non-virtually derived base at offset zero.
947 if (Offset.isZero())
948 return;
949 // Offset makes sense only for non-virtual bases.
950 else
951 NonZeroOffset = true;
952 }
953 VirtualBase = VirtualBase && IsVirtual;
954 }
955
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000956 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000957 assert((VirtualBase || NonZeroOffset) &&
958 "Should have returned if has non-virtual base with zero offset");
959
960 QualType BaseType =
961 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
962 QualType DerivedType =
963 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
964
Jordan Rose04a94d12013-03-28 19:09:40 +0000965 SourceLocation BeginLoc = OpRange.getBegin();
966 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000967 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000968 << OpRange;
969 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000970 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000971 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000972}
973
Sebastian Redl9f831db2009-07-25 15:41:38 +0000974/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
975/// valid.
976/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
977/// like this:
978/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000979void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000980 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000981 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000982 else
983 checkNonOverloadPlaceholders();
984 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
985 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000986
987 unsigned msg = diag::err_bad_cxx_cast_generic;
Fangrui Song6907ce22018-07-30 19:24:48 +0000988 TryCastResult tcr =
989 TryReinterpretCast(Self, SrcExpr, DestType,
John McCall31168b02011-06-15 23:02:42 +0000990 /*CStyle*/false, OpRange, msg, Kind);
Richard Smithf276e2d2018-07-10 23:04:35 +0000991 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000992 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
993 return;
994 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000995 //FIXME: &f<int>; is overloaded and resolvable
996 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000997 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000998 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000999 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +00001000
John McCall909acf82011-02-14 18:34:10 +00001001 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +00001002 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
1003 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001004 }
Richard Smithf276e2d2018-07-10 23:04:35 +00001005 }
1006
1007 if (isValidCast(tcr)) {
Brian Kelley762f9282017-03-29 18:16:38 +00001008 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +00001009 checkObjCConversion(Sema::CCK_OtherCast);
John McCallcda80832013-03-22 02:58:14 +00001010 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
Richard Smithf276e2d2018-07-10 23:04:35 +00001011 } else {
1012 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +00001013 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001014}
1015
1016
1017/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1018/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1019/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +00001020void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +00001021 if (isPlaceholder()) {
1022 checkNonOverloadPlaceholders();
1023 if (SrcExpr.isInvalid())
1024 return;
1025 }
1026
Sebastian Redl9f831db2009-07-25 15:41:38 +00001027 // This test is outside everything else because it's the only case where
1028 // a non-lvalue-reference target type does not lead to decay.
1029 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +00001030 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +00001031 Kind = CK_ToVoid;
1032
1033 if (claimPlaceholder(BuiltinType::Overload)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001034 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1035 false, // Decay Function to ptr
Douglas Gregorb491ed32011-02-19 21:32:49 +00001036 true, // Complain
1037 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +00001038 if (SrcExpr.isInvalid())
1039 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001040 }
John McCall9776e432011-10-06 23:25:11 +00001041
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001042 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001043 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001044 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045
John McCall50a2c2c2011-10-11 23:14:30 +00001046 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1047 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001048 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00001049 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1050 return;
1051 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001052
1053 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +00001054 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +00001055 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001056 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +00001057 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +00001058 if (SrcExpr.isInvalid())
1059 return;
1060 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1061 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +00001062 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Fangrui Song6907ce22018-07-30 19:24:48 +00001063 << oe->getName() << DestType << OpRange
Douglas Gregor0da1d432011-02-28 20:01:57 +00001064 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00001065 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +00001066 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +00001067 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1068 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001069 }
Richard Smithf276e2d2018-07-10 23:04:35 +00001070 }
1071
1072 if (isValidCast(tcr)) {
John McCall31168b02011-06-15 23:02:42 +00001073 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +00001074 checkCastAlign();
Brian Kelley762f9282017-03-29 18:16:38 +00001075 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +00001076 checkObjCConversion(Sema::CCK_OtherCast);
Richard Smithf276e2d2018-07-10 23:04:35 +00001077 } else {
1078 SrcExpr = ExprError();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001079 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001080}
1081
Yaxun Liu4b06ffe2018-08-03 03:18:56 +00001082static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1083 auto *SrcPtrType = SrcType->getAs<PointerType>();
1084 if (!SrcPtrType)
1085 return false;
1086 auto *DestPtrType = DestType->getAs<PointerType>();
1087 if (!DestPtrType)
1088 return false;
1089 return SrcPtrType->getPointeeType().getAddressSpace() !=
1090 DestPtrType->getPointeeType().getAddressSpace();
1091}
1092
Sebastian Redl9f831db2009-07-25 15:41:38 +00001093/// TryStaticCast - Check if a static cast can be performed, and do so if
1094/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1095/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +00001096static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +00001097 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001098 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001099 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001100 CastKind &Kind, CXXCastPath &BasePath,
1101 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +00001102 // Determine whether we have the semantics of a C-style cast.
Fangrui Song6907ce22018-07-30 19:24:48 +00001103 bool CStyle
John McCall31168b02011-06-15 23:02:42 +00001104 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Fangrui Song6907ce22018-07-30 19:24:48 +00001105
Sebastian Redl9f831db2009-07-25 15:41:38 +00001106 // The order the tests is not entirely arbitrary. There is one conversion
1107 // that can be handled in two different ways. Given:
1108 // struct A {};
1109 // struct B : public A {
1110 // B(); B(const A&);
1111 // };
1112 // const A &a = B();
1113 // the cast static_cast<const B&>(a) could be seen as either a static
1114 // reference downcast, or an explicit invocation of the user-defined
1115 // conversion using B's conversion constructor.
1116 // DR 427 specifies that the downcast is to be applied here.
1117
1118 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1119 // Done outside this function.
1120
1121 TryCastResult tcr;
1122
1123 // C++ 5.2.9p5, reference downcast.
1124 // See the function for details.
1125 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +00001126 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1127 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001128 if (tcr != TC_NotApplicable)
1129 return tcr;
1130
Fangrui Song6907ce22018-07-30 19:24:48 +00001131 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001132 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1133 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001134 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
Sebastian Redld74dd492012-02-12 18:41:05 +00001135 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +00001136 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001137 return tcr;
1138
1139 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1140 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +00001141 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001142 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +00001143 if (SrcExpr.isInvalid())
1144 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001145 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001146 return tcr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001147
Sebastian Redl9f831db2009-07-25 15:41:38 +00001148 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1149 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1150 // conversions, subject to further restrictions.
1151 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1152 // of qualification conversions impossible.
1153 // In the CStyle case, the earlier attempt to const_cast should have taken
1154 // care of reverse qualification conversions.
1155
John Wiegley01296292011-04-08 18:41:53 +00001156 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001157
Douglas Gregor0bf31402010-10-08 23:50:27 +00001158 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001159 // converted to an integral type. [...] A value of a scoped enumeration type
1160 // can also be explicitly converted to a floating-point type [...].
1161 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1162 if (Enum->getDecl()->isScoped()) {
1163 if (DestType->isBooleanType()) {
1164 Kind = CK_IntegralToBoolean;
1165 return TC_Success;
1166 } else if (DestType->isIntegralType(Self.Context)) {
1167 Kind = CK_IntegralCast;
1168 return TC_Success;
1169 } else if (DestType->isRealFloatingType()) {
1170 Kind = CK_IntegralToFloating;
1171 return TC_Success;
1172 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001173 }
1174 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001175
Sebastian Redl9f831db2009-07-25 15:41:38 +00001176 // Reverse integral promotion/conversion. All such conversions are themselves
1177 // again integral promotions or conversions and are thus already handled by
1178 // p2 (TryDirectInitialization above).
1179 // (Note: any data loss warnings should be suppressed.)
1180 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1181 // enum->enum). See also C++ 5.2.9p7.
1182 // The same goes for reverse floating point promotion/conversion and
1183 // floating-integral conversions. Again, only floating->enum is relevant.
1184 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001185 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001186 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001187 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001188 } else if (SrcType->isRealFloatingType()) {
1189 Kind = CK_FloatingToIntegral;
1190 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001191 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001192 }
1193
1194 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1195 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001196 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001197 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001198 if (tcr != TC_NotApplicable)
1199 return tcr;
1200
1201 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1202 // conversion. C++ 5.2.9p9 has additional information.
1203 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001204 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001205 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001206 if (tcr != TC_NotApplicable)
1207 return tcr;
1208
1209 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1210 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1211 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001212 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001213 QualType SrcPointee = SrcPointer->getPointeeType();
1214 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001215 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001216 QualType DestPointee = DestPointer->getPointeeType();
1217 if (DestPointee->isIncompleteOrObjectType()) {
1218 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001219 // to a qualifier violation. Note that we permit Objective-C lifetime
1220 // and GC qualifier mismatches here.
1221 if (!CStyle) {
1222 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1223 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1224 DestPointeeQuals.removeObjCGCAttr();
1225 DestPointeeQuals.removeObjCLifetime();
1226 SrcPointeeQuals.removeObjCGCAttr();
1227 SrcPointeeQuals.removeObjCLifetime();
1228 if (DestPointeeQuals != SrcPointeeQuals &&
1229 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1230 msg = diag::err_bad_cxx_cast_qualifiers_away;
1231 return TC_Failed;
1232 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001233 }
Yaxun Liu4b06ffe2018-08-03 03:18:56 +00001234 Kind = IsAddressSpaceConversion(SrcType, DestType)
1235 ? CK_AddressSpaceConversion
1236 : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001237 return TC_Success;
1238 }
David Majnemer85bd1202015-06-02 22:15:12 +00001239
1240 // Microsoft permits static_cast from 'pointer-to-void' to
1241 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001242 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1243 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001244 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1245 Kind = CK_BitCast;
1246 return TC_Success;
1247 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001248 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001249 else if (DestType->isObjCObjectPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001250 // allow both c-style cast and static_cast of objective-c pointers as
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001251 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001252 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001253 return TC_Success;
1254 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001255 else if (CStyle && DestType->isBlockPointerType()) {
1256 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001257 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001258 return TC_Success;
1259 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001260 }
1261 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001262 // Allow arbitrary objective-c pointer conversion with static casts.
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001263 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001264 DestType->isObjCObjectPointerType()) {
1265 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001266 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001267 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001268 // Allow ns-pointer to cf-pointer conversion in either direction
1269 // with static casts.
1270 if (!CStyle &&
1271 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1272 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001273
1274 // See if it looks like the user is trying to convert between
1275 // related record types, and select a better diagnostic if so.
1276 if (auto SrcPointer = SrcType->getAs<PointerType>())
1277 if (auto DestPointer = DestType->getAs<PointerType>())
1278 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1279 DestPointer->getPointeeType()->getAs<RecordType>())
1280 msg = diag::err_bad_cxx_cast_unrelated_class;
Fangrui Song6907ce22018-07-30 19:24:48 +00001281
Sebastian Redl9f831db2009-07-25 15:41:38 +00001282 // We tried everything. Everything! Nothing works! :-(
1283 return TC_NotApplicable;
1284}
1285
1286/// Tests whether a conversion according to N2844 is valid.
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001287TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1288 QualType DestType, bool CStyle,
1289 CastKind &Kind, CXXCastPath &BasePath,
1290 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001291 // C++11 [expr.static.cast]p3:
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001292 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
Douglas Gregor465184a2011-01-22 00:06:57 +00001293 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001294 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001295 if (!R)
1296 return TC_NotApplicable;
1297
Douglas Gregor465184a2011-01-22 00:06:57 +00001298 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001299 return TC_NotApplicable;
1300
1301 // Because we try the reference downcast before this function, from now on
1302 // this is the only cast possibility, so we issue an error if we fail now.
1303 // FIXME: Should allow casting away constness if CStyle.
1304 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001305 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001306 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001307 QualType FromType = SrcExpr->getType();
1308 QualType ToType = R->getPointeeType();
1309 if (CStyle) {
1310 FromType = FromType.getUnqualifiedType();
1311 ToType = ToType.getUnqualifiedType();
1312 }
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001313
1314 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001315 SrcExpr->getBeginLoc(), ToType, FromType, DerivedToBase, ObjCConversion,
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001316 ObjCLifetimeConversion);
1317 if (RefResult != Sema::Ref_Compatible) {
1318 if (CStyle || RefResult == Sema::Ref_Incompatible)
Davide Italianoa2275912015-07-12 22:10:56 +00001319 return TC_NotApplicable;
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001320 // Diagnose types which are reference-related but not compatible here since
1321 // we can provide better diagnostics. In these cases forwarding to
1322 // [expr.static.cast]p4 should never result in a well-formed cast.
1323 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1324 : diag::err_bad_rvalue_to_rvalue_cast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001325 return TC_Failed;
1326 }
1327
Douglas Gregorba278e22011-01-25 16:13:26 +00001328 if (DerivedToBase) {
1329 Kind = CK_DerivedToBase;
1330 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1331 /*DetectVirtual=*/true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001332 if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
Richard Smith0f59cb32015-12-18 21:45:41 +00001333 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001334 return TC_NotApplicable;
Fangrui Song6907ce22018-07-30 19:24:48 +00001335
Douglas Gregorba278e22011-01-25 16:13:26 +00001336 Self.BuildBasePathArray(Paths, BasePath);
1337 } else
1338 Kind = CK_NoOp;
Fangrui Song6907ce22018-07-30 19:24:48 +00001339
Sebastian Redl9f831db2009-07-25 15:41:38 +00001340 return TC_Success;
1341}
1342
1343/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1344TryCastResult
1345TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001346 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001347 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001348 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001349 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1350 // cast to type "reference to cv2 D", where D is a class derived from B,
1351 // if a valid standard conversion from "pointer to D" to "pointer to B"
1352 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1353 // In addition, DR54 clarifies that the base must be accessible in the
1354 // current context. Although the wording of DR54 only applies to the pointer
1355 // variant of this rule, the intent is clearly for it to apply to the this
1356 // conversion as well.
1357
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001358 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001359 if (!DestReference) {
1360 return TC_NotApplicable;
1361 }
1362 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001363 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001364 // We know the left side is an lvalue reference, so we can suggest a reason.
1365 msg = diag::err_bad_cxx_cast_rvalue;
1366 return TC_NotApplicable;
1367 }
1368
1369 QualType DestPointee = DestReference->getPointeeType();
1370
Richard Smith11330852014-07-08 17:25:14 +00001371 // FIXME: If the source is a prvalue, we should issue a warning (because the
1372 // cast always has undefined behavior), and for AST consistency, we should
1373 // materialize a temporary.
Fangrui Song6907ce22018-07-30 19:24:48 +00001374 return TryStaticDowncast(Self,
1375 Self.Context.getCanonicalType(SrcExpr->getType()),
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001376 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001377 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1378 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001379}
1380
1381/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1382TryCastResult
1383TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001384 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001385 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001386 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001387 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1388 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1389 // is a class derived from B, if a valid standard conversion from "pointer
1390 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1391 // class of D.
1392 // In addition, DR54 clarifies that the base must be accessible in the
1393 // current context.
1394
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001395 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001396 if (!DestPointer) {
1397 return TC_NotApplicable;
1398 }
1399
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001400 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001401 if (!SrcPointer) {
1402 msg = diag::err_bad_static_cast_pointer_nonpointer;
1403 return TC_NotApplicable;
1404 }
1405
Fangrui Song6907ce22018-07-30 19:24:48 +00001406 return TryStaticDowncast(Self,
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001407 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001408 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001409 CStyle, OpRange, SrcType, DestType, msg, Kind,
1410 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001411}
1412
1413/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1414/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001415/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001416TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001417TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001418 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Fangrui Song6907ce22018-07-30 19:24:48 +00001419 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001420 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001421 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001422 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1423 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001424 return TC_NotApplicable;
1425
Sebastian Redl9f831db2009-07-25 15:41:38 +00001426 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001427 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001428 return TC_NotApplicable;
1429 }
1430
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001431 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001432 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001433 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001434 return TC_NotApplicable;
1435 }
1436
1437 // Target type does derive from source type. Now we're serious. If an error
1438 // appears now, it's not ignored.
1439 // This may not be entirely in line with the standard. Take for example:
1440 // struct A {};
1441 // struct B : virtual A {
1442 // B(A&);
1443 // };
Mike Stump11289f42009-09-09 15:08:12 +00001444 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001445 // void f()
1446 // {
1447 // (void)static_cast<const B&>(*((A*)0));
1448 // }
1449 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1450 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1451 // However, both GCC and Comeau reject this example, and accepting it would
1452 // mean more complex code if we're to preserve the nice error message.
1453 // FIXME: Being 100% compliant here would be nice to have.
1454
1455 // Must preserve cv, as always, unless we're in C-style mode.
1456 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001457 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001458 return TC_Failed;
1459 }
1460
1461 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1462 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1463 // that it builds the paths in reverse order.
1464 // To sum up: record all paths to the base and build a nice string from
1465 // them. Use it to spice up the error message.
1466 if (!Paths.isRecordingPaths()) {
1467 Paths.clear();
1468 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001469 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001470 }
1471 std::string PathDisplayStr;
1472 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001473 for (clang::CXXBasePath &Path : Paths) {
1474 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001475 // We haven't displayed a path to this particular base
1476 // class subobject yet.
1477 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001478 for (CXXBasePathElement &PE : llvm::reverse(Path))
1479 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001480 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001481 }
1482 }
1483
1484 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Fangrui Song6907ce22018-07-30 19:24:48 +00001485 << QualType(SrcType).getUnqualifiedType()
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001486 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001487 << PathDisplayStr << OpRange;
1488 msg = 0;
1489 return TC_Failed;
1490 }
1491
Craig Topperc3ec1492014-05-26 06:22:03 +00001492 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001493 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1494 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1495 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1496 msg = 0;
1497 return TC_Failed;
1498 }
1499
John McCallfe9cf0a2011-02-14 23:21:33 +00001500 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001501 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1502 SrcType, DestType,
1503 Paths.front(),
1504 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001505 case Sema::AR_accessible:
1506 case Sema::AR_delayed: // be optimistic
1507 case Sema::AR_dependent: // be optimistic
1508 break;
1509
1510 case Sema::AR_inaccessible:
1511 msg = 0;
1512 return TC_Failed;
1513 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001514 }
1515
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001516 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001517 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001518 return TC_Success;
1519}
1520
1521/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1522/// C++ 5.2.9p9 is valid:
1523///
1524/// An rvalue of type "pointer to member of D of type cv1 T" can be
1525/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1526/// where B is a base class of D [...].
1527///
1528TryCastResult
Fangrui Song6907ce22018-07-30 19:24:48 +00001529TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1530 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001531 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001532 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001533 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001534 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001535 if (!DestMemPtr)
1536 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001537
1538 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001539 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001540 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001541 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001542 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001543 FoundOverload)) {
1544 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1545 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1546 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1547 WasOverloadedFunction = true;
1548 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001549 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001550
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001551 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001552 if (!SrcMemPtr) {
1553 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1554 return TC_NotApplicable;
1555 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001556
1557 // Lock down the inheritance model right now in MS ABI, whether or not the
1558 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001559 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001560 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001561 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1562 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001563
1564 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001565 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1566 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001567 return TC_NotApplicable;
1568
1569 // B base of D
1570 QualType SrcClass(SrcMemPtr->getClass(), 0);
1571 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001572 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001573 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001574 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001575 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001576
1577 // 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 +00001578 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001579 Paths.clear();
1580 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001581 bool StillOkay =
1582 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001583 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001584 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001585 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1586 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1587 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1588 msg = 0;
1589 return TC_Failed;
1590 }
1591
1592 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1593 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1594 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1595 msg = 0;
1596 return TC_Failed;
1597 }
1598
John McCallfe9cf0a2011-02-14 23:21:33 +00001599 if (!CStyle) {
1600 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1601 DestClass, SrcClass,
1602 Paths.front(),
1603 diag::err_upcast_to_inaccessible_base)) {
1604 case Sema::AR_accessible:
1605 case Sema::AR_delayed:
1606 case Sema::AR_dependent:
1607 // Optimistically assume that the delayed and dependent cases
1608 // will work out.
1609 break;
1610
1611 case Sema::AR_inaccessible:
1612 msg = 0;
1613 return TC_Failed;
1614 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001615 }
1616
Douglas Gregorc934bc82010-03-07 23:24:59 +00001617 if (WasOverloadedFunction) {
1618 // Resolve the address of the overloaded function again, this time
1619 // allowing complaints if something goes wrong.
Fangrui Song6907ce22018-07-30 19:24:48 +00001620 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1621 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001622 true,
1623 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001624 if (!Fn) {
1625 msg = 0;
1626 return TC_Failed;
1627 }
1628
John McCall16df1e52010-03-30 21:47:33 +00001629 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001630 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001631 msg = 0;
1632 return TC_Failed;
1633 }
1634 }
1635
Anders Carlssonb78feca2010-04-24 19:22:20 +00001636 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001637 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001638 return TC_Success;
1639}
1640
1641/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1642/// is valid:
1643///
1644/// An expression e can be explicitly converted to a type T using a
1645/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1646TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001647TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Fangrui Song6907ce22018-07-30 19:24:48 +00001648 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001649 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001650 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001651 if (DestType->isRecordType()) {
1652 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001653 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001654 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001655 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001656 msg = 0;
1657 return TC_Failed;
1658 }
1659 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001660
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001661 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1662 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001663 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001664 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001665 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001666 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001667 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001668 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001669 Expr *SrcExprRaw = SrcExpr.get();
Richard Smithb8c0f552016-12-09 18:49:13 +00001670 // FIXME: Per DR242, we should check for an implicit conversion sequence
1671 // or for a constructor that could be invoked by direct-initialization
1672 // here, not for an initialization sequence.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001673 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001674
1675 // At this point of CheckStaticCast, if the destination is a reference,
Fangrui Song6907ce22018-07-30 19:24:48 +00001676 // or the expression is an overload expression this has to work.
Douglas Gregore81f58e2010-11-08 03:40:48 +00001677 // There is no other way that works.
1678 // On the other hand, if we're checking a C-style cast, we've still got
1679 // the reinterpret_cast way.
Fangrui Song6907ce22018-07-30 19:24:48 +00001680 bool CStyle
John McCall31168b02011-06-15 23:02:42 +00001681 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001682 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001683 return TC_NotApplicable;
Fangrui Song6907ce22018-07-30 19:24:48 +00001684
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001685 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001686 if (Result.isInvalid()) {
1687 msg = 0;
1688 return TC_Failed;
1689 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001690
Douglas Gregorb33eed02010-04-16 22:09:46 +00001691 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001692 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001693 else
John McCalle3027922010-08-25 11:45:40 +00001694 Kind = CK_NoOp;
Fangrui Song6907ce22018-07-30 19:24:48 +00001695
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001696 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001697 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001698}
1699
1700/// TryConstCast - See if a const_cast from source to destination is allowed,
1701/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001702static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1703 QualType DestType, bool CStyle,
1704 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001705 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001706 QualType SrcType = SrcExpr.get()->getType();
1707 bool NeedToMaterializeTemporary = false;
1708
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001709 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001710 // C++11 5.2.11p4:
1711 // if a pointer to T1 can be explicitly converted to the type "pointer to
1712 // T2" using a const_cast, then the following conversions can also be
1713 // made:
1714 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1715 // type T2 using the cast const_cast<T2&>;
1716 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1717 // type T2 using the cast const_cast<T2&&>; and
1718 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1719 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1720
1721 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001722 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1723 // is C-style, static_cast might find a way, so we simply suggest a
1724 // message and tell the parent to keep searching.
1725 msg = diag::err_bad_cxx_cast_rvalue;
1726 return TC_NotApplicable;
1727 }
1728
Richard Smith82c9b512013-06-14 22:27:52 +00001729 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1730 if (!SrcType->isRecordType()) {
1731 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1732 // this is C-style, static_cast can do this.
1733 msg = diag::err_bad_cxx_cast_rvalue;
1734 return TC_NotApplicable;
1735 }
1736
1737 // Materialize the class prvalue so that the const_cast can bind a
1738 // reference to it.
1739 NeedToMaterializeTemporary = true;
1740 }
1741
John McCalld25db7e2013-05-06 21:39:12 +00001742 // It's not completely clear under the standard whether we can
1743 // const_cast bit-field gl-values. Doing so would not be
1744 // intrinsically complicated, but for now, we say no for
1745 // consistency with other compilers and await the word of the
1746 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001747 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001748 msg = diag::err_bad_cxx_cast_bitfield;
1749 return TC_NotApplicable;
1750 }
1751
Sebastian Redl9f831db2009-07-25 15:41:38 +00001752 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1753 SrcType = Self.Context.getPointerType(SrcType);
1754 }
1755
1756 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1757 // the rules for const_cast are the same as those used for pointers.
1758
John McCall0e704f72010-05-18 09:35:29 +00001759 if (!DestType->isPointerType() &&
1760 !DestType->isMemberPointerType() &&
1761 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001762 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1763 // was a reference type, we converted it to a pointer above.
1764 // The status of rvalue references isn't entirely clear, but it looks like
1765 // conversion to them is simply invalid.
1766 // C++ 5.2.11p3: For two pointer types [...]
1767 if (!CStyle)
1768 msg = diag::err_bad_const_cast_dest;
1769 return TC_NotApplicable;
1770 }
1771 if (DestType->isFunctionPointerType() ||
1772 DestType->isMemberFunctionPointerType()) {
1773 // Cannot cast direct function pointers.
1774 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1775 // T is the ultimate pointee of source and target type.
1776 if (!CStyle)
1777 msg = diag::err_bad_const_cast_dest;
1778 return TC_NotApplicable;
1779 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001780
Richard Smitha3405ff2018-07-11 00:19:19 +00001781 // C++ [expr.const.cast]p3:
1782 // "For two similar types T1 and T2, [...]"
1783 //
1784 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1785 // type qualifiers. (Likewise, we ignore other changes when determining
1786 // whether a cast casts away constness.)
1787 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001788 return TC_NotApplicable;
1789
Richard Smith82c9b512013-06-14 22:27:52 +00001790 if (NeedToMaterializeTemporary)
1791 // This is a const_cast from a class prvalue to an rvalue reference type.
1792 // Materialize a temporary to store the result of the conversion.
Richard Smithb8c0f552016-12-09 18:49:13 +00001793 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1794 SrcExpr.get(),
Tim Shen4a05bb82016-06-21 20:29:17 +00001795 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001796
Sebastian Redl9f831db2009-07-25 15:41:38 +00001797 return TC_Success;
1798}
1799
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001800// Checks for undefined behavior in reinterpret_cast.
1801// The cases that is checked for is:
1802// *reinterpret_cast<T*>(&a)
1803// reinterpret_cast<T&>(a)
1804// where accessing 'a' as type 'T' will result in undefined behavior.
1805void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1806 bool IsDereference,
1807 SourceRange Range) {
1808 unsigned DiagID = IsDereference ?
1809 diag::warn_pointer_indirection_from_incompatible_type :
1810 diag::warn_undefined_reinterpret_cast;
1811
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001812 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001813 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001814
1815 QualType SrcTy, DestTy;
1816 if (IsDereference) {
1817 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1818 return;
1819 }
1820 SrcTy = SrcType->getPointeeType();
1821 DestTy = DestType->getPointeeType();
1822 } else {
1823 if (!DestType->getAs<ReferenceType>()) {
1824 return;
1825 }
1826 SrcTy = SrcType;
1827 DestTy = DestType->getPointeeType();
1828 }
1829
1830 // Cast is compatible if the types are the same.
1831 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1832 return;
1833 }
1834 // or one of the types is a char or void type
1835 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1836 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1837 return;
1838 }
1839 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001840 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001841 return;
1842 }
1843
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001844 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001845 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1846 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1847 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1848 return;
1849 }
1850 }
1851
1852 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1853}
Douglas Gregor1beec452011-03-12 01:48:56 +00001854
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001855static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1856 QualType DestType) {
1857 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001858 if (Self.Context.hasSameType(SrcType, DestType))
1859 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001860 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1861 if (SrcPtrTy->isObjCSelType()) {
1862 QualType DT = DestType;
1863 if (isa<PointerType>(DestType))
1864 DT = DestType->getPointeeType();
1865 if (!DT.getUnqualifiedType()->isVoidType())
1866 Self.Diag(SrcExpr.get()->getExprLoc(),
1867 diag::warn_cast_pointer_from_sel)
1868 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1869 }
1870}
1871
Reid Kleckner9f497332016-05-10 21:00:03 +00001872/// Diagnose casts that change the calling convention of a pointer to a function
1873/// defined in the current TU.
1874static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1875 QualType DstType, SourceRange OpRange) {
1876 // Check if this cast would change the calling convention of a function
1877 // pointer type.
1878 QualType SrcType = SrcExpr.get()->getType();
1879 if (Self.Context.hasSameType(SrcType, DstType) ||
1880 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1881 return;
1882 const auto *SrcFTy =
1883 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1884 const auto *DstFTy =
1885 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1886 CallingConv SrcCC = SrcFTy->getCallConv();
1887 CallingConv DstCC = DstFTy->getCallConv();
1888 if (SrcCC == DstCC)
1889 return;
1890
1891 // We have a calling convention cast. Check if the source is a pointer to a
1892 // known, specific function that has already been defined.
1893 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1894 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1895 if (UO->getOpcode() == UO_AddrOf)
1896 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1897 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1898 if (!DRE)
1899 return;
1900 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Reid Kleckner0b009e82017-01-31 19:37:45 +00001901 if (!FD)
Reid Kleckner9f497332016-05-10 21:00:03 +00001902 return;
1903
Reid Kleckner43be52a2016-05-11 17:43:13 +00001904 // Only warn if we are casting from the default convention to a non-default
1905 // convention. This can happen when the programmer forgot to apply the calling
Reid Kleckner0b009e82017-01-31 19:37:45 +00001906 // convention to the function declaration and then inserted this cast to
Reid Kleckner43be52a2016-05-11 17:43:13 +00001907 // satisfy the type system.
1908 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1909 FD->isVariadic(), FD->isCXXInstanceMember());
1910 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1911 return;
1912
Reid Kleckner9f497332016-05-10 21:00:03 +00001913 // Diagnose this cast, as it is probably bad.
1914 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1915 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1916 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1917 << SrcCCName << DstCCName << OpRange;
1918
1919 // The checks above are cheaper than checking if the diagnostic is enabled.
1920 // However, it's worth checking if the warning is enabled before we construct
1921 // a fixit.
1922 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1923 return;
1924
1925 // Try to suggest a fixit to change the calling convention of the function
1926 // whose address was taken. Try to use the latest macro for the convention.
1927 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1928 // to match the Windows header declarations.
Reid Kleckner0b009e82017-01-31 19:37:45 +00001929 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
Reid Kleckner9f497332016-05-10 21:00:03 +00001930 Preprocessor &PP = Self.getPreprocessor();
1931 SmallVector<TokenValue, 6> AttrTokens;
1932 SmallString<64> CCAttrText;
1933 llvm::raw_svector_ostream OS(CCAttrText);
1934 if (Self.getLangOpts().MicrosoftExt) {
1935 // __stdcall or __vectorcall
1936 OS << "__" << DstCCName;
1937 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1938 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1939 ? TokenValue(II->getTokenID())
1940 : TokenValue(II));
1941 } else {
1942 // __attribute__((stdcall)) or __attribute__((vectorcall))
1943 OS << "__attribute__((" << DstCCName << "))";
1944 AttrTokens.push_back(tok::kw___attribute);
1945 AttrTokens.push_back(tok::l_paren);
1946 AttrTokens.push_back(tok::l_paren);
1947 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1948 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1949 ? TokenValue(II->getTokenID())
1950 : TokenValue(II));
1951 AttrTokens.push_back(tok::r_paren);
1952 AttrTokens.push_back(tok::r_paren);
1953 }
1954 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1955 if (!AttrSpelling.empty())
1956 CCAttrText = AttrSpelling;
1957 OS << ' ';
1958 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1959 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1960}
1961
David Blaikie282ad872012-10-16 18:53:14 +00001962static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1963 const Expr *SrcExpr, QualType DestType,
1964 Sema &Self) {
1965 QualType SrcType = SrcExpr->getType();
1966
1967 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1968 // are not explicit design choices, but consistent with GCC's behavior.
1969 // Feel free to modify them if you've reason/evidence for an alternative.
1970 if (CStyle && SrcType->isIntegralType(Self.Context)
1971 && !SrcType->isBooleanType()
1972 && !SrcType->isEnumeralType()
1973 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001974 && Self.Context.getTypeSize(DestType) >
1975 Self.Context.getTypeSize(SrcType)) {
1976 // Separate between casts to void* and non-void* pointers.
1977 // Some APIs use (abuse) void* for something like a user context,
1978 // and often that value is an integer even if it isn't a pointer itself.
1979 // Having a separate warning flag allows users to control the warning
1980 // for their workflow.
1981 unsigned Diag = DestType->isVoidPointerType() ?
1982 diag::warn_int_to_void_pointer_cast
1983 : diag::warn_int_to_pointer_cast;
1984 Self.Diag(Loc, Diag) << SrcType << DestType;
1985 }
David Blaikie282ad872012-10-16 18:53:14 +00001986}
1987
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001988static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1989 ExprResult &Result) {
1990 // We can only fix an overloaded reinterpret_cast if
1991 // - it is a template with explicit arguments that resolves to an lvalue
1992 // unambiguously, or
1993 // - it is the only function in an overload set that may have its address
1994 // taken.
1995
1996 Expr *E = Result.get();
1997 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1998 // like it?
1999 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2000 Result,
2001 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
2002 ) &&
2003 Result.isUsable())
2004 return true;
2005
George Burgess IVbeca4a32016-06-08 00:34:22 +00002006 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2007 // preserves Result.
2008 Result = E;
George Burgess IV1dbfa852017-05-09 04:06:24 +00002009 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
2010 Result, /*DoFunctionPointerConversion=*/true))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00002011 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00002012 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00002013}
2014
John Wiegley01296292011-04-08 18:41:53 +00002015static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00002016 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00002017 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00002018 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00002019 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00002020 bool IsLValueCast = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002021
Sebastian Redl9f831db2009-07-25 15:41:38 +00002022 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00002023 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002024
2025 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00002026 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00002027 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00002028 ExprResult FixedExpr = SrcExpr;
2029 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00002030 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00002031
2032 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2033 SrcExpr = FixedExpr;
2034 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00002035 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00002036
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00002038 if (!SrcExpr.get()->isGLValue()) {
2039 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2040 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00002041 msg = diag::err_bad_cxx_cast_rvalue;
2042 return TC_NotApplicable;
2043 }
2044
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00002045 if (!CStyle) {
2046 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002047 /*IsDereference=*/false, OpRange);
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00002048 }
2049
Sebastian Redl9f831db2009-07-25 15:41:38 +00002050 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2051 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2052 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002053
Craig Topperc3ec1492014-05-26 06:22:03 +00002054 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002055 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00002056 case OK_Ordinary:
2057 break;
Richard Smithb8c0f552016-12-09 18:49:13 +00002058 case OK_BitField:
2059 msg = diag::err_bad_cxx_cast_bitfield;
2060 return TC_NotApplicable;
2061 // FIXME: Use a specific diagnostic for the rest of these cases.
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002062 case OK_VectorComponent: inappropriate = "vector element"; break;
2063 case OK_ObjCProperty: inappropriate = "property expression"; break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002064 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
Ted Kremeneke65b0862012-03-06 20:05:56 +00002065 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002066 }
2067 if (inappropriate) {
2068 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2069 << inappropriate << DestType
2070 << OpRange << SrcExpr.get()->getSourceRange();
2071 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002072 return TC_NotApplicable;
2073 }
2074
Sebastian Redl9f831db2009-07-25 15:41:38 +00002075 // This code does this transformation for the checked types.
2076 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2077 SrcType = Self.Context.getPointerType(SrcType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002078
Douglas Gregor51954272010-07-13 23:17:26 +00002079 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002080 }
2081
2082 // Canonicalize source for comparison.
2083 SrcType = Self.Context.getCanonicalType(SrcType);
2084
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002085 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2086 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002087 if (DestMemPtr && SrcMemPtr) {
2088 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2089 // can be explicitly converted to an rvalue of type "pointer to member
2090 // of Y of type T2" if T1 and T2 are both function types or both object
2091 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00002092 if (DestMemPtr->isMemberFunctionPointer() !=
2093 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00002094 return TC_NotApplicable;
2095
David Majnemer1cdd96d2014-01-17 09:01:00 +00002096 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2097 // We need to determine the inheritance model that the class will use if
2098 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00002099 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2100 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00002101 }
2102
Charles Davisebab1ed2010-08-16 05:30:44 +00002103 // Don't allow casting between member pointers of different sizes.
2104 if (Self.Context.getTypeSize(DestMemPtr) !=
2105 Self.Context.getTypeSize(SrcMemPtr)) {
2106 msg = diag::err_bad_cxx_cast_member_pointer_size;
2107 return TC_Failed;
2108 }
2109
Richard Smithf276e2d2018-07-10 23:04:35 +00002110 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2111 // constness.
2112 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2113 // we accept it.
2114 if (auto CACK =
2115 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2116 /*CheckObjCLifetime=*/CStyle))
2117 return getCastAwayConstnessCastKind(CACK, msg);
2118
Sebastian Redl9f831db2009-07-25 15:41:38 +00002119 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00002120 assert(!IsLValueCast);
2121 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002122 return TC_Success;
2123 }
2124
2125 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00002126 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002127 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2128 // type large enough to hold it. A value of std::nullptr_t can be
2129 // converted to an integral type; the conversion has the same meaning
2130 // and validity as a conversion of (void*)0 to the integral type.
2131 if (Self.Context.getTypeSize(SrcType) >
2132 Self.Context.getTypeSize(DestType)) {
2133 msg = diag::err_bad_reinterpret_cast_small_int;
2134 return TC_Failed;
2135 }
John McCalle3027922010-08-25 11:45:40 +00002136 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002137 return TC_Success;
2138 }
2139
John McCall1c78f082015-07-23 23:54:07 +00002140 // Allow reinterpret_casts between vectors of the same size and
2141 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00002142 bool destIsVector = DestType->isVectorType();
2143 bool srcIsVector = SrcType->isVectorType();
2144 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00002145 // The non-vector type, if any, must have integral type. This is
2146 // the same rule that C vector casts use; note, however, that enum
2147 // types are not integral in C++.
2148 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2149 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002150 return TC_NotApplicable;
2151
John McCall1c78f082015-07-23 23:54:07 +00002152 // The size we want to consider is eltCount * eltSize.
2153 // That's exactly what the lax-conversion rules will check.
2154 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002155 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002156 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002157 }
John McCall1c78f082015-07-23 23:54:07 +00002158
2159 // Otherwise, pick a reasonable diagnostic.
2160 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002161 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002162 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002163 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2164 else
2165 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
Fangrui Song6907ce22018-07-30 19:24:48 +00002166
Anders Carlsson570af5d2009-09-16 19:19:43 +00002167 return TC_Failed;
2168 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002169
2170 if (SrcType == DestType) {
2171 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2172 // restrictions, a cast to the same type is allowed so long as it does not
Fangrui Song6907ce22018-07-30 19:24:48 +00002173 // cast away constness. In C++98, the intent was not entirely clear here,
Chad Rosier96c755d12012-02-03 02:54:37 +00002174 // since all other paragraphs explicitly forbid casts to the same type.
2175 // C++11 clarifies this case with p2.
2176 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002177 // The only allowed types are: integral, enumeration, pointer, or
Chad Rosier96c755d12012-02-03 02:54:37 +00002178 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2179 Kind = CK_NoOp;
2180 TryCastResult Result = TC_NotApplicable;
2181 if (SrcType->isIntegralOrEnumerationType() ||
2182 SrcType->isAnyPointerType() ||
2183 SrcType->isMemberPointerType() ||
2184 SrcType->isBlockPointerType()) {
2185 Result = TC_Success;
2186 }
2187 return Result;
2188 }
2189
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002190 bool destIsPtr = DestType->isAnyPointerType() ||
2191 DestType->isBlockPointerType();
2192 bool srcIsPtr = SrcType->isAnyPointerType() ||
2193 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002194 if (!destIsPtr && !srcIsPtr) {
2195 // Except for std::nullptr_t->integer and lvalue->reference, which are
2196 // handled above, at least one of the two arguments must be a pointer.
2197 return TC_NotApplicable;
2198 }
2199
Douglas Gregor6972a622010-06-16 00:35:25 +00002200 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002201 assert(srcIsPtr && "One type must be a pointer");
2202 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002203 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002204 // integral type size doesn't matter (except we don't allow bool).
2205 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2206 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002207 if ((Self.Context.getTypeSize(SrcType) >
2208 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002209 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002210 msg = diag::err_bad_reinterpret_cast_small_int;
2211 return TC_Failed;
2212 }
John McCalle3027922010-08-25 11:45:40 +00002213 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002214 return TC_Success;
2215 }
2216
Douglas Gregorb90df602010-06-16 00:17:44 +00002217 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002218 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002219 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2220 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002221 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2222 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002223 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2224 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002225 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002226 return TC_Success;
2227 }
2228
2229 if (!destIsPtr || !srcIsPtr) {
2230 // With the valid non-pointer conversions out of the way, we can be even
2231 // more stringent.
2232 return TC_NotApplicable;
2233 }
2234
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002235 // Cannot convert between block pointers and Objective-C object pointers.
2236 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2237 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2238 return TC_NotApplicable;
2239
Richard Smithf276e2d2018-07-10 23:04:35 +00002240 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2241 // The C-style cast operator can.
2242 TryCastResult SuccessResult = TC_Success;
2243 if (auto CACK =
2244 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2245 /*CheckObjCLifetime=*/CStyle))
2246 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2247
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002248 if (IsAddressSpaceConversion(SrcType, DestType)) {
2249 Kind = CK_AddressSpaceConversion;
2250 assert(SrcType->isPointerType() && DestType->isPointerType());
2251 if (!CStyle &&
2252 !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2253 SrcType->getPointeeType().getQualifiers())) {
2254 SuccessResult = TC_Failed;
2255 }
2256 } else if (IsLValueCast) {
John McCall9320b872011-09-09 05:25:32 +00002257 Kind = CK_LValueBitCast;
2258 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002259 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002260 } else if (DestType->isBlockPointerType()) {
2261 if (!SrcType->isBlockPointerType()) {
2262 Kind = CK_AnyPointerToBlockPointerCast;
2263 } else {
2264 Kind = CK_BitCast;
2265 }
2266 } else {
2267 Kind = CK_BitCast;
2268 }
2269
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002270 // Any pointer can be cast to an Objective-C pointer type with a C-style
2271 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002272 if (CStyle && DestType->isObjCObjectPointerType()) {
Richard Smithf276e2d2018-07-10 23:04:35 +00002273 return SuccessResult;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002274 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002275 if (CStyle)
2276 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002277
2278 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2279
Sebastian Redl9f831db2009-07-25 15:41:38 +00002280 // Not casting away constness, so the only remaining check is for compatible
2281 // pointer categories.
2282
2283 if (SrcType->isFunctionPointerType()) {
2284 if (DestType->isFunctionPointerType()) {
2285 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2286 // a pointer to a function of a different type.
Richard Smithf276e2d2018-07-10 23:04:35 +00002287 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002288 }
2289
2290 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2291 // an object type or vice versa is conditionally-supported.
2292 // Compilers support it in C++03 too, though, because it's necessary for
2293 // casting the return value of dlsym() and GetProcAddress().
2294 // FIXME: Conditionally-supported behavior should be configurable in the
2295 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002296 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002297 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002298 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2299 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002300 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002301 }
2302
2303 if (DestType->isFunctionPointerType()) {
2304 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002305 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002306 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002307 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2308 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002309 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002310 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002311
Sebastian Redl9f831db2009-07-25 15:41:38 +00002312 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2313 // a pointer to an object of different type.
2314 // Void pointers are not specified, but supported by every compiler out there.
2315 // So we finish by allowing everything that remains - it's got to be two
2316 // object pointers.
Richard Smithf276e2d2018-07-10 23:04:35 +00002317 return SuccessResult;
2318}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002319
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002320static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2321 QualType DestType, bool CStyle,
2322 unsigned &msg) {
2323 if (!Self.getLangOpts().OpenCL)
2324 // FIXME: As compiler doesn't have any information about overlapping addr
2325 // spaces at the moment we have to be permissive here.
2326 return TC_NotApplicable;
2327 // Even though the logic below is general enough and can be applied to
2328 // non-OpenCL mode too, we fast-path above because no other languages
2329 // define overlapping address spaces currently.
2330 auto SrcType = SrcExpr.get()->getType();
2331 auto SrcPtrType = SrcType->getAs<PointerType>();
2332 if (!SrcPtrType)
2333 return TC_NotApplicable;
2334 auto DestPtrType = DestType->getAs<PointerType>();
2335 if (!DestPtrType)
2336 return TC_NotApplicable;
2337 auto SrcPointeeType = SrcPtrType->getPointeeType();
2338 auto DestPointeeType = DestPtrType->getPointeeType();
2339 if (SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace())
2340 return TC_NotApplicable;
2341 if (!DestPtrType->isAddressSpaceOverlapping(*SrcPtrType)) {
2342 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2343 return TC_Failed;
2344 }
2345 auto SrcPointeeTypeWithoutAS =
2346 Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2347 auto DestPointeeTypeWithoutAS =
2348 Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2349 return Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2350 DestPointeeTypeWithoutAS)
2351 ? TC_Success
2352 : TC_NotApplicable;
2353}
2354
Anastasia Stulova5325f832018-10-10 16:05:22 +00002355void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2356 // In OpenCL only conversions between pointers to objects in overlapping
2357 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2358 // with any named one, except for constant.
Anastasia Stulova5b6dda32019-05-08 14:23:49 +00002359
2360 // Converting the top level pointee addrspace is permitted for compatible
2361 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2362 // if any of the nested pointee addrspaces differ, we emit a warning
2363 // regardless of addrspace compatibility. This makes
2364 // local int ** p;
2365 // return (generic int **) p;
2366 // warn even though local -> generic is permitted.
Anastasia Stulova5325f832018-10-10 16:05:22 +00002367 if (Self.getLangOpts().OpenCL) {
Anastasia Stulova5b6dda32019-05-08 14:23:49 +00002368 const Type *DestPtr, *SrcPtr;
2369 bool Nested = false;
2370 unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2371 DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2372 SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2373
2374 while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
2375 const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2376 const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2377 QualType DestPPointee = DestPPtr->getPointeeType();
2378 QualType SrcPPointee = SrcPPtr->getPointeeType();
2379 if (Nested ? DestPPointee.getAddressSpace() !=
2380 SrcPPointee.getAddressSpace()
2381 : !DestPPtr->isAddressSpaceOverlapping(*SrcPPtr)) {
2382 Self.Diag(OpRange.getBegin(), DiagID)
2383 << SrcType << DestType << Sema::AA_Casting
2384 << SrcExpr.get()->getSourceRange();
2385 if (!Nested)
2386 SrcExpr = ExprError();
2387 return;
2388 }
2389
2390 DestPtr = DestPPtr->getPointeeType().getTypePtr();
2391 SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2392 Nested = true;
2393 DiagID = diag::ext_nested_pointer_qualifier_mismatch;
Anastasia Stulova5325f832018-10-10 16:05:22 +00002394 }
2395 }
2396}
2397
Sebastian Redld74dd492012-02-12 18:41:05 +00002398void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2399 bool ListInitialization) {
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002400 assert(Self.getLangOpts().CPlusPlus);
2401
John McCall9776e432011-10-06 23:25:11 +00002402 // Handle placeholders.
2403 if (isPlaceholder()) {
2404 // C-style casts can resolve __unknown_any types.
2405 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2406 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2407 SrcExpr.get(), Kind,
2408 ValueKind, BasePath);
2409 return;
2410 }
John McCallb50451a2011-10-05 07:41:44 +00002411
John McCall9776e432011-10-06 23:25:11 +00002412 checkNonOverloadPlaceholders();
2413 if (SrcExpr.isInvalid())
2414 return;
John McCalla072f5d2011-10-17 17:42:19 +00002415 }
John McCall9776e432011-10-06 23:25:11 +00002416
2417 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002418 // This test is outside everything else because it's the only case where
2419 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002420 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002421 Kind = CK_ToVoid;
2422
John McCall9776e432011-10-06 23:25:11 +00002423 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002424 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
Fangrui Song6907ce22018-07-30 19:24:48 +00002425 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002426 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002427 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002428 if (SrcExpr.isInvalid())
2429 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002430 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002431
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002432 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002433 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002434 }
2435
Sebastian Redl9f831db2009-07-25 15:41:38 +00002436 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002437 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2438 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002439 assert(Kind == CK_Dependent);
2440 return;
John McCall8cb679e2010-11-15 09:13:47 +00002441 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002442
John McCall50a2c2c2011-10-11 23:14:30 +00002443 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2444 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002445 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002446 if (SrcExpr.isInvalid())
2447 return;
John Wiegley01296292011-04-08 18:41:53 +00002448 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002449
John McCall3aef3d82011-04-10 19:13:55 +00002450 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002451 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002452 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002453 && (SrcExpr.get()->getType()->isIntegerType()
2454 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002455 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002456 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002457 return;
John McCall3aef3d82011-04-10 19:13:55 +00002458 }
2459
Sebastian Redl9f831db2009-07-25 15:41:38 +00002460 // C++ [expr.cast]p5: The conversions performed by
2461 // - a const_cast,
2462 // - a static_cast,
2463 // - a static_cast followed by a const_cast,
2464 // - a reinterpret_cast, or
2465 // - a reinterpret_cast followed by a const_cast,
2466 // can be performed using the cast notation of explicit type conversion.
2467 // [...] If a conversion can be interpreted in more than one of the ways
2468 // listed above, the interpretation that appears first in the list is used,
2469 // even if a cast resulting from that interpretation is ill-formed.
2470 // In plain language, this means trying a const_cast ...
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002471 // Note that for address space we check compatibility after const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00002472 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002473 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002474 /*CStyle*/ true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002475 if (SrcExpr.isInvalid())
2476 return;
Richard Smithf276e2d2018-07-10 23:04:35 +00002477 if (isValidCast(tcr))
John McCalle3027922010-08-25 11:45:40 +00002478 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002479
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002480 Sema::CheckedConversionKind CCK =
2481 FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002482 if (tcr == TC_NotApplicable) {
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002483 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg);
John McCallb50451a2011-10-05 07:41:44 +00002484 if (SrcExpr.isInvalid())
2485 return;
Anastasia Stulova5099aef2019-06-03 15:42:36 +00002486
2487 if (isValidCast(tcr))
2488 Kind = CK_AddressSpaceConversion;
2489
Sebastian Redl9f831db2009-07-25 15:41:38 +00002490 if (tcr == TC_NotApplicable) {
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002491 // ... or if that is not possible, a static_cast, ignoring const, ...
2492 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2493 BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002494 if (SrcExpr.isInvalid())
2495 return;
Anastasia Stulova6f7c5362019-03-07 17:06:30 +00002496
2497 if (tcr == TC_NotApplicable) {
2498 // ... and finally a reinterpret_cast, ignoring const.
2499 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2500 OpRange, msg, Kind);
2501 if (SrcExpr.isInvalid())
2502 return;
2503 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002504 }
2505 }
2506
Brian Kelley11352a82017-03-29 18:09:02 +00002507 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
Richard Smithf276e2d2018-07-10 23:04:35 +00002508 isValidCast(tcr))
Brian Kelley11352a82017-03-29 18:09:02 +00002509 checkObjCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002510
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002511 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002512 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002513 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002514 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2515 DestType,
2516 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002517 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002518 if (Fn) {
2519 // If DestType is a function type (not to be confused with the function
2520 // pointer type), it will be possible to resolve the function address,
2521 // but the type cast should be considered as failure.
2522 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2523 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2524 << OE->getName() << DestType << OpRange
2525 << OE->getQualifierLoc().getSourceRange();
2526 Self.NoteAllOverloadCandidates(SrcExpr.get());
2527 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002528 } else {
John McCallb50451a2011-10-05 07:41:44 +00002529 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002530 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002531 }
2532 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002533
Richard Smithf276e2d2018-07-10 23:04:35 +00002534 if (isValidCast(tcr)) {
2535 if (Kind == CK_BitCast)
2536 checkCastAlign();
2537 } else {
John McCallb50451a2011-10-05 07:41:44 +00002538 SrcExpr = ExprError();
Richard Smithf276e2d2018-07-10 23:04:35 +00002539 }
John McCallb50451a2011-10-05 07:41:44 +00002540}
2541
Fangrui Song6907ce22018-07-30 19:24:48 +00002542/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002543/// non-matching type. Such as enum function call to int, int call to
2544/// pointer; etc. Cast to 'void' is an exception.
2545static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2546 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002547 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2548 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002549 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002550
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002551 if (!isa<CallExpr>(SrcExpr.get()))
2552 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002553
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002554 QualType SrcType = SrcExpr.get()->getType();
2555 if (DestType.getUnqualifiedType()->isVoidType())
2556 return;
2557 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2558 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2559 return;
2560 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2561 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2562 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2563 return;
2564 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2565 return;
2566 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2567 return;
2568 if (SrcType->isComplexType() && DestType->isComplexType())
2569 return;
2570 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2571 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002572
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002573 Self.Diag(SrcExpr.get()->getExprLoc(),
2574 diag::warn_bad_function_cast)
2575 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2576}
2577
John McCall9776e432011-10-06 23:25:11 +00002578/// Check the semantics of a C-style cast operation, in C.
2579void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002580 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002581
John McCall4124c492011-10-17 18:40:02 +00002582 // C-style casts can resolve __unknown_any types.
2583 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2584 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2585 SrcExpr.get(), Kind,
2586 ValueKind, BasePath);
2587 return;
2588 }
John McCall9776e432011-10-06 23:25:11 +00002589
2590 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2591 // type needs to be scalar.
2592 if (DestType->isVoidType()) {
2593 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002594 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002595 if (SrcExpr.isInvalid())
2596 return;
2597
2598 // Cast to void allows any expr type.
2599 Kind = CK_ToVoid;
2600 return;
2601 }
2602
George Burgess IV5f21c712015-10-12 19:57:04 +00002603 // Overloads are allowed with C extensions, so we need to support them.
2604 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2605 DeclAccessPair DAP;
2606 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2607 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2608 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2609 else
2610 return;
2611 assert(SrcExpr.isUsable());
2612 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002613 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002614 if (SrcExpr.isInvalid())
2615 return;
2616 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002617
John McCall4124c492011-10-17 18:40:02 +00002618 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002619
Anastasia Stulova5325f832018-10-10 16:05:22 +00002620 checkAddressSpaceCast(SrcType, DestType);
2621 if (SrcExpr.isInvalid())
2622 return;
Joey Gouly8fc32f02014-01-14 12:47:29 +00002623
John McCall9776e432011-10-06 23:25:11 +00002624 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2625 diag::err_typecheck_cast_to_incomplete)) {
2626 SrcExpr = ExprError();
2627 return;
2628 }
2629
2630 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2631 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2632
2633 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2634 // GCC struct/union extension: allow cast to self.
2635 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2636 << DestType << SrcExpr.get()->getSourceRange();
2637 Kind = CK_NoOp;
2638 return;
2639 }
2640
2641 // GCC's cast to union extension.
2642 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2643 RecordDecl *RD = DestRecordTy->getDecl();
John McCallf1ef7962017-08-15 21:42:47 +00002644 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2645 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2646 << SrcExpr.get()->getSourceRange();
2647 Kind = CK_ToUnion;
2648 return;
2649 } else {
John McCall9776e432011-10-06 23:25:11 +00002650 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2651 << SrcType << SrcExpr.get()->getSourceRange();
2652 SrcExpr = ExprError();
2653 return;
2654 }
John McCall9776e432011-10-06 23:25:11 +00002655 }
2656
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002657 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2658 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002659 Expr::EvalResult Result;
2660 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2661 llvm::APSInt CastInt = Result.Val.getInt();
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002662 if (0 == CastInt) {
Andrew Savonichevb555b762018-10-23 15:19:20 +00002663 Kind = CK_ZeroToOCLOpaqueType;
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002664 return;
2665 }
2666 Self.Diag(OpRange.getBegin(),
Richard Smithf8812672016-12-02 22:38:31 +00002667 diag::err_opencl_cast_non_zero_to_event_t)
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002668 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2669 SrcExpr = ExprError();
2670 return;
2671 }
2672 }
2673
John McCall9776e432011-10-06 23:25:11 +00002674 // Reject any other conversions to non-scalar types.
2675 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2676 << DestType << SrcExpr.get()->getSourceRange();
2677 SrcExpr = ExprError();
2678 return;
2679 }
2680
2681 // The type we're casting to is known to be a scalar or vector.
2682
2683 // Require the operand to be a scalar or vector.
2684 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2685 Self.Diag(SrcExpr.get()->getExprLoc(),
2686 diag::err_typecheck_expect_scalar_operand)
2687 << SrcType << SrcExpr.get()->getSourceRange();
2688 SrcExpr = ExprError();
2689 return;
2690 }
2691
2692 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002693 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002694 return;
2695 }
2696
2697 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2698 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2699 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2700 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002701 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002702 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2703 SrcExpr = ExprError();
2704 }
2705 return;
2706 }
2707
2708 if (SrcType->isVectorType()) {
2709 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2710 SrcExpr = ExprError();
2711 return;
2712 }
2713
2714 // The source and target types are both scalars, i.e.
2715 // - arithmetic types (fundamental, enum, and complex)
2716 // - all kinds of pointers
2717 // Note that member pointers were filtered out with C++, above.
2718
2719 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2720 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2721 SrcExpr = ExprError();
2722 return;
2723 }
2724
2725 // If either type is a pointer, the other type has to be either an
2726 // integer or a pointer.
2727 if (!DestType->isArithmeticType()) {
2728 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2729 Self.Diag(SrcExpr.get()->getExprLoc(),
2730 diag::err_cast_pointer_from_non_pointer_int)
2731 << SrcType << SrcExpr.get()->getSourceRange();
2732 SrcExpr = ExprError();
2733 return;
2734 }
David Blaikie282ad872012-10-16 18:53:14 +00002735 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2736 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002737 } else if (!SrcType->isArithmeticType()) {
2738 if (!DestType->isIntegralType(Self.Context) &&
2739 DestType->isArithmeticType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002740 Self.Diag(SrcExpr.get()->getBeginLoc(),
2741 diag::err_cast_pointer_to_non_pointer_int)
2742 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002743 SrcExpr = ExprError();
2744 return;
2745 }
2746 }
2747
Yaxun Liu5b746652016-12-18 05:18:55 +00002748 if (Self.getLangOpts().OpenCL &&
2749 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
Joey Goulydd7f4562013-01-23 11:56:20 +00002750 if (DestType->isHalfType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002751 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
2752 << DestType << SrcExpr.get()->getSourceRange();
Joey Goulydd7f4562013-01-23 11:56:20 +00002753 SrcExpr = ExprError();
2754 return;
2755 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002756 }
2757
John McCall9776e432011-10-06 23:25:11 +00002758 // ARC imposes extra restrictions on casts.
Brian Kelley11352a82017-03-29 18:09:02 +00002759 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2760 checkObjCConversion(Sema::CCK_CStyleCast);
John McCall9776e432011-10-06 23:25:11 +00002761 if (SrcExpr.isInvalid())
2762 return;
Brian Kelley11352a82017-03-29 18:09:02 +00002763
2764 const PointerType *CastPtr = DestType->getAs<PointerType>();
2765 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
John McCall9776e432011-10-06 23:25:11 +00002766 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2767 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2768 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00002769 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
John McCall9776e432011-10-06 23:25:11 +00002770 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2771 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002772 Self.Diag(SrcExpr.get()->getBeginLoc(),
John McCall9776e432011-10-06 23:25:11 +00002773 diag::err_typecheck_incompatible_ownership)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002774 << SrcType << DestType << Sema::AA_Casting
2775 << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002776 return;
2777 }
2778 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002779 }
John McCall9776e432011-10-06 23:25:11 +00002780 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002781 Self.Diag(SrcExpr.get()->getBeginLoc(),
John McCall9776e432011-10-06 23:25:11 +00002782 diag::err_arc_convesion_of_weak_unavailable)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002783 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002784 SrcExpr = ExprError();
2785 return;
2786 }
2787 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002788
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002789 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002790 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002791 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002792 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2793 if (SrcExpr.isInvalid())
2794 return;
2795
2796 if (Kind == CK_BitCast)
2797 checkCastAlign();
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002798}
Roman Divackyd5178012014-11-21 21:03:10 +00002799
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002800void CastOperation::CheckBuiltinBitCast() {
2801 QualType SrcType = SrcExpr.get()->getType();
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002802
Erik Pilkington0a223d92019-08-12 18:31:27 +00002803 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2804 diag::err_typecheck_cast_to_incomplete) ||
2805 Self.RequireCompleteType(OpRange.getBegin(), SrcType,
2806 diag::err_incomplete_type)) {
2807 SrcExpr = ExprError();
2808 return;
2809 }
2810
Erik Pilkington055fcec2019-08-12 19:29:43 +00002811 if (SrcExpr.get()->isRValue())
2812 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
2813 /*IsLValueReference=*/false);
2814
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002815 CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
2816 CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
2817 if (DestSize != SourceSize) {
2818 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
2819 << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
2820 SrcExpr = ExprError();
2821 return;
2822 }
2823
2824 if (!DestType.isTriviallyCopyableType(Self.Context)) {
2825 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
2826 << 1;
2827 SrcExpr = ExprError();
2828 return;
2829 }
2830
2831 if (!SrcType.isTriviallyCopyableType(Self.Context)) {
2832 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
2833 << 0;
2834 SrcExpr = ExprError();
2835 return;
2836 }
2837
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002838 Kind = CK_LValueToRValueBitCast;
2839}
2840
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002841/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2842/// const, volatile or both.
2843static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2844 QualType DestType) {
2845 if (SrcExpr.isInvalid())
2846 return;
2847
2848 QualType SrcType = SrcExpr.get()->getType();
2849 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2850 DestType->isLValueReferenceType()))
2851 return;
2852
Roman Divackyd5178012014-11-21 21:03:10 +00002853 QualType TheOffendingSrcType, TheOffendingDestType;
2854 Qualifiers CastAwayQualifiers;
Richard Smithf276e2d2018-07-10 23:04:35 +00002855 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
2856 &TheOffendingSrcType, &TheOffendingDestType,
2857 &CastAwayQualifiers) !=
2858 CastAwayConstnessKind::CACK_Similar)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002859 return;
2860
Richard Smithf276e2d2018-07-10 23:04:35 +00002861 // FIXME: 'restrict' is not properly handled here.
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002862 int qualifiers = -1;
2863 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2864 qualifiers = 0;
2865 } else if (CastAwayQualifiers.hasConst()) {
2866 qualifiers = 1;
2867 } else if (CastAwayQualifiers.hasVolatile()) {
2868 qualifiers = 2;
Roman Divackyd5178012014-11-21 21:03:10 +00002869 }
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002870 // This is a variant of int **x; const int **y = (const int **)x;
2871 if (qualifiers == -1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002872 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002873 << SrcType << DestType;
2874 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002875 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002876 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
John McCall9776e432011-10-06 23:25:11 +00002877}
2878
2879ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2880 TypeSourceInfo *CastTypeInfo,
2881 SourceLocation RPLoc,
2882 Expr *CastExpr) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002883 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002884 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002885 Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
John McCallb50451a2011-10-05 07:41:44 +00002886
David Blaikiebbafb8a2012-03-11 07:00:24 +00002887 if (getLangOpts().CPlusPlus) {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002888 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
Sebastian Redld74dd492012-02-12 18:41:05 +00002889 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002890 } else {
2891 Op.CheckCStyleCast();
2892 }
2893
John McCallb50451a2011-10-05 07:41:44 +00002894 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002895 return ExprError();
2896
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002897 // -Wcast-qual
2898 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2899
John McCall4124c492011-10-17 18:40:02 +00002900 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002901 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002902 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002903}
2904
2905ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
Richard Smith60437622017-02-09 19:17:44 +00002906 QualType Type,
John McCallb50451a2011-10-05 07:41:44 +00002907 SourceLocation LPLoc,
2908 Expr *CastExpr,
2909 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002910 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
Richard Smith60437622017-02-09 19:17:44 +00002911 CastOperation Op(*this, Type, CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002912 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002913 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
John McCallb50451a2011-10-05 07:41:44 +00002914
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002915 Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002916 if (Op.SrcExpr.isInvalid())
2917 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002918
2919 auto *SubExpr = Op.SrcExpr.get();
2920 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2921 SubExpr = BindExpr->getSubExpr();
2922 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002923 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002924
John McCall4124c492011-10-17 18:40:02 +00002925 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002926 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002927 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002928}