blob: bfe08cf5b449876913b4366d2b06f97f62f3d188 [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();
90
Roman Lebedevd55661d2018-07-24 08:16:50 +000091 void updatePartOfExplicitCastFlags(CastExpr *CE) {
92 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
93 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
94 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
Roman Lebedev12216f12018-07-27 07:27:14 +000095 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
96 ICE->setIsPartOfExplicitCast(true);
Roman Lebedevd55661d2018-07-24 08:16:50 +000097 }
98
John McCall4124c492011-10-17 18:40:02 +000099 /// Complete an apparently-successful cast operation that yields
100 /// the given expression.
101 ExprResult complete(CastExpr *castExpr) {
102 // If this is an unbridged cast, wrap the result in an implicit
103 // cast that yields the unbridged-cast placeholder type.
104 if (IsARCUnbridgedCast) {
105 castExpr = ImplicitCastExpr::Create(Self.Context,
106 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000107 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +0000108 castExpr->getValueKind());
109 }
Roman Lebedevd55661d2018-07-24 08:16:50 +0000110 updatePartOfExplicitCastFlags(castExpr);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000111 return castExpr;
John McCall4124c492011-10-17 18:40:02 +0000112 }
113
John McCall9776e432011-10-06 23:25:11 +0000114 // Internal convenience methods.
115
116 /// Try to handle the given placeholder expression kind. Return
117 /// true if the source expression has the appropriate placeholder
118 /// kind. A placeholder can only be claimed once.
119 bool claimPlaceholder(BuiltinType::Kind K) {
120 if (PlaceholderKind != K) return false;
121
122 PlaceholderKind = (BuiltinType::Kind) 0;
123 return true;
124 }
125
126 bool isPlaceholder() const {
127 return PlaceholderKind != 0;
128 }
129 bool isPlaceholder(BuiltinType::Kind K) const {
130 return PlaceholderKind == K;
131 }
John McCallb50451a2011-10-05 07:41:44 +0000132
Anastasia Stulova5325f832018-10-10 16:05:22 +0000133 // Language specific cast restrictions for address spaces.
134 void checkAddressSpaceCast(QualType SrcType, QualType DestType);
135
John McCallb50451a2011-10-05 07:41:44 +0000136 void checkCastAlign() {
137 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
138 }
139
Brian Kelley11352a82017-03-29 18:09:02 +0000140 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
141 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
John McCall4124c492011-10-17 18:40:02 +0000142
John McCallb50451a2011-10-05 07:41:44 +0000143 Expr *src = SrcExpr.get();
Brian Kelley11352a82017-03-29 18:09:02 +0000144 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
145 Sema::ACR_unbridged)
John McCall4124c492011-10-17 18:40:02 +0000146 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000147 SrcExpr = src;
148 }
John McCall9776e432011-10-06 23:25:11 +0000149
150 /// Check for and handle non-overload placeholder expressions.
151 void checkNonOverloadPlaceholders() {
152 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
153 return;
154
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000155 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000156 if (SrcExpr.isInvalid())
157 return;
158 PlaceholderKind = (BuiltinType::Kind) 0;
159 }
John McCallb50451a2011-10-05 07:41:44 +0000160 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000161}
Sebastian Redl842ef522008-11-08 13:00:26 +0000162
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000163static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
164 QualType DestType);
165
Sebastian Redl9f831db2009-07-25 15:41:38 +0000166// The Try functions attempt a specific way of casting. If they succeed, they
167// return TC_Success. If their way of casting is not appropriate for the given
168// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
169// to emit if no other way succeeds. If their way of casting is appropriate but
170// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
171// they emit a specialized diagnostic.
172// All diagnostics returned by these functions must expect the same three
173// arguments:
174// %0: Cast Type (a value from the CastType enumeration)
175// %1: Source Type
176// %2: Destination Type
177static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000178 QualType DestType, bool CStyle,
179 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000180 CXXCastPath &BasePath,
181 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000182static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000183 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000184 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000185 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000186 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000187 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000188static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
189 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000190 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000191 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000192 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000193 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000194static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
195 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000196 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000197 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000198 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000199 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000200 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000201static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000202 QualType SrcType,
203 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000204 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000205 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000206 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000207 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000208
John Wiegley01296292011-04-08 18:41:53 +0000209static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +0000210 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +0000211 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000212 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000213 unsigned &msg, CastKind &Kind,
214 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000215static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +0000216 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +0000217 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000218 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000219 unsigned &msg, CastKind &Kind,
220 CXXCastPath &BasePath,
221 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000222static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
223 QualType DestType, bool CStyle,
224 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000225static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000226 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000227 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000228 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000229 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000230
Douglas Gregorb491ed32011-02-19 21:32:49 +0000231
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000232/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000233ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000234Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000235 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000236 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000237 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000238 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000239
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000240 assert(!D.isInvalidType());
241
242 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
243 if (D.isInvalidType())
244 return ExprError();
245
David Blaikiebbafb8a2012-03-11 07:00:24 +0000246 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000247 // Check that there are no default arguments (C++ only).
248 CheckExtraCXXDefaultArguments(D);
249 }
250
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000251 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000252 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
253 SourceRange(LParenLoc, RParenLoc));
254}
255
John McCalldadc5752010-08-24 06:29:42 +0000256ExprResult
John McCalld377e042010-01-15 19:13:16 +0000257Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000258 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000259 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000260 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000261 QualType DestType = DestTInfo->getType();
262
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000263 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000264 bool TypeDependent =
265 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000266
John McCallb50451a2011-10-05 07:41:44 +0000267 CastOperation Op(*this, DestType, E);
268 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
269 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000270
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000271 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000272 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000273
274 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000275 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000276 Op.CheckConstCast();
277 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000278 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000279 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000280 }
John McCall4124c492011-10-17 18:40:02 +0000281 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000282 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000283 OpLoc, Parens.getEnd(),
284 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000285
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000286 case tok::kw_dynamic_cast: {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000287 // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
288 if (getLangOpts().OpenCLCPlusPlus) {
289 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
290 << "dynamic_cast");
291 }
292
John Wiegley01296292011-04-08 18:41:53 +0000293 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000294 Op.CheckDynamicCast();
295 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000296 return ExprError();
297 }
John McCall4124c492011-10-17 18:40:02 +0000298 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000299 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000300 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000301 OpLoc, Parens.getEnd(),
302 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000303 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000304 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000305 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000306 Op.CheckReinterpretCast();
307 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000308 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000309 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000310 }
John McCall4124c492011-10-17 18:40:02 +0000311 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000312 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000313 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000314 Parens.getEnd(),
315 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000316 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000317 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000318 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000319 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000320 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000321 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000322 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000323 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000324
John McCall4124c492011-10-17 18:40:02 +0000325 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000326 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000327 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000328 OpLoc, Parens.getEnd(),
329 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000330 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000331 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000332}
333
John McCall909acf82011-02-14 18:34:10 +0000334/// Try to diagnose a failed overloaded cast. Returns true if
335/// diagnostics were emitted.
336static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
337 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000338 QualType destType,
339 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000340 switch (CT) {
341 // These cast kinds don't consider user-defined conversions.
342 case CT_Const:
343 case CT_Reinterpret:
344 case CT_Dynamic:
345 return false;
346
347 // These do.
348 case CT_Static:
349 case CT_CStyle:
350 case CT_Functional:
351 break;
352 }
353
354 QualType srcType = src->getType();
355 if (!destType->isRecordType() && !srcType->isRecordType())
356 return false;
357
358 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
359 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000360 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000361 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000362 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000363 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000364 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000365 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000366
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000367 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000368 switch (sequence.getFailureKind()) {
369 default: return false;
370
371 case InitializationSequence::FK_ConstructorOverloadFailed:
372 case InitializationSequence::FK_UserConversionOverloadFailed:
373 break;
374 }
375
376 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
377
378 unsigned msg = 0;
379 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
380
381 switch (sequence.getFailedOverloadResult()) {
382 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000383 case OR_No_Viable_Function:
384 if (candidates.empty())
385 msg = diag::err_ovl_no_conversion_in_cast;
386 else
387 msg = diag::err_ovl_no_viable_conversion_in_cast;
388 howManyCandidates = OCD_AllCandidates;
389 break;
390
391 case OR_Ambiguous:
392 msg = diag::err_ovl_ambiguous_conversion_in_cast;
393 howManyCandidates = OCD_ViableCandidates;
394 break;
395
396 case OR_Deleted:
397 msg = diag::err_ovl_deleted_conversion_in_cast;
398 howManyCandidates = OCD_ViableCandidates;
399 break;
400 }
401
402 S.Diag(range.getBegin(), msg)
403 << CT << srcType << destType
404 << range << src->getSourceRange();
405
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000406 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000407
408 return true;
409}
410
411/// Diagnose a failed cast.
412static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000413 SourceRange opRange, Expr *src, QualType destType,
414 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000415 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000416 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
417 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000418 return;
419
420 S.Diag(opRange.getBegin(), msg) << castType
421 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000422
423 // Detect if both types are (ptr to) class, and note any incompleteness.
424 int DifferentPtrness = 0;
425 QualType From = destType;
426 if (auto Ptr = From->getAs<PointerType>()) {
427 From = Ptr->getPointeeType();
428 DifferentPtrness++;
429 }
430 QualType To = src->getType();
431 if (auto Ptr = To->getAs<PointerType>()) {
432 To = Ptr->getPointeeType();
433 DifferentPtrness--;
434 }
435 if (!DifferentPtrness) {
436 auto RecFrom = From->getAs<RecordType>();
437 auto RecTo = To->getAs<RecordType>();
438 if (RecFrom && RecTo) {
439 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
440 if (!DeclFrom->isCompleteDefinition())
441 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
442 << DeclFrom->getDeclName();
443 auto DeclTo = RecTo->getAsCXXRecordDecl();
444 if (!DeclTo->isCompleteDefinition())
445 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
446 << DeclTo->getDeclName();
447 }
448 }
John McCall909acf82011-02-14 18:34:10 +0000449}
450
Richard Smithf276e2d2018-07-10 23:04:35 +0000451namespace {
452/// The kind of unwrapping we did when determining whether a conversion casts
453/// away constness.
454enum CastAwayConstnessKind {
455 /// The conversion does not cast away constness.
456 CACK_None = 0,
457 /// We unwrapped similar types.
458 CACK_Similar = 1,
459 /// We unwrapped dissimilar types with similar representations (eg, a pointer
460 /// versus an Objective-C object pointer).
461 CACK_SimilarKind = 2,
462 /// We unwrapped representationally-unrelated types, such as a pointer versus
463 /// a pointer-to-member.
464 CACK_Incoherent = 3,
465};
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000466}
467
Richard Smithf276e2d2018-07-10 23:04:35 +0000468/// Unwrap one level of types for CastsAwayConstness.
469///
Richard Smitha3405ff2018-07-11 00:19:19 +0000470/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
471/// both types, provided that they're both pointer-like or array-like. Unlike
472/// the Sema function, doesn't care if the unwrapped pieces are related.
Richard Smith5407d4f2018-07-18 20:13:36 +0000473///
474/// This function may remove additional levels as necessary for correctness:
475/// the resulting T1 is unwrapped sufficiently that it is never an array type,
476/// so that its qualifiers can be directly compared to those of T2 (which will
477/// have the combined set of qualifiers from all indermediate levels of T2),
478/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
479/// with those from T2.
Richard Smithf276e2d2018-07-10 23:04:35 +0000480static CastAwayConstnessKind
481unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000482 enum { None, Ptr, MemPtr, BlockPtr, Array };
Richard Smithf276e2d2018-07-10 23:04:35 +0000483 auto Classify = [](QualType T) {
Richard Smith5407d4f2018-07-18 20:13:36 +0000484 if (T->isAnyPointerType()) return Ptr;
485 if (T->isMemberPointerType()) return MemPtr;
486 if (T->isBlockPointerType()) return BlockPtr;
Richard Smitha3405ff2018-07-11 00:19:19 +0000487 // We somewhat-arbitrarily don't look through VLA types here. This is at
488 // least consistent with the behavior of UnwrapSimilarTypes.
Richard Smith5407d4f2018-07-18 20:13:36 +0000489 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
490 return None;
Richard Smithf276e2d2018-07-10 23:04:35 +0000491 };
492
Richard Smitha3405ff2018-07-11 00:19:19 +0000493 auto Unwrap = [&](QualType T) {
494 if (auto *AT = Context.getAsArrayType(T))
495 return AT->getElementType();
496 return T->getPointeeType();
497 };
498
Richard Smith5407d4f2018-07-18 20:13:36 +0000499 CastAwayConstnessKind Kind;
500
501 if (T2->isReferenceType()) {
502 // Special case: if the destination type is a reference type, unwrap it as
503 // the first level. (The source will have been an lvalue expression in this
504 // case, so there is no corresponding "reference to" in T1 to remove.) This
505 // simulates removing a "pointer to" from both sides.
506 T2 = T2->getPointeeType();
507 Kind = CastAwayConstnessKind::CACK_Similar;
508 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
509 Kind = CastAwayConstnessKind::CACK_Similar;
510 } else {
511 // Try unwrapping mismatching levels.
512 int T1Class = Classify(T1);
513 if (T1Class == None)
514 return CastAwayConstnessKind::CACK_None;
515
516 int T2Class = Classify(T2);
517 if (T2Class == None)
518 return CastAwayConstnessKind::CACK_None;
519
520 T1 = Unwrap(T1);
521 T2 = Unwrap(T2);
522 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
523 : CastAwayConstnessKind::CACK_Incoherent;
524 }
525
526 // We've unwrapped at least one level. If the resulting T1 is a (possibly
527 // multidimensional) array type, any qualifier on any matching layer of
528 // T2 is considered to correspond to T1. Decompose down to the element
529 // type of T1 so that we can compare properly.
530 while (true) {
531 Context.UnwrapSimilarArrayTypes(T1, T2);
532
533 if (Classify(T1) != Array)
534 break;
535
536 auto T2Class = Classify(T2);
537 if (T2Class == None)
538 break;
539
540 if (T2Class != Array)
541 Kind = CastAwayConstnessKind::CACK_Incoherent;
542 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
543 Kind = CastAwayConstnessKind::CACK_SimilarKind;
544
545 T1 = Unwrap(T1);
546 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
547 }
548
549 return Kind;
Richard Smithf276e2d2018-07-10 23:04:35 +0000550}
551
552/// Check if the pointer conversion from SrcType to DestType casts away
553/// constness as defined in C++ [expr.const.cast]. This is used by the cast
554/// checkers. Both arguments must denote pointer (possibly to member) types.
John McCall31168b02011-06-15 23:02:42 +0000555///
556/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
John McCall31168b02011-06-15 23:02:42 +0000557/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Richard Smithf276e2d2018-07-10 23:04:35 +0000558static CastAwayConstnessKind
John McCall31168b02011-06-15 23:02:42 +0000559CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000560 bool CheckCVR, bool CheckObjCLifetime,
561 QualType *TheOffendingSrcType = nullptr,
562 QualType *TheOffendingDestType = nullptr,
563 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000564 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000565 // and we're not in ObjC mode, there's nothing to check.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000566 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
Richard Smithf276e2d2018-07-10 23:04:35 +0000567 return CastAwayConstnessKind::CACK_None;
568
569 if (!DestType->isReferenceType()) {
570 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
571 SrcType->isBlockPointerType()) &&
572 "Source type is not pointer or pointer to member.");
573 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
574 DestType->isBlockPointerType()) &&
575 "Destination type is not pointer or pointer to member.");
576 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000577
Fangrui Song6907ce22018-07-30 19:24:48 +0000578 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000579 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000580
Fangrui Song6907ce22018-07-30 19:24:48 +0000581 // Find the qualifiers. We only care about cvr-qualifiers for the
582 // purpose of this check, because other qualifiers (address spaces,
Douglas Gregorb472e932011-04-15 17:59:54 +0000583 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000584 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
585 QualType PrevUnwrappedDestType = UnwrappedDestType;
Richard Smithf276e2d2018-07-10 23:04:35 +0000586 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
587 bool AllConstSoFar = true;
588 while (auto Kind = unwrapCastAwayConstnessLevel(
589 Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
590 // Track the worst kind of unwrap we needed to do before we found a
591 // problem.
592 if (Kind > WorstKind)
593 WorstKind = Kind;
594
John McCall31168b02011-06-15 23:02:42 +0000595 // Determine the relevant qualifiers at this level.
596 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000597 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000598 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Akira Hatanaka8d7bdf62017-08-11 00:06:49 +0000599
600 // We do not meaningfully track object const-ness of Objective-C object
601 // types. Remove const from the source type if either the source or
602 // the destination is an Objective-C object type.
603 if (UnwrappedSrcType->isObjCObjectType() ||
604 UnwrappedDestType->isObjCObjectType())
605 SrcQuals.removeConst();
606
John McCall31168b02011-06-15 23:02:42 +0000607 if (CheckCVR) {
Richard Smithf276e2d2018-07-10 23:04:35 +0000608 Qualifiers SrcCvrQuals =
609 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
610 Qualifiers DestCvrQuals =
611 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000612
Richard Smithf276e2d2018-07-10 23:04:35 +0000613 if (SrcCvrQuals != DestCvrQuals) {
614 if (CastAwayQualifiers)
615 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
616
617 // If we removed a cvr-qualifier, this is casting away 'constness'.
618 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
619 if (TheOffendingSrcType)
620 *TheOffendingSrcType = PrevUnwrappedSrcType;
621 if (TheOffendingDestType)
622 *TheOffendingDestType = PrevUnwrappedDestType;
623 return WorstKind;
624 }
625
626 // If any prior level was not 'const', this is also casting away
627 // 'constness'. We noted the outermost type missing a 'const' already.
628 if (!AllConstSoFar)
629 return WorstKind;
Roman Divackyd5178012014-11-21 21:03:10 +0000630 }
John McCall31168b02011-06-15 23:02:42 +0000631 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000632
John McCall31168b02011-06-15 23:02:42 +0000633 if (CheckObjCLifetime &&
634 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
Richard Smithf276e2d2018-07-10 23:04:35 +0000635 return WorstKind;
636
637 // If we found our first non-const-qualified type, this may be the place
638 // where things start to go wrong.
639 if (AllConstSoFar && !DestQuals.hasConst()) {
640 AllConstSoFar = false;
641 if (TheOffendingSrcType)
642 *TheOffendingSrcType = PrevUnwrappedSrcType;
643 if (TheOffendingDestType)
644 *TheOffendingDestType = PrevUnwrappedDestType;
645 }
Roman Divackyd5178012014-11-21 21:03:10 +0000646
647 PrevUnwrappedSrcType = UnwrappedSrcType;
648 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000649 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000650
Richard Smithf276e2d2018-07-10 23:04:35 +0000651 return CastAwayConstnessKind::CACK_None;
652}
653
654static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
655 unsigned &DiagID) {
656 switch (CACK) {
657 case CastAwayConstnessKind::CACK_None:
658 llvm_unreachable("did not cast away constness");
659
660 case CastAwayConstnessKind::CACK_Similar:
661 // FIXME: Accept these as an extension too?
662 case CastAwayConstnessKind::CACK_SimilarKind:
663 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
664 return TC_Failed;
665
666 case CastAwayConstnessKind::CACK_Incoherent:
667 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
668 return TC_Extension;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000669 }
670
Richard Smithf276e2d2018-07-10 23:04:35 +0000671 llvm_unreachable("unexpected cast away constness kind");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000672}
673
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000674/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
675/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
676/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000677void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000678 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000679 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000680 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000681 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000682 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
683 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000684
John McCallb50451a2011-10-05 07:41:44 +0000685 QualType OrigSrcType = SrcExpr.get()->getType();
686 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000687
688 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
689 // or "pointer to cv void".
690
691 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000692 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000693 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000694 if (DestPointer) {
695 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000696 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000697 DestPointee = DestReference->getPointeeType();
698 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000699 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000700 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000701 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000702 return;
703 }
704
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000705 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000706 if (DestPointee->isVoidType()) {
707 assert(DestPointer && "Reference to void is not possible");
708 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000709 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000710 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000711 DestRange)) {
712 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000713 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000714 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000715 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000716 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000717 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000718 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000719 return;
720 }
721
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000722 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
723 // complete class type, [...]. If T is an lvalue reference type, v shall be
Fangrui Song6907ce22018-07-30 19:24:48 +0000724 // an lvalue of a complete class type, [...]. If T is an rvalue reference
Douglas Gregor465184a2011-01-22 00:06:57 +0000725 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000726 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000727 QualType SrcPointee;
728 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000729 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000730 SrcPointee = SrcPointer->getPointeeType();
731 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000732 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000733 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000734 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000735 return;
736 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000737 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000738 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000739 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000740 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000741 }
742 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000743 } else {
Richard Smith11330852014-07-08 17:25:14 +0000744 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
745 // to materialize the prvalue before we bind the reference to it.
746 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000747 SrcExpr = Self.CreateMaterializeTemporaryExpr(
748 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000749 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000750 }
751
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000752 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000753 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000754 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000755 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000756 SrcExpr.get())) {
757 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000758 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000759 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000760 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000761 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000762 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000763 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000764 return;
765 }
766
767 assert((DestPointer || DestReference) &&
768 "Bad destination non-ptr/ref slipped through.");
769 assert((DestRecord || DestPointee->isVoidType()) &&
770 "Bad destination pointee slipped through.");
771 assert(SrcRecord && "Bad source pointee slipped through.");
772
773 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
774 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000775 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000776 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000777 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000778 return;
779 }
780
781 // C++ 5.2.7p3: If the type of v is the same as the required result type,
782 // [except for cv].
783 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000784 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000785 return;
786 }
787
788 // C++ 5.2.7p5
789 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000790 if (DestRecord &&
791 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000792 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Fangrui Song6907ce22018-07-30 19:24:48 +0000793 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000794 &BasePath)) {
795 SrcExpr = ExprError();
796 return;
797 }
Richard Smith11330852014-07-08 17:25:14 +0000798
John McCalle3027922010-08-25 11:45:40 +0000799 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000800 return;
801 }
802
803 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000804 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000805 assert(SrcDecl && "Definition missing");
806 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000807 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000808 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000809 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000810 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000811
Eli Friedman3ce27102013-09-24 23:21:41 +0000812 // dynamic_cast is not available with -fno-rtti.
813 // As an exception, dynamic_cast to void* is available because it doesn't
814 // use RTTI.
815 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000816 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
817 SrcExpr = ExprError();
818 return;
819 }
820
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000821 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000822 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000823}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000824
825/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
826/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
827/// like this:
828/// const char *str = "literal";
829/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000830void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000831 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000832 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000833 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000834 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000835 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
836 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000837
838 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smithf276e2d2018-07-10 23:04:35 +0000839 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
840 if (TCR != TC_Success && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000841 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000842 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000843 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000844 if (!isValidCast(TCR))
845 SrcExpr = ExprError();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000846}
847
John McCallcda80832013-03-22 02:58:14 +0000848/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
849/// or downcast between respective pointers or references.
850static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
851 QualType DestType,
852 SourceRange OpRange) {
853 QualType SrcType = SrcExpr->getType();
854 // When casting from pointer or reference, get pointee type; use original
855 // type otherwise.
856 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
857 const CXXRecordDecl *SrcRD =
858 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
859
John McCallf2abe192013-03-27 00:03:48 +0000860 // Examining subobjects for records is only possible if the complete and
861 // valid definition is available. Also, template instantiation is not
862 // allowed here.
863 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000864 return;
865
866 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
867
John McCallf2abe192013-03-27 00:03:48 +0000868 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000869 return;
870
871 enum {
872 ReinterpretUpcast,
873 ReinterpretDowncast
874 } ReinterpretKind;
875
876 CXXBasePaths BasePaths;
877
878 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
879 ReinterpretKind = ReinterpretUpcast;
880 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
881 ReinterpretKind = ReinterpretDowncast;
882 else
883 return;
884
885 bool VirtualBase = true;
886 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000887 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000888 E = BasePaths.end();
889 I != E; ++I) {
890 const CXXBasePath &Path = *I;
891 CharUnits Offset = CharUnits::Zero();
892 bool IsVirtual = false;
893 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
894 IElem != EElem; ++IElem) {
895 IsVirtual = IElem->Base->isVirtual();
896 if (IsVirtual)
897 break;
898 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
899 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000900 // Don't check if any base has invalid declaration or has no definition
901 // since it has no layout info.
902 const CXXRecordDecl *Class = IElem->Class,
903 *ClassDefinition = Class->getDefinition();
904 if (Class->isInvalidDecl() || !ClassDefinition ||
905 !ClassDefinition->isCompleteDefinition())
906 return;
907
John McCallcda80832013-03-22 02:58:14 +0000908 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000909 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000910 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
911 }
912 if (!IsVirtual) {
913 // Don't warn if any path is a non-virtually derived base at offset zero.
914 if (Offset.isZero())
915 return;
916 // Offset makes sense only for non-virtual bases.
917 else
918 NonZeroOffset = true;
919 }
920 VirtualBase = VirtualBase && IsVirtual;
921 }
922
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000923 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000924 assert((VirtualBase || NonZeroOffset) &&
925 "Should have returned if has non-virtual base with zero offset");
926
927 QualType BaseType =
928 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
929 QualType DerivedType =
930 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
931
Jordan Rose04a94d12013-03-28 19:09:40 +0000932 SourceLocation BeginLoc = OpRange.getBegin();
933 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000934 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000935 << OpRange;
936 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000937 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000938 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000939}
940
Sebastian Redl9f831db2009-07-25 15:41:38 +0000941/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
942/// valid.
943/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
944/// like this:
945/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000946void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000947 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000948 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000949 else
950 checkNonOverloadPlaceholders();
951 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
952 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000953
954 unsigned msg = diag::err_bad_cxx_cast_generic;
Fangrui Song6907ce22018-07-30 19:24:48 +0000955 TryCastResult tcr =
956 TryReinterpretCast(Self, SrcExpr, DestType,
John McCall31168b02011-06-15 23:02:42 +0000957 /*CStyle*/false, OpRange, msg, Kind);
Richard Smithf276e2d2018-07-10 23:04:35 +0000958 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000959 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
960 return;
961 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000962 //FIXME: &f<int>; is overloaded and resolvable
963 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000964 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000965 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000966 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000967
John McCall909acf82011-02-14 18:34:10 +0000968 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000969 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
970 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000971 }
Richard Smithf276e2d2018-07-10 23:04:35 +0000972 }
973
974 if (isValidCast(tcr)) {
Brian Kelley762f9282017-03-29 18:16:38 +0000975 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000976 checkObjCConversion(Sema::CCK_OtherCast);
John McCallcda80832013-03-22 02:58:14 +0000977 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
Richard Smithf276e2d2018-07-10 23:04:35 +0000978 } else {
979 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000980 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000981}
982
983
984/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
985/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
986/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000987void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000988 if (isPlaceholder()) {
989 checkNonOverloadPlaceholders();
990 if (SrcExpr.isInvalid())
991 return;
992 }
993
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 // This test is outside everything else because it's the only case where
995 // a non-lvalue-reference target type does not lead to decay.
996 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000997 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000998 Kind = CK_ToVoid;
999
1000 if (claimPlaceholder(BuiltinType::Overload)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001001 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1002 false, // Decay Function to ptr
Douglas Gregorb491ed32011-02-19 21:32:49 +00001003 true, // Complain
1004 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +00001005 if (SrcExpr.isInvalid())
1006 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001007 }
John McCall9776e432011-10-06 23:25:11 +00001008
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001009 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001010 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001011 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001012
John McCall50a2c2c2011-10-11 23:14:30 +00001013 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1014 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001015 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00001016 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1017 return;
1018 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001019
1020 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +00001021 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +00001022 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001023 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +00001024 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +00001025 if (SrcExpr.isInvalid())
1026 return;
1027 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1028 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +00001029 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Fangrui Song6907ce22018-07-30 19:24:48 +00001030 << oe->getName() << DestType << OpRange
Douglas Gregor0da1d432011-02-28 20:01:57 +00001031 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00001032 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +00001033 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +00001034 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1035 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001036 }
Richard Smithf276e2d2018-07-10 23:04:35 +00001037 }
1038
1039 if (isValidCast(tcr)) {
John McCall31168b02011-06-15 23:02:42 +00001040 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +00001041 checkCastAlign();
Brian Kelley762f9282017-03-29 18:16:38 +00001042 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +00001043 checkObjCConversion(Sema::CCK_OtherCast);
Richard Smithf276e2d2018-07-10 23:04:35 +00001044 } else {
1045 SrcExpr = ExprError();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001046 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001047}
1048
Yaxun Liu4b06ffe2018-08-03 03:18:56 +00001049static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1050 auto *SrcPtrType = SrcType->getAs<PointerType>();
1051 if (!SrcPtrType)
1052 return false;
1053 auto *DestPtrType = DestType->getAs<PointerType>();
1054 if (!DestPtrType)
1055 return false;
1056 return SrcPtrType->getPointeeType().getAddressSpace() !=
1057 DestPtrType->getPointeeType().getAddressSpace();
1058}
1059
Sebastian Redl9f831db2009-07-25 15:41:38 +00001060/// TryStaticCast - Check if a static cast can be performed, and do so if
1061/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1062/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +00001063static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Fangrui Song6907ce22018-07-30 19:24:48 +00001064 QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001065 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001066 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001067 CastKind &Kind, CXXCastPath &BasePath,
1068 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +00001069 // Determine whether we have the semantics of a C-style cast.
Fangrui Song6907ce22018-07-30 19:24:48 +00001070 bool CStyle
John McCall31168b02011-06-15 23:02:42 +00001071 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Fangrui Song6907ce22018-07-30 19:24:48 +00001072
Sebastian Redl9f831db2009-07-25 15:41:38 +00001073 // The order the tests is not entirely arbitrary. There is one conversion
1074 // that can be handled in two different ways. Given:
1075 // struct A {};
1076 // struct B : public A {
1077 // B(); B(const A&);
1078 // };
1079 // const A &a = B();
1080 // the cast static_cast<const B&>(a) could be seen as either a static
1081 // reference downcast, or an explicit invocation of the user-defined
1082 // conversion using B's conversion constructor.
1083 // DR 427 specifies that the downcast is to be applied here.
1084
1085 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1086 // Done outside this function.
1087
1088 TryCastResult tcr;
1089
1090 // C++ 5.2.9p5, reference downcast.
1091 // See the function for details.
1092 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +00001093 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1094 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001095 if (tcr != TC_NotApplicable)
1096 return tcr;
1097
Fangrui Song6907ce22018-07-30 19:24:48 +00001098 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001099 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1100 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001101 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
Sebastian Redld74dd492012-02-12 18:41:05 +00001102 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +00001103 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001104 return tcr;
1105
1106 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1107 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +00001108 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001109 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +00001110 if (SrcExpr.isInvalid())
1111 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001112 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001113 return tcr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001114
Sebastian Redl9f831db2009-07-25 15:41:38 +00001115 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1116 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1117 // conversions, subject to further restrictions.
1118 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1119 // of qualification conversions impossible.
1120 // In the CStyle case, the earlier attempt to const_cast should have taken
1121 // care of reverse qualification conversions.
1122
John Wiegley01296292011-04-08 18:41:53 +00001123 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001124
Douglas Gregor0bf31402010-10-08 23:50:27 +00001125 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001126 // converted to an integral type. [...] A value of a scoped enumeration type
1127 // can also be explicitly converted to a floating-point type [...].
1128 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1129 if (Enum->getDecl()->isScoped()) {
1130 if (DestType->isBooleanType()) {
1131 Kind = CK_IntegralToBoolean;
1132 return TC_Success;
1133 } else if (DestType->isIntegralType(Self.Context)) {
1134 Kind = CK_IntegralCast;
1135 return TC_Success;
1136 } else if (DestType->isRealFloatingType()) {
1137 Kind = CK_IntegralToFloating;
1138 return TC_Success;
1139 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001140 }
1141 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001142
Sebastian Redl9f831db2009-07-25 15:41:38 +00001143 // Reverse integral promotion/conversion. All such conversions are themselves
1144 // again integral promotions or conversions and are thus already handled by
1145 // p2 (TryDirectInitialization above).
1146 // (Note: any data loss warnings should be suppressed.)
1147 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1148 // enum->enum). See also C++ 5.2.9p7.
1149 // The same goes for reverse floating point promotion/conversion and
1150 // floating-integral conversions. Again, only floating->enum is relevant.
1151 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001152 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001153 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001154 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001155 } else if (SrcType->isRealFloatingType()) {
1156 Kind = CK_FloatingToIntegral;
1157 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001158 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001159 }
1160
1161 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1162 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001163 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001164 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001165 if (tcr != TC_NotApplicable)
1166 return tcr;
1167
1168 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1169 // conversion. C++ 5.2.9p9 has additional information.
1170 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001171 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001172 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001173 if (tcr != TC_NotApplicable)
1174 return tcr;
1175
1176 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1177 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1178 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001179 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001180 QualType SrcPointee = SrcPointer->getPointeeType();
1181 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001182 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001183 QualType DestPointee = DestPointer->getPointeeType();
1184 if (DestPointee->isIncompleteOrObjectType()) {
1185 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001186 // to a qualifier violation. Note that we permit Objective-C lifetime
1187 // and GC qualifier mismatches here.
1188 if (!CStyle) {
1189 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1190 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1191 DestPointeeQuals.removeObjCGCAttr();
1192 DestPointeeQuals.removeObjCLifetime();
1193 SrcPointeeQuals.removeObjCGCAttr();
1194 SrcPointeeQuals.removeObjCLifetime();
1195 if (DestPointeeQuals != SrcPointeeQuals &&
1196 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1197 msg = diag::err_bad_cxx_cast_qualifiers_away;
1198 return TC_Failed;
1199 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001200 }
Yaxun Liu4b06ffe2018-08-03 03:18:56 +00001201 Kind = IsAddressSpaceConversion(SrcType, DestType)
1202 ? CK_AddressSpaceConversion
1203 : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001204 return TC_Success;
1205 }
David Majnemer85bd1202015-06-02 22:15:12 +00001206
1207 // Microsoft permits static_cast from 'pointer-to-void' to
1208 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001209 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1210 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001211 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1212 Kind = CK_BitCast;
1213 return TC_Success;
1214 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001215 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001216 else if (DestType->isObjCObjectPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001217 // allow both c-style cast and static_cast of objective-c pointers as
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001218 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001219 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001220 return TC_Success;
1221 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001222 else if (CStyle && DestType->isBlockPointerType()) {
1223 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001224 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001225 return TC_Success;
1226 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001227 }
1228 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001229 // Allow arbitrary objective-c pointer conversion with static casts.
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001230 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001231 DestType->isObjCObjectPointerType()) {
1232 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001233 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001234 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001235 // Allow ns-pointer to cf-pointer conversion in either direction
1236 // with static casts.
1237 if (!CStyle &&
1238 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1239 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001240
1241 // See if it looks like the user is trying to convert between
1242 // related record types, and select a better diagnostic if so.
1243 if (auto SrcPointer = SrcType->getAs<PointerType>())
1244 if (auto DestPointer = DestType->getAs<PointerType>())
1245 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1246 DestPointer->getPointeeType()->getAs<RecordType>())
1247 msg = diag::err_bad_cxx_cast_unrelated_class;
Fangrui Song6907ce22018-07-30 19:24:48 +00001248
Sebastian Redl9f831db2009-07-25 15:41:38 +00001249 // We tried everything. Everything! Nothing works! :-(
1250 return TC_NotApplicable;
1251}
1252
1253/// Tests whether a conversion according to N2844 is valid.
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001254TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1255 QualType DestType, bool CStyle,
1256 CastKind &Kind, CXXCastPath &BasePath,
1257 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001258 // C++11 [expr.static.cast]p3:
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001259 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
Douglas Gregor465184a2011-01-22 00:06:57 +00001260 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001261 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001262 if (!R)
1263 return TC_NotApplicable;
1264
Douglas Gregor465184a2011-01-22 00:06:57 +00001265 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001266 return TC_NotApplicable;
1267
1268 // Because we try the reference downcast before this function, from now on
1269 // this is the only cast possibility, so we issue an error if we fail now.
1270 // FIXME: Should allow casting away constness if CStyle.
1271 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001272 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001273 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001274 QualType FromType = SrcExpr->getType();
1275 QualType ToType = R->getPointeeType();
1276 if (CStyle) {
1277 FromType = FromType.getUnqualifiedType();
1278 ToType = ToType.getUnqualifiedType();
1279 }
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001280
1281 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001282 SrcExpr->getBeginLoc(), ToType, FromType, DerivedToBase, ObjCConversion,
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001283 ObjCLifetimeConversion);
1284 if (RefResult != Sema::Ref_Compatible) {
1285 if (CStyle || RefResult == Sema::Ref_Incompatible)
Davide Italianoa2275912015-07-12 22:10:56 +00001286 return TC_NotApplicable;
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001287 // Diagnose types which are reference-related but not compatible here since
1288 // we can provide better diagnostics. In these cases forwarding to
1289 // [expr.static.cast]p4 should never result in a well-formed cast.
1290 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1291 : diag::err_bad_rvalue_to_rvalue_cast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001292 return TC_Failed;
1293 }
1294
Douglas Gregorba278e22011-01-25 16:13:26 +00001295 if (DerivedToBase) {
1296 Kind = CK_DerivedToBase;
1297 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1298 /*DetectVirtual=*/true);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001299 if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
Richard Smith0f59cb32015-12-18 21:45:41 +00001300 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001301 return TC_NotApplicable;
Fangrui Song6907ce22018-07-30 19:24:48 +00001302
Douglas Gregorba278e22011-01-25 16:13:26 +00001303 Self.BuildBasePathArray(Paths, BasePath);
1304 } else
1305 Kind = CK_NoOp;
Fangrui Song6907ce22018-07-30 19:24:48 +00001306
Sebastian Redl9f831db2009-07-25 15:41:38 +00001307 return TC_Success;
1308}
1309
1310/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1311TryCastResult
1312TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001313 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001314 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001315 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001316 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1317 // cast to type "reference to cv2 D", where D is a class derived from B,
1318 // if a valid standard conversion from "pointer to D" to "pointer to B"
1319 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1320 // In addition, DR54 clarifies that the base must be accessible in the
1321 // current context. Although the wording of DR54 only applies to the pointer
1322 // variant of this rule, the intent is clearly for it to apply to the this
1323 // conversion as well.
1324
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001325 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001326 if (!DestReference) {
1327 return TC_NotApplicable;
1328 }
1329 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001330 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001331 // We know the left side is an lvalue reference, so we can suggest a reason.
1332 msg = diag::err_bad_cxx_cast_rvalue;
1333 return TC_NotApplicable;
1334 }
1335
1336 QualType DestPointee = DestReference->getPointeeType();
1337
Richard Smith11330852014-07-08 17:25:14 +00001338 // FIXME: If the source is a prvalue, we should issue a warning (because the
1339 // cast always has undefined behavior), and for AST consistency, we should
1340 // materialize a temporary.
Fangrui Song6907ce22018-07-30 19:24:48 +00001341 return TryStaticDowncast(Self,
1342 Self.Context.getCanonicalType(SrcExpr->getType()),
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001343 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001344 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1345 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001346}
1347
1348/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1349TryCastResult
1350TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001351 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001352 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001353 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001354 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1355 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1356 // is a class derived from B, if a valid standard conversion from "pointer
1357 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1358 // class of D.
1359 // In addition, DR54 clarifies that the base must be accessible in the
1360 // current context.
1361
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001362 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001363 if (!DestPointer) {
1364 return TC_NotApplicable;
1365 }
1366
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001367 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001368 if (!SrcPointer) {
1369 msg = diag::err_bad_static_cast_pointer_nonpointer;
1370 return TC_NotApplicable;
1371 }
1372
Fangrui Song6907ce22018-07-30 19:24:48 +00001373 return TryStaticDowncast(Self,
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001374 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001375 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001376 CStyle, OpRange, SrcType, DestType, msg, Kind,
1377 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001378}
1379
1380/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1381/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001382/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001383TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001384TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001385 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Fangrui Song6907ce22018-07-30 19:24:48 +00001386 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001387 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001388 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001389 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1390 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001391 return TC_NotApplicable;
1392
Sebastian Redl9f831db2009-07-25 15:41:38 +00001393 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001394 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001395 return TC_NotApplicable;
1396 }
1397
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001398 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001399 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001400 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001401 return TC_NotApplicable;
1402 }
1403
1404 // Target type does derive from source type. Now we're serious. If an error
1405 // appears now, it's not ignored.
1406 // This may not be entirely in line with the standard. Take for example:
1407 // struct A {};
1408 // struct B : virtual A {
1409 // B(A&);
1410 // };
Mike Stump11289f42009-09-09 15:08:12 +00001411 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001412 // void f()
1413 // {
1414 // (void)static_cast<const B&>(*((A*)0));
1415 // }
1416 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1417 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1418 // However, both GCC and Comeau reject this example, and accepting it would
1419 // mean more complex code if we're to preserve the nice error message.
1420 // FIXME: Being 100% compliant here would be nice to have.
1421
1422 // Must preserve cv, as always, unless we're in C-style mode.
1423 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001424 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001425 return TC_Failed;
1426 }
1427
1428 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1429 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1430 // that it builds the paths in reverse order.
1431 // To sum up: record all paths to the base and build a nice string from
1432 // them. Use it to spice up the error message.
1433 if (!Paths.isRecordingPaths()) {
1434 Paths.clear();
1435 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001436 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001437 }
1438 std::string PathDisplayStr;
1439 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001440 for (clang::CXXBasePath &Path : Paths) {
1441 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001442 // We haven't displayed a path to this particular base
1443 // class subobject yet.
1444 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001445 for (CXXBasePathElement &PE : llvm::reverse(Path))
1446 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001447 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001448 }
1449 }
1450
1451 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Fangrui Song6907ce22018-07-30 19:24:48 +00001452 << QualType(SrcType).getUnqualifiedType()
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001453 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001454 << PathDisplayStr << OpRange;
1455 msg = 0;
1456 return TC_Failed;
1457 }
1458
Craig Topperc3ec1492014-05-26 06:22:03 +00001459 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001460 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1461 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1462 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1463 msg = 0;
1464 return TC_Failed;
1465 }
1466
John McCallfe9cf0a2011-02-14 23:21:33 +00001467 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001468 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1469 SrcType, DestType,
1470 Paths.front(),
1471 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001472 case Sema::AR_accessible:
1473 case Sema::AR_delayed: // be optimistic
1474 case Sema::AR_dependent: // be optimistic
1475 break;
1476
1477 case Sema::AR_inaccessible:
1478 msg = 0;
1479 return TC_Failed;
1480 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001481 }
1482
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001483 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001484 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001485 return TC_Success;
1486}
1487
1488/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1489/// C++ 5.2.9p9 is valid:
1490///
1491/// An rvalue of type "pointer to member of D of type cv1 T" can be
1492/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1493/// where B is a base class of D [...].
1494///
1495TryCastResult
Fangrui Song6907ce22018-07-30 19:24:48 +00001496TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1497 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001498 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001499 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001500 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001501 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001502 if (!DestMemPtr)
1503 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001504
1505 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001506 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001507 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001508 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001509 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001510 FoundOverload)) {
1511 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1512 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1513 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1514 WasOverloadedFunction = true;
1515 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001516 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001517
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001518 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001519 if (!SrcMemPtr) {
1520 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1521 return TC_NotApplicable;
1522 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001523
1524 // Lock down the inheritance model right now in MS ABI, whether or not the
1525 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001526 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001527 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001528 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1529 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001530
1531 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001532 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1533 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001534 return TC_NotApplicable;
1535
1536 // B base of D
1537 QualType SrcClass(SrcMemPtr->getClass(), 0);
1538 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001539 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001540 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001541 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001542 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001543
1544 // 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 +00001545 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001546 Paths.clear();
1547 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001548 bool StillOkay =
1549 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001550 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001551 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001552 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1553 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1554 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1555 msg = 0;
1556 return TC_Failed;
1557 }
1558
1559 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1560 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1561 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1562 msg = 0;
1563 return TC_Failed;
1564 }
1565
John McCallfe9cf0a2011-02-14 23:21:33 +00001566 if (!CStyle) {
1567 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1568 DestClass, SrcClass,
1569 Paths.front(),
1570 diag::err_upcast_to_inaccessible_base)) {
1571 case Sema::AR_accessible:
1572 case Sema::AR_delayed:
1573 case Sema::AR_dependent:
1574 // Optimistically assume that the delayed and dependent cases
1575 // will work out.
1576 break;
1577
1578 case Sema::AR_inaccessible:
1579 msg = 0;
1580 return TC_Failed;
1581 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001582 }
1583
Douglas Gregorc934bc82010-03-07 23:24:59 +00001584 if (WasOverloadedFunction) {
1585 // Resolve the address of the overloaded function again, this time
1586 // allowing complaints if something goes wrong.
Fangrui Song6907ce22018-07-30 19:24:48 +00001587 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1588 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001589 true,
1590 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001591 if (!Fn) {
1592 msg = 0;
1593 return TC_Failed;
1594 }
1595
John McCall16df1e52010-03-30 21:47:33 +00001596 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001597 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001598 msg = 0;
1599 return TC_Failed;
1600 }
1601 }
1602
Anders Carlssonb78feca2010-04-24 19:22:20 +00001603 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001604 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001605 return TC_Success;
1606}
1607
1608/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1609/// is valid:
1610///
1611/// An expression e can be explicitly converted to a type T using a
1612/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1613TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001614TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Fangrui Song6907ce22018-07-30 19:24:48 +00001615 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001616 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001617 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001618 if (DestType->isRecordType()) {
1619 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001620 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001621 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001622 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001623 msg = 0;
1624 return TC_Failed;
1625 }
1626 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001627
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001628 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1629 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001630 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001631 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001632 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001633 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001634 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001635 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001636 Expr *SrcExprRaw = SrcExpr.get();
Richard Smithb8c0f552016-12-09 18:49:13 +00001637 // FIXME: Per DR242, we should check for an implicit conversion sequence
1638 // or for a constructor that could be invoked by direct-initialization
1639 // here, not for an initialization sequence.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001640 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001641
1642 // At this point of CheckStaticCast, if the destination is a reference,
Fangrui Song6907ce22018-07-30 19:24:48 +00001643 // or the expression is an overload expression this has to work.
Douglas Gregore81f58e2010-11-08 03:40:48 +00001644 // There is no other way that works.
1645 // On the other hand, if we're checking a C-style cast, we've still got
1646 // the reinterpret_cast way.
Fangrui Song6907ce22018-07-30 19:24:48 +00001647 bool CStyle
John McCall31168b02011-06-15 23:02:42 +00001648 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001649 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001650 return TC_NotApplicable;
Fangrui Song6907ce22018-07-30 19:24:48 +00001651
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001652 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001653 if (Result.isInvalid()) {
1654 msg = 0;
1655 return TC_Failed;
1656 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001657
Douglas Gregorb33eed02010-04-16 22:09:46 +00001658 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001659 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001660 else
John McCalle3027922010-08-25 11:45:40 +00001661 Kind = CK_NoOp;
Fangrui Song6907ce22018-07-30 19:24:48 +00001662
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001663 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001664 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001665}
1666
1667/// TryConstCast - See if a const_cast from source to destination is allowed,
1668/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001669static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1670 QualType DestType, bool CStyle,
1671 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001672 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001673 QualType SrcType = SrcExpr.get()->getType();
1674 bool NeedToMaterializeTemporary = false;
1675
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001676 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001677 // C++11 5.2.11p4:
1678 // if a pointer to T1 can be explicitly converted to the type "pointer to
1679 // T2" using a const_cast, then the following conversions can also be
1680 // made:
1681 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1682 // type T2 using the cast const_cast<T2&>;
1683 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1684 // type T2 using the cast const_cast<T2&&>; and
1685 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1686 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1687
1688 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001689 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1690 // is C-style, static_cast might find a way, so we simply suggest a
1691 // message and tell the parent to keep searching.
1692 msg = diag::err_bad_cxx_cast_rvalue;
1693 return TC_NotApplicable;
1694 }
1695
Richard Smith82c9b512013-06-14 22:27:52 +00001696 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1697 if (!SrcType->isRecordType()) {
1698 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1699 // this is C-style, static_cast can do this.
1700 msg = diag::err_bad_cxx_cast_rvalue;
1701 return TC_NotApplicable;
1702 }
1703
1704 // Materialize the class prvalue so that the const_cast can bind a
1705 // reference to it.
1706 NeedToMaterializeTemporary = true;
1707 }
1708
John McCalld25db7e2013-05-06 21:39:12 +00001709 // It's not completely clear under the standard whether we can
1710 // const_cast bit-field gl-values. Doing so would not be
1711 // intrinsically complicated, but for now, we say no for
1712 // consistency with other compilers and await the word of the
1713 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001714 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001715 msg = diag::err_bad_cxx_cast_bitfield;
1716 return TC_NotApplicable;
1717 }
1718
Sebastian Redl9f831db2009-07-25 15:41:38 +00001719 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1720 SrcType = Self.Context.getPointerType(SrcType);
1721 }
1722
1723 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1724 // the rules for const_cast are the same as those used for pointers.
1725
John McCall0e704f72010-05-18 09:35:29 +00001726 if (!DestType->isPointerType() &&
1727 !DestType->isMemberPointerType() &&
1728 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001729 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1730 // was a reference type, we converted it to a pointer above.
1731 // The status of rvalue references isn't entirely clear, but it looks like
1732 // conversion to them is simply invalid.
1733 // C++ 5.2.11p3: For two pointer types [...]
1734 if (!CStyle)
1735 msg = diag::err_bad_const_cast_dest;
1736 return TC_NotApplicable;
1737 }
1738 if (DestType->isFunctionPointerType() ||
1739 DestType->isMemberFunctionPointerType()) {
1740 // Cannot cast direct function pointers.
1741 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1742 // T is the ultimate pointee of source and target type.
1743 if (!CStyle)
1744 msg = diag::err_bad_const_cast_dest;
1745 return TC_NotApplicable;
1746 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001747
Richard Smitha3405ff2018-07-11 00:19:19 +00001748 // C++ [expr.const.cast]p3:
1749 // "For two similar types T1 and T2, [...]"
1750 //
1751 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1752 // type qualifiers. (Likewise, we ignore other changes when determining
1753 // whether a cast casts away constness.)
1754 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001755 return TC_NotApplicable;
1756
Richard Smith82c9b512013-06-14 22:27:52 +00001757 if (NeedToMaterializeTemporary)
1758 // This is a const_cast from a class prvalue to an rvalue reference type.
1759 // Materialize a temporary to store the result of the conversion.
Richard Smithb8c0f552016-12-09 18:49:13 +00001760 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1761 SrcExpr.get(),
Tim Shen4a05bb82016-06-21 20:29:17 +00001762 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001763
Sebastian Redl9f831db2009-07-25 15:41:38 +00001764 return TC_Success;
1765}
1766
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001767// Checks for undefined behavior in reinterpret_cast.
1768// The cases that is checked for is:
1769// *reinterpret_cast<T*>(&a)
1770// reinterpret_cast<T&>(a)
1771// where accessing 'a' as type 'T' will result in undefined behavior.
1772void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1773 bool IsDereference,
1774 SourceRange Range) {
1775 unsigned DiagID = IsDereference ?
1776 diag::warn_pointer_indirection_from_incompatible_type :
1777 diag::warn_undefined_reinterpret_cast;
1778
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001779 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001780 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001781
1782 QualType SrcTy, DestTy;
1783 if (IsDereference) {
1784 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1785 return;
1786 }
1787 SrcTy = SrcType->getPointeeType();
1788 DestTy = DestType->getPointeeType();
1789 } else {
1790 if (!DestType->getAs<ReferenceType>()) {
1791 return;
1792 }
1793 SrcTy = SrcType;
1794 DestTy = DestType->getPointeeType();
1795 }
1796
1797 // Cast is compatible if the types are the same.
1798 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1799 return;
1800 }
1801 // or one of the types is a char or void type
1802 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1803 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1804 return;
1805 }
1806 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001807 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001808 return;
1809 }
1810
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001811 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001812 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1813 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1814 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1815 return;
1816 }
1817 }
1818
1819 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1820}
Douglas Gregor1beec452011-03-12 01:48:56 +00001821
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001822static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1823 QualType DestType) {
1824 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001825 if (Self.Context.hasSameType(SrcType, DestType))
1826 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001827 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1828 if (SrcPtrTy->isObjCSelType()) {
1829 QualType DT = DestType;
1830 if (isa<PointerType>(DestType))
1831 DT = DestType->getPointeeType();
1832 if (!DT.getUnqualifiedType()->isVoidType())
1833 Self.Diag(SrcExpr.get()->getExprLoc(),
1834 diag::warn_cast_pointer_from_sel)
1835 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1836 }
1837}
1838
Reid Kleckner9f497332016-05-10 21:00:03 +00001839/// Diagnose casts that change the calling convention of a pointer to a function
1840/// defined in the current TU.
1841static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1842 QualType DstType, SourceRange OpRange) {
1843 // Check if this cast would change the calling convention of a function
1844 // pointer type.
1845 QualType SrcType = SrcExpr.get()->getType();
1846 if (Self.Context.hasSameType(SrcType, DstType) ||
1847 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1848 return;
1849 const auto *SrcFTy =
1850 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1851 const auto *DstFTy =
1852 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1853 CallingConv SrcCC = SrcFTy->getCallConv();
1854 CallingConv DstCC = DstFTy->getCallConv();
1855 if (SrcCC == DstCC)
1856 return;
1857
1858 // We have a calling convention cast. Check if the source is a pointer to a
1859 // known, specific function that has already been defined.
1860 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1861 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1862 if (UO->getOpcode() == UO_AddrOf)
1863 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1864 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1865 if (!DRE)
1866 return;
1867 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Reid Kleckner0b009e82017-01-31 19:37:45 +00001868 if (!FD)
Reid Kleckner9f497332016-05-10 21:00:03 +00001869 return;
1870
Reid Kleckner43be52a2016-05-11 17:43:13 +00001871 // Only warn if we are casting from the default convention to a non-default
1872 // convention. This can happen when the programmer forgot to apply the calling
Reid Kleckner0b009e82017-01-31 19:37:45 +00001873 // convention to the function declaration and then inserted this cast to
Reid Kleckner43be52a2016-05-11 17:43:13 +00001874 // satisfy the type system.
1875 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1876 FD->isVariadic(), FD->isCXXInstanceMember());
1877 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1878 return;
1879
Reid Kleckner9f497332016-05-10 21:00:03 +00001880 // Diagnose this cast, as it is probably bad.
1881 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1882 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1883 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1884 << SrcCCName << DstCCName << OpRange;
1885
1886 // The checks above are cheaper than checking if the diagnostic is enabled.
1887 // However, it's worth checking if the warning is enabled before we construct
1888 // a fixit.
1889 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1890 return;
1891
1892 // Try to suggest a fixit to change the calling convention of the function
1893 // whose address was taken. Try to use the latest macro for the convention.
1894 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1895 // to match the Windows header declarations.
Reid Kleckner0b009e82017-01-31 19:37:45 +00001896 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
Reid Kleckner9f497332016-05-10 21:00:03 +00001897 Preprocessor &PP = Self.getPreprocessor();
1898 SmallVector<TokenValue, 6> AttrTokens;
1899 SmallString<64> CCAttrText;
1900 llvm::raw_svector_ostream OS(CCAttrText);
1901 if (Self.getLangOpts().MicrosoftExt) {
1902 // __stdcall or __vectorcall
1903 OS << "__" << DstCCName;
1904 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1905 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1906 ? TokenValue(II->getTokenID())
1907 : TokenValue(II));
1908 } else {
1909 // __attribute__((stdcall)) or __attribute__((vectorcall))
1910 OS << "__attribute__((" << DstCCName << "))";
1911 AttrTokens.push_back(tok::kw___attribute);
1912 AttrTokens.push_back(tok::l_paren);
1913 AttrTokens.push_back(tok::l_paren);
1914 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1915 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1916 ? TokenValue(II->getTokenID())
1917 : TokenValue(II));
1918 AttrTokens.push_back(tok::r_paren);
1919 AttrTokens.push_back(tok::r_paren);
1920 }
1921 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1922 if (!AttrSpelling.empty())
1923 CCAttrText = AttrSpelling;
1924 OS << ' ';
1925 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1926 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1927}
1928
David Blaikie282ad872012-10-16 18:53:14 +00001929static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1930 const Expr *SrcExpr, QualType DestType,
1931 Sema &Self) {
1932 QualType SrcType = SrcExpr->getType();
1933
1934 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1935 // are not explicit design choices, but consistent with GCC's behavior.
1936 // Feel free to modify them if you've reason/evidence for an alternative.
1937 if (CStyle && SrcType->isIntegralType(Self.Context)
1938 && !SrcType->isBooleanType()
1939 && !SrcType->isEnumeralType()
1940 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001941 && Self.Context.getTypeSize(DestType) >
1942 Self.Context.getTypeSize(SrcType)) {
1943 // Separate between casts to void* and non-void* pointers.
1944 // Some APIs use (abuse) void* for something like a user context,
1945 // and often that value is an integer even if it isn't a pointer itself.
1946 // Having a separate warning flag allows users to control the warning
1947 // for their workflow.
1948 unsigned Diag = DestType->isVoidPointerType() ?
1949 diag::warn_int_to_void_pointer_cast
1950 : diag::warn_int_to_pointer_cast;
1951 Self.Diag(Loc, Diag) << SrcType << DestType;
1952 }
David Blaikie282ad872012-10-16 18:53:14 +00001953}
1954
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001955static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1956 ExprResult &Result) {
1957 // We can only fix an overloaded reinterpret_cast if
1958 // - it is a template with explicit arguments that resolves to an lvalue
1959 // unambiguously, or
1960 // - it is the only function in an overload set that may have its address
1961 // taken.
1962
1963 Expr *E = Result.get();
1964 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1965 // like it?
1966 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1967 Result,
1968 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1969 ) &&
1970 Result.isUsable())
1971 return true;
1972
George Burgess IVbeca4a32016-06-08 00:34:22 +00001973 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1974 // preserves Result.
1975 Result = E;
George Burgess IV1dbfa852017-05-09 04:06:24 +00001976 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1977 Result, /*DoFunctionPointerConversion=*/true))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001978 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00001979 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001980}
1981
John Wiegley01296292011-04-08 18:41:53 +00001982static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001983 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001984 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001985 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001986 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001987 bool IsLValueCast = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001988
Sebastian Redl9f831db2009-07-25 15:41:38 +00001989 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001990 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001991
1992 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001993 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001994 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001995 ExprResult FixedExpr = SrcExpr;
1996 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001997 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001998
1999 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2000 SrcExpr = FixedExpr;
2001 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00002002 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00002003
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002004 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00002005 if (!SrcExpr.get()->isGLValue()) {
2006 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2007 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00002008 msg = diag::err_bad_cxx_cast_rvalue;
2009 return TC_NotApplicable;
2010 }
2011
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00002012 if (!CStyle) {
2013 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2014 /*isDereference=*/false, OpRange);
2015 }
2016
Sebastian Redl9f831db2009-07-25 15:41:38 +00002017 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2018 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2019 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002020
Craig Topperc3ec1492014-05-26 06:22:03 +00002021 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002022 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00002023 case OK_Ordinary:
2024 break;
Richard Smithb8c0f552016-12-09 18:49:13 +00002025 case OK_BitField:
2026 msg = diag::err_bad_cxx_cast_bitfield;
2027 return TC_NotApplicable;
2028 // FIXME: Use a specific diagnostic for the rest of these cases.
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002029 case OK_VectorComponent: inappropriate = "vector element"; break;
2030 case OK_ObjCProperty: inappropriate = "property expression"; break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002031 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
Ted Kremeneke65b0862012-03-06 20:05:56 +00002032 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00002033 }
2034 if (inappropriate) {
2035 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2036 << inappropriate << DestType
2037 << OpRange << SrcExpr.get()->getSourceRange();
2038 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00002039 return TC_NotApplicable;
2040 }
2041
Sebastian Redl9f831db2009-07-25 15:41:38 +00002042 // This code does this transformation for the checked types.
2043 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2044 SrcType = Self.Context.getPointerType(SrcType);
Fangrui Song6907ce22018-07-30 19:24:48 +00002045
Douglas Gregor51954272010-07-13 23:17:26 +00002046 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002047 }
2048
2049 // Canonicalize source for comparison.
2050 SrcType = Self.Context.getCanonicalType(SrcType);
2051
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002052 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2053 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002054 if (DestMemPtr && SrcMemPtr) {
2055 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2056 // can be explicitly converted to an rvalue of type "pointer to member
2057 // of Y of type T2" if T1 and T2 are both function types or both object
2058 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00002059 if (DestMemPtr->isMemberFunctionPointer() !=
2060 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00002061 return TC_NotApplicable;
2062
David Majnemer1cdd96d2014-01-17 09:01:00 +00002063 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2064 // We need to determine the inheritance model that the class will use if
2065 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00002066 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2067 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00002068 }
2069
Charles Davisebab1ed2010-08-16 05:30:44 +00002070 // Don't allow casting between member pointers of different sizes.
2071 if (Self.Context.getTypeSize(DestMemPtr) !=
2072 Self.Context.getTypeSize(SrcMemPtr)) {
2073 msg = diag::err_bad_cxx_cast_member_pointer_size;
2074 return TC_Failed;
2075 }
2076
Richard Smithf276e2d2018-07-10 23:04:35 +00002077 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2078 // constness.
2079 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2080 // we accept it.
2081 if (auto CACK =
2082 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2083 /*CheckObjCLifetime=*/CStyle))
2084 return getCastAwayConstnessCastKind(CACK, msg);
2085
Sebastian Redl9f831db2009-07-25 15:41:38 +00002086 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00002087 assert(!IsLValueCast);
2088 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002089 return TC_Success;
2090 }
2091
2092 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00002093 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002094 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2095 // type large enough to hold it. A value of std::nullptr_t can be
2096 // converted to an integral type; the conversion has the same meaning
2097 // and validity as a conversion of (void*)0 to the integral type.
2098 if (Self.Context.getTypeSize(SrcType) >
2099 Self.Context.getTypeSize(DestType)) {
2100 msg = diag::err_bad_reinterpret_cast_small_int;
2101 return TC_Failed;
2102 }
John McCalle3027922010-08-25 11:45:40 +00002103 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002104 return TC_Success;
2105 }
2106
John McCall1c78f082015-07-23 23:54:07 +00002107 // Allow reinterpret_casts between vectors of the same size and
2108 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00002109 bool destIsVector = DestType->isVectorType();
2110 bool srcIsVector = SrcType->isVectorType();
2111 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00002112 // The non-vector type, if any, must have integral type. This is
2113 // the same rule that C vector casts use; note, however, that enum
2114 // types are not integral in C++.
2115 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2116 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002117 return TC_NotApplicable;
2118
John McCall1c78f082015-07-23 23:54:07 +00002119 // The size we want to consider is eltCount * eltSize.
2120 // That's exactly what the lax-conversion rules will check.
2121 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002122 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002123 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002124 }
John McCall1c78f082015-07-23 23:54:07 +00002125
2126 // Otherwise, pick a reasonable diagnostic.
2127 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002128 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002129 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002130 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2131 else
2132 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
Fangrui Song6907ce22018-07-30 19:24:48 +00002133
Anders Carlsson570af5d2009-09-16 19:19:43 +00002134 return TC_Failed;
2135 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002136
2137 if (SrcType == DestType) {
2138 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2139 // restrictions, a cast to the same type is allowed so long as it does not
Fangrui Song6907ce22018-07-30 19:24:48 +00002140 // cast away constness. In C++98, the intent was not entirely clear here,
Chad Rosier96c755d12012-02-03 02:54:37 +00002141 // since all other paragraphs explicitly forbid casts to the same type.
2142 // C++11 clarifies this case with p2.
2143 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002144 // The only allowed types are: integral, enumeration, pointer, or
Chad Rosier96c755d12012-02-03 02:54:37 +00002145 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2146 Kind = CK_NoOp;
2147 TryCastResult Result = TC_NotApplicable;
2148 if (SrcType->isIntegralOrEnumerationType() ||
2149 SrcType->isAnyPointerType() ||
2150 SrcType->isMemberPointerType() ||
2151 SrcType->isBlockPointerType()) {
2152 Result = TC_Success;
2153 }
2154 return Result;
2155 }
2156
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002157 bool destIsPtr = DestType->isAnyPointerType() ||
2158 DestType->isBlockPointerType();
2159 bool srcIsPtr = SrcType->isAnyPointerType() ||
2160 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002161 if (!destIsPtr && !srcIsPtr) {
2162 // Except for std::nullptr_t->integer and lvalue->reference, which are
2163 // handled above, at least one of the two arguments must be a pointer.
2164 return TC_NotApplicable;
2165 }
2166
Douglas Gregor6972a622010-06-16 00:35:25 +00002167 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002168 assert(srcIsPtr && "One type must be a pointer");
2169 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002170 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002171 // integral type size doesn't matter (except we don't allow bool).
2172 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2173 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002174 if ((Self.Context.getTypeSize(SrcType) >
2175 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002176 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002177 msg = diag::err_bad_reinterpret_cast_small_int;
2178 return TC_Failed;
2179 }
John McCalle3027922010-08-25 11:45:40 +00002180 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002181 return TC_Success;
2182 }
2183
Douglas Gregorb90df602010-06-16 00:17:44 +00002184 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002185 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002186 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2187 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002188 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2189 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002190 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2191 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002192 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002193 return TC_Success;
2194 }
2195
2196 if (!destIsPtr || !srcIsPtr) {
2197 // With the valid non-pointer conversions out of the way, we can be even
2198 // more stringent.
2199 return TC_NotApplicable;
2200 }
2201
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002202 // Cannot convert between block pointers and Objective-C object pointers.
2203 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2204 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2205 return TC_NotApplicable;
2206
Richard Smithf276e2d2018-07-10 23:04:35 +00002207 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2208 // The C-style cast operator can.
2209 TryCastResult SuccessResult = TC_Success;
2210 if (auto CACK =
2211 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2212 /*CheckObjCLifetime=*/CStyle))
2213 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2214
John McCall9320b872011-09-09 05:25:32 +00002215 if (IsLValueCast) {
2216 Kind = CK_LValueBitCast;
2217 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002218 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002219 } else if (DestType->isBlockPointerType()) {
2220 if (!SrcType->isBlockPointerType()) {
2221 Kind = CK_AnyPointerToBlockPointerCast;
2222 } else {
2223 Kind = CK_BitCast;
2224 }
Yaxun Liu99a9f752018-07-20 11:32:51 +00002225 } else if (IsAddressSpaceConversion(SrcType, DestType)) {
2226 Kind = CK_AddressSpaceConversion;
John McCall9320b872011-09-09 05:25:32 +00002227 } else {
2228 Kind = CK_BitCast;
2229 }
2230
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002231 // Any pointer can be cast to an Objective-C pointer type with a C-style
2232 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002233 if (CStyle && DestType->isObjCObjectPointerType()) {
Richard Smithf276e2d2018-07-10 23:04:35 +00002234 return SuccessResult;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002235 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002236 if (CStyle)
2237 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002238
2239 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2240
Sebastian Redl9f831db2009-07-25 15:41:38 +00002241 // Not casting away constness, so the only remaining check is for compatible
2242 // pointer categories.
2243
2244 if (SrcType->isFunctionPointerType()) {
2245 if (DestType->isFunctionPointerType()) {
2246 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2247 // a pointer to a function of a different type.
Richard Smithf276e2d2018-07-10 23:04:35 +00002248 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002249 }
2250
2251 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2252 // an object type or vice versa is conditionally-supported.
2253 // Compilers support it in C++03 too, though, because it's necessary for
2254 // casting the return value of dlsym() and GetProcAddress().
2255 // FIXME: Conditionally-supported behavior should be configurable in the
2256 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002257 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002258 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002259 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2260 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002261 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002262 }
2263
2264 if (DestType->isFunctionPointerType()) {
2265 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002266 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002267 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002268 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2269 << OpRange;
Richard Smithf276e2d2018-07-10 23:04:35 +00002270 return SuccessResult;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002271 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002272
Sebastian Redl9f831db2009-07-25 15:41:38 +00002273 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2274 // a pointer to an object of different type.
2275 // Void pointers are not specified, but supported by every compiler out there.
2276 // So we finish by allowing everything that remains - it's got to be two
2277 // object pointers.
Richard Smithf276e2d2018-07-10 23:04:35 +00002278 return SuccessResult;
2279}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002280
Anastasia Stulova5325f832018-10-10 16:05:22 +00002281void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2282 // In OpenCL only conversions between pointers to objects in overlapping
2283 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2284 // with any named one, except for constant.
2285 if (Self.getLangOpts().OpenCL) {
2286 auto SrcPtrType = SrcType->getAs<PointerType>();
2287 if (!SrcPtrType)
2288 return;
2289 auto DestPtrType = DestType->getAs<PointerType>();
2290 if (!DestPtrType)
2291 return;
2292 if (!DestPtrType->isAddressSpaceOverlapping(*SrcPtrType)) {
2293 Self.Diag(OpRange.getBegin(),
2294 diag::err_typecheck_incompatible_address_space)
2295 << SrcType << DestType << Sema::AA_Casting
2296 << SrcExpr.get()->getSourceRange();
2297 SrcExpr = ExprError();
2298 }
2299 }
2300}
2301
Sebastian Redld74dd492012-02-12 18:41:05 +00002302void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2303 bool ListInitialization) {
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002304 assert(Self.getLangOpts().CPlusPlus);
2305
John McCall9776e432011-10-06 23:25:11 +00002306 // Handle placeholders.
2307 if (isPlaceholder()) {
2308 // C-style casts can resolve __unknown_any types.
2309 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2310 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2311 SrcExpr.get(), Kind,
2312 ValueKind, BasePath);
2313 return;
2314 }
John McCallb50451a2011-10-05 07:41:44 +00002315
John McCall9776e432011-10-06 23:25:11 +00002316 checkNonOverloadPlaceholders();
2317 if (SrcExpr.isInvalid())
2318 return;
John McCalla072f5d2011-10-17 17:42:19 +00002319 }
John McCall9776e432011-10-06 23:25:11 +00002320
2321 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002322 // This test is outside everything else because it's the only case where
2323 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002324 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002325 Kind = CK_ToVoid;
2326
John McCall9776e432011-10-06 23:25:11 +00002327 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002328 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
Fangrui Song6907ce22018-07-30 19:24:48 +00002329 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002330 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002331 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002332 if (SrcExpr.isInvalid())
2333 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002334 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002335
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002336 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002337 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002338 }
2339
Sebastian Redl9f831db2009-07-25 15:41:38 +00002340 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002341 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2342 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002343 assert(Kind == CK_Dependent);
2344 return;
John McCall8cb679e2010-11-15 09:13:47 +00002345 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002346
John McCall50a2c2c2011-10-11 23:14:30 +00002347 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2348 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002349 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002350 if (SrcExpr.isInvalid())
2351 return;
John Wiegley01296292011-04-08 18:41:53 +00002352 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002353
John McCall3aef3d82011-04-10 19:13:55 +00002354 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002355 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002356 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002357 && (SrcExpr.get()->getType()->isIntegerType()
2358 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002359 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002360 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002361 return;
John McCall3aef3d82011-04-10 19:13:55 +00002362 }
2363
Sebastian Redl9f831db2009-07-25 15:41:38 +00002364 // C++ [expr.cast]p5: The conversions performed by
2365 // - a const_cast,
2366 // - a static_cast,
2367 // - a static_cast followed by a const_cast,
2368 // - a reinterpret_cast, or
2369 // - a reinterpret_cast followed by a const_cast,
2370 // can be performed using the cast notation of explicit type conversion.
2371 // [...] If a conversion can be interpreted in more than one of the ways
2372 // listed above, the interpretation that appears first in the list is used,
2373 // even if a cast resulting from that interpretation is ill-formed.
2374 // In plain language, this means trying a const_cast ...
2375 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002376 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002377 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002378 if (SrcExpr.isInvalid())
2379 return;
Richard Smithf276e2d2018-07-10 23:04:35 +00002380 if (isValidCast(tcr))
John McCalle3027922010-08-25 11:45:40 +00002381 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002382
John McCall31168b02011-06-15 23:02:42 +00002383 Sema::CheckedConversionKind CCK
2384 = FunctionalStyle? Sema::CCK_FunctionalCast
2385 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002386 if (tcr == TC_NotApplicable) {
2387 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002388 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002389 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002390 if (SrcExpr.isInvalid())
2391 return;
2392
Sebastian Redl9f831db2009-07-25 15:41:38 +00002393 if (tcr == TC_NotApplicable) {
2394 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002395 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2396 OpRange, msg, Kind);
2397 if (SrcExpr.isInvalid())
2398 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002399 }
2400 }
2401
Brian Kelley11352a82017-03-29 18:09:02 +00002402 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
Richard Smithf276e2d2018-07-10 23:04:35 +00002403 isValidCast(tcr))
Brian Kelley11352a82017-03-29 18:09:02 +00002404 checkObjCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002405
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002406 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002407 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002408 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002409 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2410 DestType,
2411 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002412 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002413 if (Fn) {
2414 // If DestType is a function type (not to be confused with the function
2415 // pointer type), it will be possible to resolve the function address,
2416 // but the type cast should be considered as failure.
2417 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2418 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2419 << OE->getName() << DestType << OpRange
2420 << OE->getQualifierLoc().getSourceRange();
2421 Self.NoteAllOverloadCandidates(SrcExpr.get());
2422 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002423 } else {
John McCallb50451a2011-10-05 07:41:44 +00002424 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002425 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002426 }
2427 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002428
Anastasia Stulova5325f832018-10-10 16:05:22 +00002429 checkAddressSpaceCast(SrcExpr.get()->getType(), DestType);
2430
Richard Smithf276e2d2018-07-10 23:04:35 +00002431 if (isValidCast(tcr)) {
2432 if (Kind == CK_BitCast)
2433 checkCastAlign();
2434 } else {
John McCallb50451a2011-10-05 07:41:44 +00002435 SrcExpr = ExprError();
Richard Smithf276e2d2018-07-10 23:04:35 +00002436 }
John McCallb50451a2011-10-05 07:41:44 +00002437}
2438
Fangrui Song6907ce22018-07-30 19:24:48 +00002439/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002440/// non-matching type. Such as enum function call to int, int call to
2441/// pointer; etc. Cast to 'void' is an exception.
2442static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2443 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002444 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2445 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002446 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002447
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002448 if (!isa<CallExpr>(SrcExpr.get()))
2449 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002450
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002451 QualType SrcType = SrcExpr.get()->getType();
2452 if (DestType.getUnqualifiedType()->isVoidType())
2453 return;
2454 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2455 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2456 return;
2457 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2458 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2459 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2460 return;
2461 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2462 return;
2463 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2464 return;
2465 if (SrcType->isComplexType() && DestType->isComplexType())
2466 return;
2467 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2468 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002469
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002470 Self.Diag(SrcExpr.get()->getExprLoc(),
2471 diag::warn_bad_function_cast)
2472 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2473}
2474
John McCall9776e432011-10-06 23:25:11 +00002475/// Check the semantics of a C-style cast operation, in C.
2476void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002477 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002478
John McCall4124c492011-10-17 18:40:02 +00002479 // C-style casts can resolve __unknown_any types.
2480 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2481 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2482 SrcExpr.get(), Kind,
2483 ValueKind, BasePath);
2484 return;
2485 }
John McCall9776e432011-10-06 23:25:11 +00002486
2487 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2488 // type needs to be scalar.
2489 if (DestType->isVoidType()) {
2490 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002491 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002492 if (SrcExpr.isInvalid())
2493 return;
2494
2495 // Cast to void allows any expr type.
2496 Kind = CK_ToVoid;
2497 return;
2498 }
2499
George Burgess IV5f21c712015-10-12 19:57:04 +00002500 // Overloads are allowed with C extensions, so we need to support them.
2501 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2502 DeclAccessPair DAP;
2503 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2504 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2505 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2506 else
2507 return;
2508 assert(SrcExpr.isUsable());
2509 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002510 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002511 if (SrcExpr.isInvalid())
2512 return;
2513 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002514
John McCall4124c492011-10-17 18:40:02 +00002515 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002516
Anastasia Stulova5325f832018-10-10 16:05:22 +00002517 checkAddressSpaceCast(SrcType, DestType);
2518 if (SrcExpr.isInvalid())
2519 return;
Joey Gouly8fc32f02014-01-14 12:47:29 +00002520
John McCall9776e432011-10-06 23:25:11 +00002521 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2522 diag::err_typecheck_cast_to_incomplete)) {
2523 SrcExpr = ExprError();
2524 return;
2525 }
2526
2527 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2528 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2529
2530 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2531 // GCC struct/union extension: allow cast to self.
2532 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2533 << DestType << SrcExpr.get()->getSourceRange();
2534 Kind = CK_NoOp;
2535 return;
2536 }
2537
2538 // GCC's cast to union extension.
2539 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2540 RecordDecl *RD = DestRecordTy->getDecl();
John McCallf1ef7962017-08-15 21:42:47 +00002541 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2542 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2543 << SrcExpr.get()->getSourceRange();
2544 Kind = CK_ToUnion;
2545 return;
2546 } else {
John McCall9776e432011-10-06 23:25:11 +00002547 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2548 << SrcType << SrcExpr.get()->getSourceRange();
2549 SrcExpr = ExprError();
2550 return;
2551 }
John McCall9776e432011-10-06 23:25:11 +00002552 }
2553
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002554 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2555 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002556 Expr::EvalResult Result;
2557 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2558 llvm::APSInt CastInt = Result.Val.getInt();
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002559 if (0 == CastInt) {
Andrew Savonichevb555b762018-10-23 15:19:20 +00002560 Kind = CK_ZeroToOCLOpaqueType;
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002561 return;
2562 }
2563 Self.Diag(OpRange.getBegin(),
Richard Smithf8812672016-12-02 22:38:31 +00002564 diag::err_opencl_cast_non_zero_to_event_t)
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002565 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2566 SrcExpr = ExprError();
2567 return;
2568 }
2569 }
2570
John McCall9776e432011-10-06 23:25:11 +00002571 // Reject any other conversions to non-scalar types.
2572 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2573 << DestType << SrcExpr.get()->getSourceRange();
2574 SrcExpr = ExprError();
2575 return;
2576 }
2577
2578 // The type we're casting to is known to be a scalar or vector.
2579
2580 // Require the operand to be a scalar or vector.
2581 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2582 Self.Diag(SrcExpr.get()->getExprLoc(),
2583 diag::err_typecheck_expect_scalar_operand)
2584 << SrcType << SrcExpr.get()->getSourceRange();
2585 SrcExpr = ExprError();
2586 return;
2587 }
2588
2589 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002590 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002591 return;
2592 }
2593
2594 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2595 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2596 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2597 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002598 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002599 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2600 SrcExpr = ExprError();
2601 }
2602 return;
2603 }
2604
2605 if (SrcType->isVectorType()) {
2606 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2607 SrcExpr = ExprError();
2608 return;
2609 }
2610
2611 // The source and target types are both scalars, i.e.
2612 // - arithmetic types (fundamental, enum, and complex)
2613 // - all kinds of pointers
2614 // Note that member pointers were filtered out with C++, above.
2615
2616 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2617 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2618 SrcExpr = ExprError();
2619 return;
2620 }
2621
2622 // If either type is a pointer, the other type has to be either an
2623 // integer or a pointer.
2624 if (!DestType->isArithmeticType()) {
2625 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2626 Self.Diag(SrcExpr.get()->getExprLoc(),
2627 diag::err_cast_pointer_from_non_pointer_int)
2628 << SrcType << SrcExpr.get()->getSourceRange();
2629 SrcExpr = ExprError();
2630 return;
2631 }
David Blaikie282ad872012-10-16 18:53:14 +00002632 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2633 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002634 } else if (!SrcType->isArithmeticType()) {
2635 if (!DestType->isIntegralType(Self.Context) &&
2636 DestType->isArithmeticType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002637 Self.Diag(SrcExpr.get()->getBeginLoc(),
2638 diag::err_cast_pointer_to_non_pointer_int)
2639 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002640 SrcExpr = ExprError();
2641 return;
2642 }
2643 }
2644
Yaxun Liu5b746652016-12-18 05:18:55 +00002645 if (Self.getLangOpts().OpenCL &&
2646 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
Joey Goulydd7f4562013-01-23 11:56:20 +00002647 if (DestType->isHalfType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002648 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
2649 << DestType << SrcExpr.get()->getSourceRange();
Joey Goulydd7f4562013-01-23 11:56:20 +00002650 SrcExpr = ExprError();
2651 return;
2652 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002653 }
2654
John McCall9776e432011-10-06 23:25:11 +00002655 // ARC imposes extra restrictions on casts.
Brian Kelley11352a82017-03-29 18:09:02 +00002656 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2657 checkObjCConversion(Sema::CCK_CStyleCast);
John McCall9776e432011-10-06 23:25:11 +00002658 if (SrcExpr.isInvalid())
2659 return;
Brian Kelley11352a82017-03-29 18:09:02 +00002660
2661 const PointerType *CastPtr = DestType->getAs<PointerType>();
2662 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
John McCall9776e432011-10-06 23:25:11 +00002663 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2664 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2665 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00002666 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
John McCall9776e432011-10-06 23:25:11 +00002667 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2668 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002669 Self.Diag(SrcExpr.get()->getBeginLoc(),
John McCall9776e432011-10-06 23:25:11 +00002670 diag::err_typecheck_incompatible_ownership)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002671 << SrcType << DestType << Sema::AA_Casting
2672 << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002673 return;
2674 }
2675 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002676 }
John McCall9776e432011-10-06 23:25:11 +00002677 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002678 Self.Diag(SrcExpr.get()->getBeginLoc(),
John McCall9776e432011-10-06 23:25:11 +00002679 diag::err_arc_convesion_of_weak_unavailable)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002680 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002681 SrcExpr = ExprError();
2682 return;
2683 }
2684 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002685
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002686 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002687 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002688 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002689 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2690 if (SrcExpr.isInvalid())
2691 return;
2692
2693 if (Kind == CK_BitCast)
2694 checkCastAlign();
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002695}
Roman Divackyd5178012014-11-21 21:03:10 +00002696
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002697/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2698/// const, volatile or both.
2699static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2700 QualType DestType) {
2701 if (SrcExpr.isInvalid())
2702 return;
2703
2704 QualType SrcType = SrcExpr.get()->getType();
2705 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2706 DestType->isLValueReferenceType()))
2707 return;
2708
Roman Divackyd5178012014-11-21 21:03:10 +00002709 QualType TheOffendingSrcType, TheOffendingDestType;
2710 Qualifiers CastAwayQualifiers;
Richard Smithf276e2d2018-07-10 23:04:35 +00002711 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
2712 &TheOffendingSrcType, &TheOffendingDestType,
2713 &CastAwayQualifiers) !=
2714 CastAwayConstnessKind::CACK_Similar)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002715 return;
2716
Richard Smithf276e2d2018-07-10 23:04:35 +00002717 // FIXME: 'restrict' is not properly handled here.
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002718 int qualifiers = -1;
2719 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2720 qualifiers = 0;
2721 } else if (CastAwayQualifiers.hasConst()) {
2722 qualifiers = 1;
2723 } else if (CastAwayQualifiers.hasVolatile()) {
2724 qualifiers = 2;
Roman Divackyd5178012014-11-21 21:03:10 +00002725 }
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002726 // This is a variant of int **x; const int **y = (const int **)x;
2727 if (qualifiers == -1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002728 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002729 << SrcType << DestType;
2730 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002731 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002732 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
John McCall9776e432011-10-06 23:25:11 +00002733}
2734
2735ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2736 TypeSourceInfo *CastTypeInfo,
2737 SourceLocation RPLoc,
2738 Expr *CastExpr) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002739 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002740 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002741 Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
John McCallb50451a2011-10-05 07:41:44 +00002742
David Blaikiebbafb8a2012-03-11 07:00:24 +00002743 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002744 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2745 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002746 } else {
2747 Op.CheckCStyleCast();
2748 }
2749
John McCallb50451a2011-10-05 07:41:44 +00002750 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002751 return ExprError();
2752
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002753 // -Wcast-qual
2754 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2755
John McCall4124c492011-10-17 18:40:02 +00002756 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002757 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002758 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002759}
2760
2761ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
Richard Smith60437622017-02-09 19:17:44 +00002762 QualType Type,
John McCallb50451a2011-10-05 07:41:44 +00002763 SourceLocation LPLoc,
2764 Expr *CastExpr,
2765 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002766 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
Richard Smith60437622017-02-09 19:17:44 +00002767 CastOperation Op(*this, Type, CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002768 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002769 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
John McCallb50451a2011-10-05 07:41:44 +00002770
Sebastian Redl2b80af42012-02-13 19:55:43 +00002771 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002772 if (Op.SrcExpr.isInvalid())
2773 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002774
2775 auto *SubExpr = Op.SrcExpr.get();
2776 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2777 SubExpr = BindExpr->getSubExpr();
2778 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002779 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002780
John McCall4124c492011-10-17 18:40:02 +00002781 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002782 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002783 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002784}