blob: e83dd0716780fd7fe8b9e6ffb81b0bd3dcc54488 [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCall3cec19f2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCallcda80832013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer1cdd96d2014-01-17 09:01:00 +000024#include "clang/Basic/TargetInfo.h"
Reid Kleckner9f497332016-05-10 21:00:03 +000025#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000027#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000028#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000029using namespace clang;
30
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Douglas Gregore81f58e2010-11-08 03:40:48 +000032
Sebastian Redl9f831db2009-07-25 15:41:38 +000033enum TryCastResult {
34 TC_NotApplicable, ///< The cast method is not applicable.
35 TC_Success, ///< The cast method is appropriate and successful.
36 TC_Failed ///< The cast method is appropriate, but failed. A
37 ///< diagnostic has been emitted.
38};
39
40enum CastType {
41 CT_Const, ///< const_cast
42 CT_Static, ///< static_cast
43 CT_Reinterpret, ///< reinterpret_cast
44 CT_Dynamic, ///< dynamic_cast
45 CT_CStyle, ///< (Type)expr
46 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000047};
48
John McCallb50451a2011-10-05 07:41:44 +000049namespace {
50 struct CastOperation {
51 CastOperation(Sema &S, QualType destType, ExprResult src)
52 : Self(S), SrcExpr(src), DestType(destType),
53 ResultType(destType.getNonLValueExprType(S.Context)),
54 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000055 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000056
57 if (const BuiltinType *placeholder =
58 src.get()->getType()->getAsPlaceholderType()) {
59 PlaceholderKind = placeholder->getKind();
60 } else {
61 PlaceholderKind = (BuiltinType::Kind) 0;
62 }
63 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000064
John McCallb50451a2011-10-05 07:41:44 +000065 Sema &Self;
66 ExprResult SrcExpr;
67 QualType DestType;
68 QualType ResultType;
69 ExprValueKind ValueKind;
70 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000071 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000072 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000073 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000074
John McCallb50451a2011-10-05 07:41:44 +000075 SourceRange OpRange;
76 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000077
John McCall9776e432011-10-06 23:25:11 +000078 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000079 void CheckConstCast();
80 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000081 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000082 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000083 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000084 void CheckCStyleCast();
85
John McCall4124c492011-10-17 18:40:02 +000086 /// Complete an apparently-successful cast operation that yields
87 /// the given expression.
88 ExprResult complete(CastExpr *castExpr) {
89 // If this is an unbridged cast, wrap the result in an implicit
90 // cast that yields the unbridged-cast placeholder type.
91 if (IsARCUnbridgedCast) {
92 castExpr = ImplicitCastExpr::Create(Self.Context,
93 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000094 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +000095 castExpr->getValueKind());
96 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000097 return castExpr;
John McCall4124c492011-10-17 18:40:02 +000098 }
99
John McCall9776e432011-10-06 23:25:11 +0000100 // Internal convenience methods.
101
102 /// Try to handle the given placeholder expression kind. Return
103 /// true if the source expression has the appropriate placeholder
104 /// kind. A placeholder can only be claimed once.
105 bool claimPlaceholder(BuiltinType::Kind K) {
106 if (PlaceholderKind != K) return false;
107
108 PlaceholderKind = (BuiltinType::Kind) 0;
109 return true;
110 }
111
112 bool isPlaceholder() const {
113 return PlaceholderKind != 0;
114 }
115 bool isPlaceholder(BuiltinType::Kind K) const {
116 return PlaceholderKind == K;
117 }
John McCallb50451a2011-10-05 07:41:44 +0000118
119 void checkCastAlign() {
120 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
121 }
122
123 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000124 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall4124c492011-10-17 18:40:02 +0000125
John McCallb50451a2011-10-05 07:41:44 +0000126 Expr *src = SrcExpr.get();
John McCall4124c492011-10-17 18:40:02 +0000127 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
128 Sema::ACR_unbridged)
129 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000130 SrcExpr = src;
131 }
John McCall9776e432011-10-06 23:25:11 +0000132
133 /// Check for and handle non-overload placeholder expressions.
134 void checkNonOverloadPlaceholders() {
135 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
136 return;
137
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000138 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000139 if (SrcExpr.isInvalid())
140 return;
141 PlaceholderKind = (BuiltinType::Kind) 0;
142 }
John McCallb50451a2011-10-05 07:41:44 +0000143 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000144}
Sebastian Redl842ef522008-11-08 13:00:26 +0000145
Sebastian Redl9f831db2009-07-25 15:41:38 +0000146// The Try functions attempt a specific way of casting. If they succeed, they
147// return TC_Success. If their way of casting is not appropriate for the given
148// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
149// to emit if no other way succeeds. If their way of casting is appropriate but
150// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
151// they emit a specialized diagnostic.
152// All diagnostics returned by these functions must expect the same three
153// arguments:
154// %0: Cast Type (a value from the CastType enumeration)
155// %1: Source Type
156// %2: Destination Type
157static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000158 QualType DestType, bool CStyle,
159 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000160 CXXCastPath &BasePath,
161 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000162static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000163 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000164 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000165 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000166 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000167 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000168static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
169 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000170 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000171 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000172 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000173 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000174static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
175 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000176 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000177 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000178 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000179 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000180 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000181static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000182 QualType SrcType,
183 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000184 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000185 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000186 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000187 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000188
John Wiegley01296292011-04-08 18:41:53 +0000189static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000190 QualType DestType,
191 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000192 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000193 unsigned &msg, CastKind &Kind,
194 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000195static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000196 QualType DestType,
197 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000198 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000199 unsigned &msg, CastKind &Kind,
200 CXXCastPath &BasePath,
201 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000202static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
203 QualType DestType, bool CStyle,
204 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000205static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000206 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000207 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000208 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000209 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000210
Douglas Gregorb491ed32011-02-19 21:32:49 +0000211
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000212/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000213ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000214Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000215 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000216 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000217 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000218 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000219
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000220 assert(!D.isInvalidType());
221
222 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
223 if (D.isInvalidType())
224 return ExprError();
225
David Blaikiebbafb8a2012-03-11 07:00:24 +0000226 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000227 // Check that there are no default arguments (C++ only).
228 CheckExtraCXXDefaultArguments(D);
229 }
230
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000231 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000232 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
233 SourceRange(LParenLoc, RParenLoc));
234}
235
John McCalldadc5752010-08-24 06:29:42 +0000236ExprResult
John McCalld377e042010-01-15 19:13:16 +0000237Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000238 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000239 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000240 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000241 QualType DestType = DestTInfo->getType();
242
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000243 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000244 bool TypeDependent =
245 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000246
John McCallb50451a2011-10-05 07:41:44 +0000247 CastOperation Op(*this, DestType, E);
248 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
249 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000250
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000251 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000252 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000253
254 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000255 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000256 Op.CheckConstCast();
257 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000258 return ExprError();
259 }
John McCall4124c492011-10-17 18:40:02 +0000260 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000261 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000262 OpLoc, Parens.getEnd(),
263 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000264
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000265 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000266 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000267 Op.CheckDynamicCast();
268 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000269 return ExprError();
270 }
John McCall4124c492011-10-17 18:40:02 +0000271 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000272 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000273 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000274 OpLoc, Parens.getEnd(),
275 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000276 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000277 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000278 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000279 Op.CheckReinterpretCast();
280 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000281 return ExprError();
282 }
John McCall4124c492011-10-17 18:40:02 +0000283 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000284 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000285 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000286 Parens.getEnd(),
287 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000288 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000289 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000290 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000291 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000292 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000293 return ExprError();
294 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000295
John McCall4124c492011-10-17 18:40:02 +0000296 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000297 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000298 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000299 OpLoc, Parens.getEnd(),
300 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000301 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000302 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000303}
304
John McCall909acf82011-02-14 18:34:10 +0000305/// Try to diagnose a failed overloaded cast. Returns true if
306/// diagnostics were emitted.
307static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
308 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000309 QualType destType,
310 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000311 switch (CT) {
312 // These cast kinds don't consider user-defined conversions.
313 case CT_Const:
314 case CT_Reinterpret:
315 case CT_Dynamic:
316 return false;
317
318 // These do.
319 case CT_Static:
320 case CT_CStyle:
321 case CT_Functional:
322 break;
323 }
324
325 QualType srcType = src->getType();
326 if (!destType->isRecordType() && !srcType->isRecordType())
327 return false;
328
329 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
330 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000331 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000332 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000333 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000334 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000335 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000336 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000337
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000338 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000339 switch (sequence.getFailureKind()) {
340 default: return false;
341
342 case InitializationSequence::FK_ConstructorOverloadFailed:
343 case InitializationSequence::FK_UserConversionOverloadFailed:
344 break;
345 }
346
347 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
348
349 unsigned msg = 0;
350 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
351
352 switch (sequence.getFailedOverloadResult()) {
353 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000354 case OR_No_Viable_Function:
355 if (candidates.empty())
356 msg = diag::err_ovl_no_conversion_in_cast;
357 else
358 msg = diag::err_ovl_no_viable_conversion_in_cast;
359 howManyCandidates = OCD_AllCandidates;
360 break;
361
362 case OR_Ambiguous:
363 msg = diag::err_ovl_ambiguous_conversion_in_cast;
364 howManyCandidates = OCD_ViableCandidates;
365 break;
366
367 case OR_Deleted:
368 msg = diag::err_ovl_deleted_conversion_in_cast;
369 howManyCandidates = OCD_ViableCandidates;
370 break;
371 }
372
373 S.Diag(range.getBegin(), msg)
374 << CT << srcType << destType
375 << range << src->getSourceRange();
376
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000377 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000378
379 return true;
380}
381
382/// Diagnose a failed cast.
383static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000384 SourceRange opRange, Expr *src, QualType destType,
385 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000386 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000387 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
388 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000389 return;
390
391 S.Diag(opRange.getBegin(), msg) << castType
392 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000393
394 // Detect if both types are (ptr to) class, and note any incompleteness.
395 int DifferentPtrness = 0;
396 QualType From = destType;
397 if (auto Ptr = From->getAs<PointerType>()) {
398 From = Ptr->getPointeeType();
399 DifferentPtrness++;
400 }
401 QualType To = src->getType();
402 if (auto Ptr = To->getAs<PointerType>()) {
403 To = Ptr->getPointeeType();
404 DifferentPtrness--;
405 }
406 if (!DifferentPtrness) {
407 auto RecFrom = From->getAs<RecordType>();
408 auto RecTo = To->getAs<RecordType>();
409 if (RecFrom && RecTo) {
410 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
411 if (!DeclFrom->isCompleteDefinition())
412 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
413 << DeclFrom->getDeclName();
414 auto DeclTo = RecTo->getAsCXXRecordDecl();
415 if (!DeclTo->isCompleteDefinition())
416 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
417 << DeclTo->getDeclName();
418 }
419 }
John McCall909acf82011-02-14 18:34:10 +0000420}
421
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000422/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
423/// this removes one level of indirection from both types, provided that they're
424/// the same kind of pointer (plain or to-member). Unlike the Sema function,
425/// this one doesn't care if the two pointers-to-member don't point into the
426/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000427static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000428 const PointerType *T1PtrType = T1->getAs<PointerType>(),
429 *T2PtrType = T2->getAs<PointerType>();
430 if (T1PtrType && T2PtrType) {
431 T1 = T1PtrType->getPointeeType();
432 T2 = T2PtrType->getPointeeType();
433 return true;
434 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000435 const ObjCObjectPointerType *T1ObjCPtrType =
436 T1->getAs<ObjCObjectPointerType>(),
437 *T2ObjCPtrType =
438 T2->getAs<ObjCObjectPointerType>();
439 if (T1ObjCPtrType) {
440 if (T2ObjCPtrType) {
441 T1 = T1ObjCPtrType->getPointeeType();
442 T2 = T2ObjCPtrType->getPointeeType();
443 return true;
444 }
445 else if (T2PtrType) {
446 T1 = T1ObjCPtrType->getPointeeType();
447 T2 = T2PtrType->getPointeeType();
448 return true;
449 }
450 }
451 else if (T2ObjCPtrType) {
452 if (T1PtrType) {
453 T2 = T2ObjCPtrType->getPointeeType();
454 T1 = T1PtrType->getPointeeType();
455 return true;
456 }
457 }
458
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000459 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
460 *T2MPType = T2->getAs<MemberPointerType>();
461 if (T1MPType && T2MPType) {
462 T1 = T1MPType->getPointeeType();
463 T2 = T2MPType->getPointeeType();
464 return true;
465 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000466
467 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
468 *T2BPType = T2->getAs<BlockPointerType>();
469 if (T1BPType && T2BPType) {
470 T1 = T1BPType->getPointeeType();
471 T2 = T2BPType->getPointeeType();
472 return true;
473 }
474
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000475 return false;
476}
477
Sebastian Redla5a77a62009-01-27 23:18:31 +0000478/// CastsAwayConstness - Check if the pointer conversion from SrcType to
479/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
480/// the cast checkers. Both arguments must denote pointer (possibly to member)
481/// types.
John McCall31168b02011-06-15 23:02:42 +0000482///
483/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
484///
485/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000486static bool
John McCall31168b02011-06-15 23:02:42 +0000487CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000488 bool CheckCVR, bool CheckObjCLifetime,
489 QualType *TheOffendingSrcType = nullptr,
490 QualType *TheOffendingDestType = nullptr,
491 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000492 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000493 // and we're not in ObjC mode, there's nothing to check.
John McCall31168b02011-06-15 23:02:42 +0000494 if (!CheckCVR && CheckObjCLifetime &&
John McCall460ce582015-10-22 18:38:17 +0000495 !Self.Context.getLangOpts().ObjC1)
John McCall31168b02011-06-15 23:02:42 +0000496 return false;
497
Sebastian Redla5a77a62009-01-27 23:18:31 +0000498 // Casting away constness is defined in C++ 5.2.11p8 with reference to
499 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
500 // the rules are non-trivial. So first we construct Tcv *...cv* as described
501 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000502 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
503 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000504 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000505 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
506 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000507 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000508
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000509 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
510 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000511 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000512
Douglas Gregorb472e932011-04-15 17:59:54 +0000513 // Find the qualifiers. We only care about cvr-qualifiers for the
514 // purpose of this check, because other qualifiers (address spaces,
515 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000516 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
517 QualType PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000518 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000519 // Determine the relevant qualifiers at this level.
520 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000521 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000522 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000523
524 Qualifiers RetainedSrcQuals, RetainedDestQuals;
525 if (CheckCVR) {
526 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
527 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000528
529 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
530 TheOffendingDestType && CastAwayQualifiers) {
531 *TheOffendingSrcType = PrevUnwrappedSrcType;
532 *TheOffendingDestType = PrevUnwrappedDestType;
533 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
534 }
John McCall31168b02011-06-15 23:02:42 +0000535 }
536
537 if (CheckObjCLifetime &&
538 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
539 return true;
540
541 cv1.push_back(RetainedSrcQuals);
542 cv2.push_back(RetainedDestQuals);
Roman Divackyd5178012014-11-21 21:03:10 +0000543
544 PrevUnwrappedSrcType = UnwrappedSrcType;
545 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000546 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000547 if (cv1.empty())
548 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000549
550 // Construct void pointers with those qualifiers (in reverse order of
551 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000552 QualType SrcConstruct = Self.Context.VoidTy;
553 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000554 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000555 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
556 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000557 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000558 SrcConstruct
559 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
560 DestConstruct
561 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000562 }
563
564 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000565 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000566 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000567 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
568 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000569}
570
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000571/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
572/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
573/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000574void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000575 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000576 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000577 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000578 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000579 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
580 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000581
John McCallb50451a2011-10-05 07:41:44 +0000582 QualType OrigSrcType = SrcExpr.get()->getType();
583 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000584
585 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
586 // or "pointer to cv void".
587
588 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000589 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000590 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000591 if (DestPointer) {
592 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000593 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000594 DestPointee = DestReference->getPointeeType();
595 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000596 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000597 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000598 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000599 return;
600 }
601
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000602 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000603 if (DestPointee->isVoidType()) {
604 assert(DestPointer && "Reference to void is not possible");
605 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000606 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000607 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000608 DestRange)) {
609 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000610 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000611 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000612 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000613 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000614 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000615 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000616 return;
617 }
618
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000619 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
620 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000621 // an lvalue of a complete class type, [...]. If T is an rvalue reference
622 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000623 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000624 QualType SrcPointee;
625 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000626 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000627 SrcPointee = SrcPointer->getPointeeType();
628 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000629 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000630 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000631 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000632 return;
633 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000634 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000635 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000636 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000637 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000638 }
639 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000640 } else {
Richard Smith11330852014-07-08 17:25:14 +0000641 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
642 // to materialize the prvalue before we bind the reference to it.
643 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000644 SrcExpr = Self.CreateMaterializeTemporaryExpr(
645 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000646 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000647 }
648
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000649 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000650 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000651 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000652 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000653 SrcExpr.get())) {
654 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000655 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000656 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000657 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000658 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000659 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000660 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000661 return;
662 }
663
664 assert((DestPointer || DestReference) &&
665 "Bad destination non-ptr/ref slipped through.");
666 assert((DestRecord || DestPointee->isVoidType()) &&
667 "Bad destination pointee slipped through.");
668 assert(SrcRecord && "Bad source pointee slipped through.");
669
670 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
671 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000672 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000673 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000674 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000675 return;
676 }
677
678 // C++ 5.2.7p3: If the type of v is the same as the required result type,
679 // [except for cv].
680 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000681 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000682 return;
683 }
684
685 // C++ 5.2.7p5
686 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000687 if (DestRecord &&
688 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000689 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
690 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000691 &BasePath)) {
692 SrcExpr = ExprError();
693 return;
694 }
Richard Smith11330852014-07-08 17:25:14 +0000695
John McCalle3027922010-08-25 11:45:40 +0000696 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000697 return;
698 }
699
700 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000701 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000702 assert(SrcDecl && "Definition missing");
703 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000704 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000705 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000706 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000707 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000708
Eli Friedman3ce27102013-09-24 23:21:41 +0000709 // dynamic_cast is not available with -fno-rtti.
710 // As an exception, dynamic_cast to void* is available because it doesn't
711 // use RTTI.
712 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000713 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
714 SrcExpr = ExprError();
715 return;
716 }
717
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000718 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000719 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000720}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000721
722/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
723/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
724/// like this:
725/// const char *str = "literal";
726/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000727void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000728 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000729 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000730 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000731 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000732 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
733 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000734
735 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000736 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000737 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000738 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000739 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000740 SrcExpr = ExprError();
741 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000742}
743
John McCallcda80832013-03-22 02:58:14 +0000744/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
745/// or downcast between respective pointers or references.
746static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
747 QualType DestType,
748 SourceRange OpRange) {
749 QualType SrcType = SrcExpr->getType();
750 // When casting from pointer or reference, get pointee type; use original
751 // type otherwise.
752 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
753 const CXXRecordDecl *SrcRD =
754 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
755
John McCallf2abe192013-03-27 00:03:48 +0000756 // Examining subobjects for records is only possible if the complete and
757 // valid definition is available. Also, template instantiation is not
758 // allowed here.
759 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000760 return;
761
762 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
763
John McCallf2abe192013-03-27 00:03:48 +0000764 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000765 return;
766
767 enum {
768 ReinterpretUpcast,
769 ReinterpretDowncast
770 } ReinterpretKind;
771
772 CXXBasePaths BasePaths;
773
774 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
775 ReinterpretKind = ReinterpretUpcast;
776 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
777 ReinterpretKind = ReinterpretDowncast;
778 else
779 return;
780
781 bool VirtualBase = true;
782 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000783 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000784 E = BasePaths.end();
785 I != E; ++I) {
786 const CXXBasePath &Path = *I;
787 CharUnits Offset = CharUnits::Zero();
788 bool IsVirtual = false;
789 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
790 IElem != EElem; ++IElem) {
791 IsVirtual = IElem->Base->isVirtual();
792 if (IsVirtual)
793 break;
794 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
795 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000796 // Don't check if any base has invalid declaration or has no definition
797 // since it has no layout info.
798 const CXXRecordDecl *Class = IElem->Class,
799 *ClassDefinition = Class->getDefinition();
800 if (Class->isInvalidDecl() || !ClassDefinition ||
801 !ClassDefinition->isCompleteDefinition())
802 return;
803
John McCallcda80832013-03-22 02:58:14 +0000804 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000805 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000806 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
807 }
808 if (!IsVirtual) {
809 // Don't warn if any path is a non-virtually derived base at offset zero.
810 if (Offset.isZero())
811 return;
812 // Offset makes sense only for non-virtual bases.
813 else
814 NonZeroOffset = true;
815 }
816 VirtualBase = VirtualBase && IsVirtual;
817 }
818
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000819 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000820 assert((VirtualBase || NonZeroOffset) &&
821 "Should have returned if has non-virtual base with zero offset");
822
823 QualType BaseType =
824 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
825 QualType DerivedType =
826 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
827
Jordan Rose04a94d12013-03-28 19:09:40 +0000828 SourceLocation BeginLoc = OpRange.getBegin();
829 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000830 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000831 << OpRange;
832 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000833 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000834 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000835}
836
Sebastian Redl9f831db2009-07-25 15:41:38 +0000837/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
838/// valid.
839/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
840/// like this:
841/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000842void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000843 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000844 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000845 else
846 checkNonOverloadPlaceholders();
847 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
848 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000849
850 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000851 TryCastResult tcr =
852 TryReinterpretCast(Self, SrcExpr, DestType,
853 /*CStyle*/false, OpRange, msg, Kind);
854 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000855 {
John Wiegley01296292011-04-08 18:41:53 +0000856 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
857 return;
858 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000859 //FIXME: &f<int>; is overloaded and resolvable
860 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000861 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000862 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000863 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000864
John McCall909acf82011-02-14 18:34:10 +0000865 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000866 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
867 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000868 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000869 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000870 } else if (tcr == TC_Success) {
871 if (Self.getLangOpts().ObjCAutoRefCount)
872 checkObjCARCConversion(Sema::CCK_OtherCast);
873 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000874 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000875}
876
877
878/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
879/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
880/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000881void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000882 if (isPlaceholder()) {
883 checkNonOverloadPlaceholders();
884 if (SrcExpr.isInvalid())
885 return;
886 }
887
Sebastian Redl9f831db2009-07-25 15:41:38 +0000888 // This test is outside everything else because it's the only case where
889 // a non-lvalue-reference target type does not lead to decay.
890 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000891 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000892 Kind = CK_ToVoid;
893
894 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000895 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000896 false, // Decay Function to ptr
897 true, // Complain
898 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000899 if (SrcExpr.isInvalid())
900 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000901 }
John McCall9776e432011-10-06 23:25:11 +0000902
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000903 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000904 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000905 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000906
John McCall50a2c2c2011-10-11 23:14:30 +0000907 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
908 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000909 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +0000910 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
911 return;
912 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000913
914 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000915 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000916 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000917 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000918 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000919 if (SrcExpr.isInvalid())
920 return;
921 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
922 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000923 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000924 << oe->getName() << DestType << OpRange
925 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000926 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000927 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000928 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
929 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000930 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000931 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000932 } else if (tcr == TC_Success) {
933 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000934 checkCastAlign();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000935 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smith507840d2011-11-29 22:48:16 +0000936 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000937 } else if (Kind == CK_BitCast) {
938 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000939 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000940}
941
942/// TryStaticCast - Check if a static cast can be performed, and do so if
943/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
944/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000945static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000946 QualType DestType,
947 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000948 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000949 CastKind &Kind, CXXCastPath &BasePath,
950 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000951 // Determine whether we have the semantics of a C-style cast.
952 bool CStyle
953 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
954
Sebastian Redl9f831db2009-07-25 15:41:38 +0000955 // The order the tests is not entirely arbitrary. There is one conversion
956 // that can be handled in two different ways. Given:
957 // struct A {};
958 // struct B : public A {
959 // B(); B(const A&);
960 // };
961 // const A &a = B();
962 // the cast static_cast<const B&>(a) could be seen as either a static
963 // reference downcast, or an explicit invocation of the user-defined
964 // conversion using B's conversion constructor.
965 // DR 427 specifies that the downcast is to be applied here.
966
967 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
968 // Done outside this function.
969
970 TryCastResult tcr;
971
972 // C++ 5.2.9p5, reference downcast.
973 // See the function for details.
974 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +0000975 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
976 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000977 if (tcr != TC_NotApplicable)
978 return tcr;
979
Davide Italianoa2275912015-07-12 22:10:56 +0000980 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +0000981 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
982 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redld74dd492012-02-12 18:41:05 +0000983 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
984 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000985 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000986 return tcr;
987
988 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
989 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000990 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000991 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000992 if (SrcExpr.isInvalid())
993 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000994 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000995 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000996
Sebastian Redl9f831db2009-07-25 15:41:38 +0000997 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
998 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
999 // conversions, subject to further restrictions.
1000 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1001 // of qualification conversions impossible.
1002 // In the CStyle case, the earlier attempt to const_cast should have taken
1003 // care of reverse qualification conversions.
1004
John Wiegley01296292011-04-08 18:41:53 +00001005 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001006
Douglas Gregor0bf31402010-10-08 23:50:27 +00001007 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001008 // converted to an integral type. [...] A value of a scoped enumeration type
1009 // can also be explicitly converted to a floating-point type [...].
1010 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1011 if (Enum->getDecl()->isScoped()) {
1012 if (DestType->isBooleanType()) {
1013 Kind = CK_IntegralToBoolean;
1014 return TC_Success;
1015 } else if (DestType->isIntegralType(Self.Context)) {
1016 Kind = CK_IntegralCast;
1017 return TC_Success;
1018 } else if (DestType->isRealFloatingType()) {
1019 Kind = CK_IntegralToFloating;
1020 return TC_Success;
1021 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001022 }
1023 }
Douglas Gregorb327eac2011-02-18 03:01:41 +00001024
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 // Reverse integral promotion/conversion. All such conversions are themselves
1026 // again integral promotions or conversions and are thus already handled by
1027 // p2 (TryDirectInitialization above).
1028 // (Note: any data loss warnings should be suppressed.)
1029 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1030 // enum->enum). See also C++ 5.2.9p7.
1031 // The same goes for reverse floating point promotion/conversion and
1032 // floating-integral conversions. Again, only floating->enum is relevant.
1033 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001034 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001035 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001036 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001037 } else if (SrcType->isRealFloatingType()) {
1038 Kind = CK_FloatingToIntegral;
1039 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001040 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001041 }
1042
1043 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1044 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001045 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001046 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001047 if (tcr != TC_NotApplicable)
1048 return tcr;
1049
1050 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1051 // conversion. C++ 5.2.9p9 has additional information.
1052 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001053 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001054 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001055 if (tcr != TC_NotApplicable)
1056 return tcr;
1057
1058 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1059 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1060 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001062 QualType SrcPointee = SrcPointer->getPointeeType();
1063 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001064 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001065 QualType DestPointee = DestPointer->getPointeeType();
1066 if (DestPointee->isIncompleteOrObjectType()) {
1067 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001068 // to a qualifier violation. Note that we permit Objective-C lifetime
1069 // and GC qualifier mismatches here.
1070 if (!CStyle) {
1071 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1072 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1073 DestPointeeQuals.removeObjCGCAttr();
1074 DestPointeeQuals.removeObjCLifetime();
1075 SrcPointeeQuals.removeObjCGCAttr();
1076 SrcPointeeQuals.removeObjCLifetime();
1077 if (DestPointeeQuals != SrcPointeeQuals &&
1078 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1079 msg = diag::err_bad_cxx_cast_qualifiers_away;
1080 return TC_Failed;
1081 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001082 }
John McCalle3027922010-08-25 11:45:40 +00001083 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001084 return TC_Success;
1085 }
David Majnemer85bd1202015-06-02 22:15:12 +00001086
1087 // Microsoft permits static_cast from 'pointer-to-void' to
1088 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001089 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1090 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001091 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1092 Kind = CK_BitCast;
1093 return TC_Success;
1094 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001095 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001096 else if (DestType->isObjCObjectPointerType()) {
1097 // allow both c-style cast and static_cast of objective-c pointers as
1098 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001099 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001100 return TC_Success;
1101 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001102 else if (CStyle && DestType->isBlockPointerType()) {
1103 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001104 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001105 return TC_Success;
1106 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001107 }
1108 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001109 // Allow arbitray objective-c pointer conversion with static casts.
1110 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001111 DestType->isObjCObjectPointerType()) {
1112 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001113 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001114 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001115 // Allow ns-pointer to cf-pointer conversion in either direction
1116 // with static casts.
1117 if (!CStyle &&
1118 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1119 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001120
1121 // See if it looks like the user is trying to convert between
1122 // related record types, and select a better diagnostic if so.
1123 if (auto SrcPointer = SrcType->getAs<PointerType>())
1124 if (auto DestPointer = DestType->getAs<PointerType>())
1125 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1126 DestPointer->getPointeeType()->getAs<RecordType>())
1127 msg = diag::err_bad_cxx_cast_unrelated_class;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001128
Sebastian Redl9f831db2009-07-25 15:41:38 +00001129 // We tried everything. Everything! Nothing works! :-(
1130 return TC_NotApplicable;
1131}
1132
1133/// Tests whether a conversion according to N2844 is valid.
1134TryCastResult
1135TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +00001136 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1137 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001138 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001139 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1140 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001141 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001142 if (!R)
1143 return TC_NotApplicable;
1144
Douglas Gregor465184a2011-01-22 00:06:57 +00001145 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001146 return TC_NotApplicable;
1147
1148 // Because we try the reference downcast before this function, from now on
1149 // this is the only cast possibility, so we issue an error if we fail now.
1150 // FIXME: Should allow casting away constness if CStyle.
1151 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001152 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001153 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001154 QualType FromType = SrcExpr->getType();
1155 QualType ToType = R->getPointeeType();
1156 if (CStyle) {
1157 FromType = FromType.getUnqualifiedType();
1158 ToType = ToType.getUnqualifiedType();
1159 }
1160
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001161 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +00001162 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +00001163 DerivedToBase, ObjCConversion,
1164 ObjCLifetimeConversion)
1165 < Sema::Ref_Compatible_With_Added_Qualification) {
Davide Italianoa2275912015-07-12 22:10:56 +00001166 if (CStyle)
1167 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001168 msg = diag::err_bad_lvalue_to_rvalue_cast;
1169 return TC_Failed;
1170 }
1171
Douglas Gregorba278e22011-01-25 16:13:26 +00001172 if (DerivedToBase) {
1173 Kind = CK_DerivedToBase;
1174 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1175 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001176 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1177 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001178 return TC_NotApplicable;
1179
1180 Self.BuildBasePathArray(Paths, BasePath);
1181 } else
1182 Kind = CK_NoOp;
1183
Sebastian Redl9f831db2009-07-25 15:41:38 +00001184 return TC_Success;
1185}
1186
1187/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1188TryCastResult
1189TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001190 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001191 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001192 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001193 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1194 // cast to type "reference to cv2 D", where D is a class derived from B,
1195 // if a valid standard conversion from "pointer to D" to "pointer to B"
1196 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1197 // In addition, DR54 clarifies that the base must be accessible in the
1198 // current context. Although the wording of DR54 only applies to the pointer
1199 // variant of this rule, the intent is clearly for it to apply to the this
1200 // conversion as well.
1201
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001202 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001203 if (!DestReference) {
1204 return TC_NotApplicable;
1205 }
1206 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001207 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001208 // We know the left side is an lvalue reference, so we can suggest a reason.
1209 msg = diag::err_bad_cxx_cast_rvalue;
1210 return TC_NotApplicable;
1211 }
1212
1213 QualType DestPointee = DestReference->getPointeeType();
1214
Richard Smith11330852014-07-08 17:25:14 +00001215 // FIXME: If the source is a prvalue, we should issue a warning (because the
1216 // cast always has undefined behavior), and for AST consistency, we should
1217 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001218 return TryStaticDowncast(Self,
1219 Self.Context.getCanonicalType(SrcExpr->getType()),
1220 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001221 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1222 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001223}
1224
1225/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1226TryCastResult
1227TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001228 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001229 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001230 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001231 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1232 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1233 // is a class derived from B, if a valid standard conversion from "pointer
1234 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1235 // class of D.
1236 // In addition, DR54 clarifies that the base must be accessible in the
1237 // current context.
1238
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001239 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001240 if (!DestPointer) {
1241 return TC_NotApplicable;
1242 }
1243
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001244 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001245 if (!SrcPointer) {
1246 msg = diag::err_bad_static_cast_pointer_nonpointer;
1247 return TC_NotApplicable;
1248 }
1249
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001250 return TryStaticDowncast(Self,
1251 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1252 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001253 CStyle, OpRange, SrcType, DestType, msg, Kind,
1254 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001255}
1256
1257/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1258/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001259/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001260TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001261TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001262 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001263 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001264 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001265 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001266 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1267 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001268 return TC_NotApplicable;
1269
Sebastian Redl9f831db2009-07-25 15:41:38 +00001270 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001271 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001272 return TC_NotApplicable;
1273 }
1274
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001275 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001276 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001277 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001278 return TC_NotApplicable;
1279 }
1280
1281 // Target type does derive from source type. Now we're serious. If an error
1282 // appears now, it's not ignored.
1283 // This may not be entirely in line with the standard. Take for example:
1284 // struct A {};
1285 // struct B : virtual A {
1286 // B(A&);
1287 // };
Mike Stump11289f42009-09-09 15:08:12 +00001288 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001289 // void f()
1290 // {
1291 // (void)static_cast<const B&>(*((A*)0));
1292 // }
1293 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1294 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1295 // However, both GCC and Comeau reject this example, and accepting it would
1296 // mean more complex code if we're to preserve the nice error message.
1297 // FIXME: Being 100% compliant here would be nice to have.
1298
1299 // Must preserve cv, as always, unless we're in C-style mode.
1300 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001301 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001302 return TC_Failed;
1303 }
1304
1305 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1306 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1307 // that it builds the paths in reverse order.
1308 // To sum up: record all paths to the base and build a nice string from
1309 // them. Use it to spice up the error message.
1310 if (!Paths.isRecordingPaths()) {
1311 Paths.clear();
1312 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001313 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001314 }
1315 std::string PathDisplayStr;
1316 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001317 for (clang::CXXBasePath &Path : Paths) {
1318 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001319 // We haven't displayed a path to this particular base
1320 // class subobject yet.
1321 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001322 for (CXXBasePathElement &PE : llvm::reverse(Path))
1323 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001324 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001325 }
1326 }
1327
1328 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001329 << QualType(SrcType).getUnqualifiedType()
1330 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001331 << PathDisplayStr << OpRange;
1332 msg = 0;
1333 return TC_Failed;
1334 }
1335
Craig Topperc3ec1492014-05-26 06:22:03 +00001336 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001337 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1338 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1339 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1340 msg = 0;
1341 return TC_Failed;
1342 }
1343
John McCallfe9cf0a2011-02-14 23:21:33 +00001344 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001345 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1346 SrcType, DestType,
1347 Paths.front(),
1348 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001349 case Sema::AR_accessible:
1350 case Sema::AR_delayed: // be optimistic
1351 case Sema::AR_dependent: // be optimistic
1352 break;
1353
1354 case Sema::AR_inaccessible:
1355 msg = 0;
1356 return TC_Failed;
1357 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001358 }
1359
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001360 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001361 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001362 return TC_Success;
1363}
1364
1365/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1366/// C++ 5.2.9p9 is valid:
1367///
1368/// An rvalue of type "pointer to member of D of type cv1 T" can be
1369/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1370/// where B is a base class of D [...].
1371///
1372TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001373TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001374 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001375 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001376 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001377 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001378 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001379 if (!DestMemPtr)
1380 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001381
1382 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001383 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001384 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001385 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001386 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001387 FoundOverload)) {
1388 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1389 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1390 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1391 WasOverloadedFunction = true;
1392 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001393 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001394
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001395 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001396 if (!SrcMemPtr) {
1397 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1398 return TC_NotApplicable;
1399 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001400
1401 // Lock down the inheritance model right now in MS ABI, whether or not the
1402 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001403 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001404 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001405 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1406 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001407
1408 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001409 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1410 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001411 return TC_NotApplicable;
1412
1413 // B base of D
1414 QualType SrcClass(SrcMemPtr->getClass(), 0);
1415 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001416 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001417 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001418 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001419 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001420
1421 // 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 +00001422 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001423 Paths.clear();
1424 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001425 bool StillOkay =
1426 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001427 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001428 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001429 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1430 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1431 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1432 msg = 0;
1433 return TC_Failed;
1434 }
1435
1436 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1437 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1438 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1439 msg = 0;
1440 return TC_Failed;
1441 }
1442
John McCallfe9cf0a2011-02-14 23:21:33 +00001443 if (!CStyle) {
1444 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1445 DestClass, SrcClass,
1446 Paths.front(),
1447 diag::err_upcast_to_inaccessible_base)) {
1448 case Sema::AR_accessible:
1449 case Sema::AR_delayed:
1450 case Sema::AR_dependent:
1451 // Optimistically assume that the delayed and dependent cases
1452 // will work out.
1453 break;
1454
1455 case Sema::AR_inaccessible:
1456 msg = 0;
1457 return TC_Failed;
1458 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001459 }
1460
Douglas Gregorc934bc82010-03-07 23:24:59 +00001461 if (WasOverloadedFunction) {
1462 // Resolve the address of the overloaded function again, this time
1463 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001464 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001465 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001466 true,
1467 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001468 if (!Fn) {
1469 msg = 0;
1470 return TC_Failed;
1471 }
1472
John McCall16df1e52010-03-30 21:47:33 +00001473 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001474 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001475 msg = 0;
1476 return TC_Failed;
1477 }
1478 }
1479
Anders Carlssonb78feca2010-04-24 19:22:20 +00001480 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001481 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001482 return TC_Success;
1483}
1484
1485/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1486/// is valid:
1487///
1488/// An expression e can be explicitly converted to a type T using a
1489/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1490TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001491TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001492 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001493 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001494 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001495 if (DestType->isRecordType()) {
1496 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001497 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001498 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001499 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001500 msg = 0;
1501 return TC_Failed;
1502 }
1503 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001504
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001505 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1506 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001507 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001508 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001509 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001510 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001511 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001512 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001513 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001514 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001515
1516 // At this point of CheckStaticCast, if the destination is a reference,
1517 // or the expression is an overload expression this has to work.
1518 // There is no other way that works.
1519 // On the other hand, if we're checking a C-style cast, we've still got
1520 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001521 bool CStyle
1522 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001523 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001524 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001525
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001526 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001527 if (Result.isInvalid()) {
1528 msg = 0;
1529 return TC_Failed;
1530 }
1531
Douglas Gregorb33eed02010-04-16 22:09:46 +00001532 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001533 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001534 else
John McCalle3027922010-08-25 11:45:40 +00001535 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001536
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001537 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001538 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001539}
1540
1541/// TryConstCast - See if a const_cast from source to destination is allowed,
1542/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001543static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1544 QualType DestType, bool CStyle,
1545 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001546 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001547 QualType SrcType = SrcExpr.get()->getType();
1548 bool NeedToMaterializeTemporary = false;
1549
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001550 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001551 // C++11 5.2.11p4:
1552 // if a pointer to T1 can be explicitly converted to the type "pointer to
1553 // T2" using a const_cast, then the following conversions can also be
1554 // made:
1555 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1556 // type T2 using the cast const_cast<T2&>;
1557 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1558 // type T2 using the cast const_cast<T2&&>; and
1559 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1560 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1561
1562 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001563 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1564 // is C-style, static_cast might find a way, so we simply suggest a
1565 // message and tell the parent to keep searching.
1566 msg = diag::err_bad_cxx_cast_rvalue;
1567 return TC_NotApplicable;
1568 }
1569
Richard Smith82c9b512013-06-14 22:27:52 +00001570 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1571 if (!SrcType->isRecordType()) {
1572 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1573 // this is C-style, static_cast can do this.
1574 msg = diag::err_bad_cxx_cast_rvalue;
1575 return TC_NotApplicable;
1576 }
1577
1578 // Materialize the class prvalue so that the const_cast can bind a
1579 // reference to it.
1580 NeedToMaterializeTemporary = true;
1581 }
1582
John McCalld25db7e2013-05-06 21:39:12 +00001583 // It's not completely clear under the standard whether we can
1584 // const_cast bit-field gl-values. Doing so would not be
1585 // intrinsically complicated, but for now, we say no for
1586 // consistency with other compilers and await the word of the
1587 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001588 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001589 msg = diag::err_bad_cxx_cast_bitfield;
1590 return TC_NotApplicable;
1591 }
1592
Sebastian Redl9f831db2009-07-25 15:41:38 +00001593 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1594 SrcType = Self.Context.getPointerType(SrcType);
1595 }
1596
1597 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1598 // the rules for const_cast are the same as those used for pointers.
1599
John McCall0e704f72010-05-18 09:35:29 +00001600 if (!DestType->isPointerType() &&
1601 !DestType->isMemberPointerType() &&
1602 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001603 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1604 // was a reference type, we converted it to a pointer above.
1605 // The status of rvalue references isn't entirely clear, but it looks like
1606 // conversion to them is simply invalid.
1607 // C++ 5.2.11p3: For two pointer types [...]
1608 if (!CStyle)
1609 msg = diag::err_bad_const_cast_dest;
1610 return TC_NotApplicable;
1611 }
1612 if (DestType->isFunctionPointerType() ||
1613 DestType->isMemberFunctionPointerType()) {
1614 // Cannot cast direct function pointers.
1615 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1616 // T is the ultimate pointee of source and target type.
1617 if (!CStyle)
1618 msg = diag::err_bad_const_cast_dest;
1619 return TC_NotApplicable;
1620 }
1621 SrcType = Self.Context.getCanonicalType(SrcType);
1622
1623 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1624 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001625 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1626 // in multi-level pointers may change, but the level count must be the same,
1627 // as must be the final pointee type.
1628 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001629 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001630 Qualifiers SrcQuals, DestQuals;
1631 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1632 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1633
1634 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1635 // the other qualifiers (e.g., address spaces) are identical.
1636 SrcQuals.removeCVRQualifiers();
1637 DestQuals.removeCVRQualifiers();
1638 if (SrcQuals != DestQuals)
1639 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001640 }
1641
1642 // Since we're dealing in canonical types, the remainder must be the same.
1643 if (SrcType != DestType)
1644 return TC_NotApplicable;
1645
Richard Smith82c9b512013-06-14 22:27:52 +00001646 if (NeedToMaterializeTemporary)
1647 // This is a const_cast from a class prvalue to an rvalue reference type.
1648 // Materialize a temporary to store the result of the conversion.
Tim Shen4a05bb82016-06-21 20:29:17 +00001649 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
1650 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001651
Sebastian Redl9f831db2009-07-25 15:41:38 +00001652 return TC_Success;
1653}
1654
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001655// Checks for undefined behavior in reinterpret_cast.
1656// The cases that is checked for is:
1657// *reinterpret_cast<T*>(&a)
1658// reinterpret_cast<T&>(a)
1659// where accessing 'a' as type 'T' will result in undefined behavior.
1660void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1661 bool IsDereference,
1662 SourceRange Range) {
1663 unsigned DiagID = IsDereference ?
1664 diag::warn_pointer_indirection_from_incompatible_type :
1665 diag::warn_undefined_reinterpret_cast;
1666
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001667 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001668 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001669
1670 QualType SrcTy, DestTy;
1671 if (IsDereference) {
1672 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1673 return;
1674 }
1675 SrcTy = SrcType->getPointeeType();
1676 DestTy = DestType->getPointeeType();
1677 } else {
1678 if (!DestType->getAs<ReferenceType>()) {
1679 return;
1680 }
1681 SrcTy = SrcType;
1682 DestTy = DestType->getPointeeType();
1683 }
1684
1685 // Cast is compatible if the types are the same.
1686 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1687 return;
1688 }
1689 // or one of the types is a char or void type
1690 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1691 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1692 return;
1693 }
1694 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001695 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001696 return;
1697 }
1698
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001699 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001700 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1701 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1702 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1703 return;
1704 }
1705 }
1706
1707 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1708}
Douglas Gregor1beec452011-03-12 01:48:56 +00001709
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001710static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1711 QualType DestType) {
1712 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001713 if (Self.Context.hasSameType(SrcType, DestType))
1714 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001715 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1716 if (SrcPtrTy->isObjCSelType()) {
1717 QualType DT = DestType;
1718 if (isa<PointerType>(DestType))
1719 DT = DestType->getPointeeType();
1720 if (!DT.getUnqualifiedType()->isVoidType())
1721 Self.Diag(SrcExpr.get()->getExprLoc(),
1722 diag::warn_cast_pointer_from_sel)
1723 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1724 }
1725}
1726
Reid Kleckner9f497332016-05-10 21:00:03 +00001727/// Diagnose casts that change the calling convention of a pointer to a function
1728/// defined in the current TU.
1729static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1730 QualType DstType, SourceRange OpRange) {
1731 // Check if this cast would change the calling convention of a function
1732 // pointer type.
1733 QualType SrcType = SrcExpr.get()->getType();
1734 if (Self.Context.hasSameType(SrcType, DstType) ||
1735 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1736 return;
1737 const auto *SrcFTy =
1738 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1739 const auto *DstFTy =
1740 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1741 CallingConv SrcCC = SrcFTy->getCallConv();
1742 CallingConv DstCC = DstFTy->getCallConv();
1743 if (SrcCC == DstCC)
1744 return;
1745
1746 // We have a calling convention cast. Check if the source is a pointer to a
1747 // known, specific function that has already been defined.
1748 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1749 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1750 if (UO->getOpcode() == UO_AddrOf)
1751 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1752 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1753 if (!DRE)
1754 return;
1755 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1756 const FunctionDecl *Definition;
1757 if (!FD || !FD->hasBody(Definition))
1758 return;
1759
Reid Kleckner43be52a2016-05-11 17:43:13 +00001760 // Only warn if we are casting from the default convention to a non-default
1761 // convention. This can happen when the programmer forgot to apply the calling
1762 // convention to the function definition and then inserted this cast to
1763 // satisfy the type system.
1764 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1765 FD->isVariadic(), FD->isCXXInstanceMember());
1766 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1767 return;
1768
Reid Kleckner9f497332016-05-10 21:00:03 +00001769 // Diagnose this cast, as it is probably bad.
1770 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1771 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1772 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1773 << SrcCCName << DstCCName << OpRange;
1774
1775 // The checks above are cheaper than checking if the diagnostic is enabled.
1776 // However, it's worth checking if the warning is enabled before we construct
1777 // a fixit.
1778 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1779 return;
1780
1781 // Try to suggest a fixit to change the calling convention of the function
1782 // whose address was taken. Try to use the latest macro for the convention.
1783 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1784 // to match the Windows header declarations.
1785 SourceLocation NameLoc = Definition->getNameInfo().getLoc();
1786 Preprocessor &PP = Self.getPreprocessor();
1787 SmallVector<TokenValue, 6> AttrTokens;
1788 SmallString<64> CCAttrText;
1789 llvm::raw_svector_ostream OS(CCAttrText);
1790 if (Self.getLangOpts().MicrosoftExt) {
1791 // __stdcall or __vectorcall
1792 OS << "__" << DstCCName;
1793 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1794 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1795 ? TokenValue(II->getTokenID())
1796 : TokenValue(II));
1797 } else {
1798 // __attribute__((stdcall)) or __attribute__((vectorcall))
1799 OS << "__attribute__((" << DstCCName << "))";
1800 AttrTokens.push_back(tok::kw___attribute);
1801 AttrTokens.push_back(tok::l_paren);
1802 AttrTokens.push_back(tok::l_paren);
1803 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1804 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1805 ? TokenValue(II->getTokenID())
1806 : TokenValue(II));
1807 AttrTokens.push_back(tok::r_paren);
1808 AttrTokens.push_back(tok::r_paren);
1809 }
1810 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1811 if (!AttrSpelling.empty())
1812 CCAttrText = AttrSpelling;
1813 OS << ' ';
1814 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1815 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1816}
1817
David Blaikie282ad872012-10-16 18:53:14 +00001818static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1819 const Expr *SrcExpr, QualType DestType,
1820 Sema &Self) {
1821 QualType SrcType = SrcExpr->getType();
1822
1823 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1824 // are not explicit design choices, but consistent with GCC's behavior.
1825 // Feel free to modify them if you've reason/evidence for an alternative.
1826 if (CStyle && SrcType->isIntegralType(Self.Context)
1827 && !SrcType->isBooleanType()
1828 && !SrcType->isEnumeralType()
1829 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001830 && Self.Context.getTypeSize(DestType) >
1831 Self.Context.getTypeSize(SrcType)) {
1832 // Separate between casts to void* and non-void* pointers.
1833 // Some APIs use (abuse) void* for something like a user context,
1834 // and often that value is an integer even if it isn't a pointer itself.
1835 // Having a separate warning flag allows users to control the warning
1836 // for their workflow.
1837 unsigned Diag = DestType->isVoidPointerType() ?
1838 diag::warn_int_to_void_pointer_cast
1839 : diag::warn_int_to_pointer_cast;
1840 Self.Diag(Loc, Diag) << SrcType << DestType;
1841 }
David Blaikie282ad872012-10-16 18:53:14 +00001842}
1843
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001844static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1845 ExprResult &Result) {
1846 // We can only fix an overloaded reinterpret_cast if
1847 // - it is a template with explicit arguments that resolves to an lvalue
1848 // unambiguously, or
1849 // - it is the only function in an overload set that may have its address
1850 // taken.
1851
1852 Expr *E = Result.get();
1853 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1854 // like it?
1855 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1856 Result,
1857 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1858 ) &&
1859 Result.isUsable())
1860 return true;
1861
George Burgess IVbeca4a32016-06-08 00:34:22 +00001862 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1863 // preserves Result.
1864 Result = E;
1865 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001866 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00001867 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001868}
1869
John Wiegley01296292011-04-08 18:41:53 +00001870static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001871 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001872 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001873 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001874 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001875 bool IsLValueCast = false;
1876
Sebastian Redl9f831db2009-07-25 15:41:38 +00001877 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001878 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001879
1880 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001881 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001882 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001883 ExprResult FixedExpr = SrcExpr;
1884 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001885 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001886
1887 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1888 SrcExpr = FixedExpr;
1889 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001890 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001891
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001892 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001893 if (!SrcExpr.get()->isGLValue()) {
1894 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1895 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001896 msg = diag::err_bad_cxx_cast_rvalue;
1897 return TC_NotApplicable;
1898 }
1899
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001900 if (!CStyle) {
1901 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1902 /*isDereference=*/false, OpRange);
1903 }
1904
Sebastian Redl9f831db2009-07-25 15:41:38 +00001905 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1906 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1907 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001908
Craig Topperc3ec1492014-05-26 06:22:03 +00001909 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001910 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001911 case OK_Ordinary:
1912 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001913 case OK_BitField: inappropriate = "bit-field"; break;
1914 case OK_VectorComponent: inappropriate = "vector element"; break;
1915 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001916 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1917 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001918 }
1919 if (inappropriate) {
1920 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1921 << inappropriate << DestType
1922 << OpRange << SrcExpr.get()->getSourceRange();
1923 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001924 return TC_NotApplicable;
1925 }
1926
Sebastian Redl9f831db2009-07-25 15:41:38 +00001927 // This code does this transformation for the checked types.
1928 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1929 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001930
Douglas Gregor51954272010-07-13 23:17:26 +00001931 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001932 }
1933
1934 // Canonicalize source for comparison.
1935 SrcType = Self.Context.getCanonicalType(SrcType);
1936
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001937 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1938 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001939 if (DestMemPtr && SrcMemPtr) {
1940 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1941 // can be explicitly converted to an rvalue of type "pointer to member
1942 // of Y of type T2" if T1 and T2 are both function types or both object
1943 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00001944 if (DestMemPtr->isMemberFunctionPointer() !=
1945 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001946 return TC_NotApplicable;
1947
1948 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1949 // constness.
1950 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1951 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001952 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1953 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001954 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001955 return TC_Failed;
1956 }
1957
David Majnemer1cdd96d2014-01-17 09:01:00 +00001958 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1959 // We need to determine the inheritance model that the class will use if
1960 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00001961 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1962 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00001963 }
1964
Charles Davisebab1ed2010-08-16 05:30:44 +00001965 // Don't allow casting between member pointers of different sizes.
1966 if (Self.Context.getTypeSize(DestMemPtr) !=
1967 Self.Context.getTypeSize(SrcMemPtr)) {
1968 msg = diag::err_bad_cxx_cast_member_pointer_size;
1969 return TC_Failed;
1970 }
1971
Sebastian Redl9f831db2009-07-25 15:41:38 +00001972 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00001973 assert(!IsLValueCast);
1974 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001975 return TC_Success;
1976 }
1977
1978 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001979 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001980 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1981 // type large enough to hold it. A value of std::nullptr_t can be
1982 // converted to an integral type; the conversion has the same meaning
1983 // and validity as a conversion of (void*)0 to the integral type.
1984 if (Self.Context.getTypeSize(SrcType) >
1985 Self.Context.getTypeSize(DestType)) {
1986 msg = diag::err_bad_reinterpret_cast_small_int;
1987 return TC_Failed;
1988 }
John McCalle3027922010-08-25 11:45:40 +00001989 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001990 return TC_Success;
1991 }
1992
John McCall1c78f082015-07-23 23:54:07 +00001993 // Allow reinterpret_casts between vectors of the same size and
1994 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00001995 bool destIsVector = DestType->isVectorType();
1996 bool srcIsVector = SrcType->isVectorType();
1997 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00001998 // The non-vector type, if any, must have integral type. This is
1999 // the same rule that C vector casts use; note, however, that enum
2000 // types are not integral in C++.
2001 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2002 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002003 return TC_NotApplicable;
2004
John McCall1c78f082015-07-23 23:54:07 +00002005 // The size we want to consider is eltCount * eltSize.
2006 // That's exactly what the lax-conversion rules will check.
2007 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002008 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002009 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002010 }
John McCall1c78f082015-07-23 23:54:07 +00002011
2012 // Otherwise, pick a reasonable diagnostic.
2013 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002014 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002015 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002016 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2017 else
2018 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2019
2020 return TC_Failed;
2021 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002022
2023 if (SrcType == DestType) {
2024 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2025 // restrictions, a cast to the same type is allowed so long as it does not
2026 // cast away constness. In C++98, the intent was not entirely clear here,
2027 // since all other paragraphs explicitly forbid casts to the same type.
2028 // C++11 clarifies this case with p2.
2029 //
2030 // The only allowed types are: integral, enumeration, pointer, or
2031 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2032 Kind = CK_NoOp;
2033 TryCastResult Result = TC_NotApplicable;
2034 if (SrcType->isIntegralOrEnumerationType() ||
2035 SrcType->isAnyPointerType() ||
2036 SrcType->isMemberPointerType() ||
2037 SrcType->isBlockPointerType()) {
2038 Result = TC_Success;
2039 }
2040 return Result;
2041 }
2042
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002043 bool destIsPtr = DestType->isAnyPointerType() ||
2044 DestType->isBlockPointerType();
2045 bool srcIsPtr = SrcType->isAnyPointerType() ||
2046 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002047 if (!destIsPtr && !srcIsPtr) {
2048 // Except for std::nullptr_t->integer and lvalue->reference, which are
2049 // handled above, at least one of the two arguments must be a pointer.
2050 return TC_NotApplicable;
2051 }
2052
Douglas Gregor6972a622010-06-16 00:35:25 +00002053 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002054 assert(srcIsPtr && "One type must be a pointer");
2055 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002056 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002057 // integral type size doesn't matter (except we don't allow bool).
2058 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2059 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002060 if ((Self.Context.getTypeSize(SrcType) >
2061 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002062 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002063 msg = diag::err_bad_reinterpret_cast_small_int;
2064 return TC_Failed;
2065 }
John McCalle3027922010-08-25 11:45:40 +00002066 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002067 return TC_Success;
2068 }
2069
Douglas Gregorb90df602010-06-16 00:17:44 +00002070 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002071 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002072 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2073 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002074 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2075 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002076 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2077 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002078 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002079 return TC_Success;
2080 }
2081
2082 if (!destIsPtr || !srcIsPtr) {
2083 // With the valid non-pointer conversions out of the way, we can be even
2084 // more stringent.
2085 return TC_NotApplicable;
2086 }
2087
2088 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2089 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00002090 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2091 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00002092 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002093 return TC_Failed;
2094 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002095
2096 // Cannot convert between block pointers and Objective-C object pointers.
2097 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2098 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2099 return TC_NotApplicable;
2100
John McCall9320b872011-09-09 05:25:32 +00002101 if (IsLValueCast) {
2102 Kind = CK_LValueBitCast;
2103 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002104 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002105 } else if (DestType->isBlockPointerType()) {
2106 if (!SrcType->isBlockPointerType()) {
2107 Kind = CK_AnyPointerToBlockPointerCast;
2108 } else {
2109 Kind = CK_BitCast;
2110 }
2111 } else {
2112 Kind = CK_BitCast;
2113 }
2114
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002115 // Any pointer can be cast to an Objective-C pointer type with a C-style
2116 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002117 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002118 return TC_Success;
2119 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002120 if (CStyle)
2121 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002122
2123 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2124
Sebastian Redl9f831db2009-07-25 15:41:38 +00002125 // Not casting away constness, so the only remaining check is for compatible
2126 // pointer categories.
2127
2128 if (SrcType->isFunctionPointerType()) {
2129 if (DestType->isFunctionPointerType()) {
2130 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2131 // a pointer to a function of a different type.
2132 return TC_Success;
2133 }
2134
2135 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2136 // an object type or vice versa is conditionally-supported.
2137 // Compilers support it in C++03 too, though, because it's necessary for
2138 // casting the return value of dlsym() and GetProcAddress().
2139 // FIXME: Conditionally-supported behavior should be configurable in the
2140 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002141 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002142 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002143 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2144 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002145 return TC_Success;
2146 }
2147
2148 if (DestType->isFunctionPointerType()) {
2149 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002150 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002151 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002152 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2153 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002154 return TC_Success;
2155 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002156
Sebastian Redl9f831db2009-07-25 15:41:38 +00002157 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2158 // a pointer to an object of different type.
2159 // Void pointers are not specified, but supported by every compiler out there.
2160 // So we finish by allowing everything that remains - it's got to be two
2161 // object pointers.
2162 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00002163}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002164
Sebastian Redld74dd492012-02-12 18:41:05 +00002165void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2166 bool ListInitialization) {
John McCall9776e432011-10-06 23:25:11 +00002167 // Handle placeholders.
2168 if (isPlaceholder()) {
2169 // C-style casts can resolve __unknown_any types.
2170 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2171 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2172 SrcExpr.get(), Kind,
2173 ValueKind, BasePath);
2174 return;
2175 }
John McCallb50451a2011-10-05 07:41:44 +00002176
John McCall9776e432011-10-06 23:25:11 +00002177 checkNonOverloadPlaceholders();
2178 if (SrcExpr.isInvalid())
2179 return;
John McCalla072f5d2011-10-17 17:42:19 +00002180 }
John McCall9776e432011-10-06 23:25:11 +00002181
2182 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002183 // This test is outside everything else because it's the only case where
2184 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002185 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002186 Kind = CK_ToVoid;
2187
John McCall9776e432011-10-06 23:25:11 +00002188 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002189 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2190 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002191 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002192 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002193 if (SrcExpr.isInvalid())
2194 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002195 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002196
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002197 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002198 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002199 }
2200
Sebastian Redl9f831db2009-07-25 15:41:38 +00002201 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002202 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2203 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002204 assert(Kind == CK_Dependent);
2205 return;
John McCall8cb679e2010-11-15 09:13:47 +00002206 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002207
John McCall50a2c2c2011-10-11 23:14:30 +00002208 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2209 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002210 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002211 if (SrcExpr.isInvalid())
2212 return;
John Wiegley01296292011-04-08 18:41:53 +00002213 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002214
John McCall3aef3d82011-04-10 19:13:55 +00002215 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002216 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002217 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002218 && (SrcExpr.get()->getType()->isIntegerType()
2219 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002220 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002221 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002222 return;
John McCall3aef3d82011-04-10 19:13:55 +00002223 }
2224
Sebastian Redl9f831db2009-07-25 15:41:38 +00002225 // C++ [expr.cast]p5: The conversions performed by
2226 // - a const_cast,
2227 // - a static_cast,
2228 // - a static_cast followed by a const_cast,
2229 // - a reinterpret_cast, or
2230 // - a reinterpret_cast followed by a const_cast,
2231 // can be performed using the cast notation of explicit type conversion.
2232 // [...] If a conversion can be interpreted in more than one of the ways
2233 // listed above, the interpretation that appears first in the list is used,
2234 // even if a cast resulting from that interpretation is ill-formed.
2235 // In plain language, this means trying a const_cast ...
2236 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002237 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002238 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002239 if (SrcExpr.isInvalid())
2240 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002241 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002242 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002243
John McCall31168b02011-06-15 23:02:42 +00002244 Sema::CheckedConversionKind CCK
2245 = FunctionalStyle? Sema::CCK_FunctionalCast
2246 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002247 if (tcr == TC_NotApplicable) {
2248 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002249 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002250 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002251 if (SrcExpr.isInvalid())
2252 return;
2253
Sebastian Redl9f831db2009-07-25 15:41:38 +00002254 if (tcr == TC_NotApplicable) {
2255 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002256 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2257 OpRange, msg, Kind);
2258 if (SrcExpr.isInvalid())
2259 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002260 }
2261 }
2262
David Blaikiebbafb8a2012-03-11 07:00:24 +00002263 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002264 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002265
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002266 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002267 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002268 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002269 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2270 DestType,
2271 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002272 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002273 if (Fn) {
2274 // If DestType is a function type (not to be confused with the function
2275 // pointer type), it will be possible to resolve the function address,
2276 // but the type cast should be considered as failure.
2277 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2278 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2279 << OE->getName() << DestType << OpRange
2280 << OE->getQualifierLoc().getSourceRange();
2281 Self.NoteAllOverloadCandidates(SrcExpr.get());
2282 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002283 } else {
John McCallb50451a2011-10-05 07:41:44 +00002284 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002285 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002286 }
John McCallb50451a2011-10-05 07:41:44 +00002287 } else if (Kind == CK_BitCast) {
2288 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002289 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002290
John McCallb50451a2011-10-05 07:41:44 +00002291 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002292 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002293 SrcExpr = ExprError();
2294}
2295
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002296/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2297/// non-matching type. Such as enum function call to int, int call to
2298/// pointer; etc. Cast to 'void' is an exception.
2299static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2300 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002301 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2302 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002303 return;
2304
2305 if (!isa<CallExpr>(SrcExpr.get()))
2306 return;
2307
2308 QualType SrcType = SrcExpr.get()->getType();
2309 if (DestType.getUnqualifiedType()->isVoidType())
2310 return;
2311 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2312 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2313 return;
2314 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2315 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2316 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2317 return;
2318 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2319 return;
2320 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2321 return;
2322 if (SrcType->isComplexType() && DestType->isComplexType())
2323 return;
2324 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2325 return;
2326
2327 Self.Diag(SrcExpr.get()->getExprLoc(),
2328 diag::warn_bad_function_cast)
2329 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2330}
2331
John McCall9776e432011-10-06 23:25:11 +00002332/// Check the semantics of a C-style cast operation, in C.
2333void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002334 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002335
John McCall4124c492011-10-17 18:40:02 +00002336 // C-style casts can resolve __unknown_any types.
2337 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2338 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2339 SrcExpr.get(), Kind,
2340 ValueKind, BasePath);
2341 return;
2342 }
John McCall9776e432011-10-06 23:25:11 +00002343
2344 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2345 // type needs to be scalar.
2346 if (DestType->isVoidType()) {
2347 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002348 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002349 if (SrcExpr.isInvalid())
2350 return;
2351
2352 // Cast to void allows any expr type.
2353 Kind = CK_ToVoid;
2354 return;
2355 }
2356
George Burgess IV5f21c712015-10-12 19:57:04 +00002357 // Overloads are allowed with C extensions, so we need to support them.
2358 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2359 DeclAccessPair DAP;
2360 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2361 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2362 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2363 else
2364 return;
2365 assert(SrcExpr.isUsable());
2366 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002367 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002368 if (SrcExpr.isInvalid())
2369 return;
2370 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002371
John McCall4124c492011-10-17 18:40:02 +00002372 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002373
Joey Gouly8fc32f02014-01-14 12:47:29 +00002374 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2375 // address space B is illegal.
2376 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2377 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002378 const PointerType *DestPtr = DestType->getAs<PointerType>();
2379 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002380 Self.Diag(OpRange.getBegin(),
2381 diag::err_typecheck_incompatible_address_space)
2382 << SrcType << DestType << Sema::AA_Casting
2383 << SrcExpr.get()->getSourceRange();
2384 SrcExpr = ExprError();
2385 return;
2386 }
2387 }
2388
John McCall9776e432011-10-06 23:25:11 +00002389 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2390 diag::err_typecheck_cast_to_incomplete)) {
2391 SrcExpr = ExprError();
2392 return;
2393 }
2394
2395 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2396 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2397
2398 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2399 // GCC struct/union extension: allow cast to self.
2400 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2401 << DestType << SrcExpr.get()->getSourceRange();
2402 Kind = CK_NoOp;
2403 return;
2404 }
2405
2406 // GCC's cast to union extension.
2407 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2408 RecordDecl *RD = DestRecordTy->getDecl();
2409 RecordDecl::field_iterator Field, FieldEnd;
2410 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2411 Field != FieldEnd; ++Field) {
2412 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2413 !Field->isUnnamedBitfield()) {
2414 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2415 << SrcExpr.get()->getSourceRange();
2416 break;
2417 }
2418 }
2419 if (Field == FieldEnd) {
2420 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2421 << SrcType << SrcExpr.get()->getSourceRange();
2422 SrcExpr = ExprError();
2423 return;
2424 }
2425 Kind = CK_ToUnion;
2426 return;
2427 }
2428
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002429 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2430 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2431 llvm::APSInt CastInt;
2432 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2433 if (0 == CastInt) {
2434 Kind = CK_ZeroToOCLEvent;
2435 return;
2436 }
2437 Self.Diag(OpRange.getBegin(),
2438 diag::error_opencl_cast_non_zero_to_event_t)
2439 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2440 SrcExpr = ExprError();
2441 return;
2442 }
2443 }
2444
John McCall9776e432011-10-06 23:25:11 +00002445 // Reject any other conversions to non-scalar types.
2446 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2447 << DestType << SrcExpr.get()->getSourceRange();
2448 SrcExpr = ExprError();
2449 return;
2450 }
2451
2452 // The type we're casting to is known to be a scalar or vector.
2453
2454 // Require the operand to be a scalar or vector.
2455 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2456 Self.Diag(SrcExpr.get()->getExprLoc(),
2457 diag::err_typecheck_expect_scalar_operand)
2458 << SrcType << SrcExpr.get()->getSourceRange();
2459 SrcExpr = ExprError();
2460 return;
2461 }
2462
2463 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002464 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002465 return;
2466 }
2467
2468 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2469 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2470 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2471 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002472 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002473 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2474 SrcExpr = ExprError();
2475 }
2476 return;
2477 }
2478
2479 if (SrcType->isVectorType()) {
2480 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2481 SrcExpr = ExprError();
2482 return;
2483 }
2484
2485 // The source and target types are both scalars, i.e.
2486 // - arithmetic types (fundamental, enum, and complex)
2487 // - all kinds of pointers
2488 // Note that member pointers were filtered out with C++, above.
2489
2490 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2491 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2492 SrcExpr = ExprError();
2493 return;
2494 }
2495
2496 // If either type is a pointer, the other type has to be either an
2497 // integer or a pointer.
2498 if (!DestType->isArithmeticType()) {
2499 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2500 Self.Diag(SrcExpr.get()->getExprLoc(),
2501 diag::err_cast_pointer_from_non_pointer_int)
2502 << SrcType << SrcExpr.get()->getSourceRange();
2503 SrcExpr = ExprError();
2504 return;
2505 }
David Blaikie282ad872012-10-16 18:53:14 +00002506 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2507 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002508 } else if (!SrcType->isArithmeticType()) {
2509 if (!DestType->isIntegralType(Self.Context) &&
2510 DestType->isArithmeticType()) {
2511 Self.Diag(SrcExpr.get()->getLocStart(),
2512 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002513 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002514 SrcExpr = ExprError();
2515 return;
2516 }
2517 }
2518
Joey Goulydd7f4562013-01-23 11:56:20 +00002519 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2520 if (DestType->isHalfType()) {
2521 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2522 << DestType << SrcExpr.get()->getSourceRange();
2523 SrcExpr = ExprError();
2524 return;
2525 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002526 }
2527
John McCall9776e432011-10-06 23:25:11 +00002528 // ARC imposes extra restrictions on casts.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002529 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCall9776e432011-10-06 23:25:11 +00002530 checkObjCARCConversion(Sema::CCK_CStyleCast);
2531 if (SrcExpr.isInvalid())
2532 return;
2533
2534 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2535 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2536 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2537 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2538 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2539 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2540 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2541 Self.Diag(SrcExpr.get()->getLocStart(),
2542 diag::err_typecheck_incompatible_ownership)
2543 << SrcType << DestType << Sema::AA_Casting
2544 << SrcExpr.get()->getSourceRange();
2545 return;
2546 }
2547 }
2548 }
2549 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2550 Self.Diag(SrcExpr.get()->getLocStart(),
2551 diag::err_arc_convesion_of_weak_unavailable)
2552 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2553 SrcExpr = ExprError();
2554 return;
2555 }
2556 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002557
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002558 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002559 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002560 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002561 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2562 if (SrcExpr.isInvalid())
2563 return;
2564
2565 if (Kind == CK_BitCast)
2566 checkCastAlign();
Roman Divackyd5178012014-11-21 21:03:10 +00002567
2568 // -Wcast-qual
2569 QualType TheOffendingSrcType, TheOffendingDestType;
2570 Qualifiers CastAwayQualifiers;
2571 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
2572 CastsAwayConstness(Self, SrcType, DestType, true, false,
2573 &TheOffendingSrcType, &TheOffendingDestType,
2574 &CastAwayQualifiers)) {
2575 int qualifiers = -1;
2576 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2577 qualifiers = 0;
2578 } else if (CastAwayQualifiers.hasConst()) {
2579 qualifiers = 1;
2580 } else if (CastAwayQualifiers.hasVolatile()) {
2581 qualifiers = 2;
2582 }
2583 // This is a variant of int **x; const int **y = (const int **)x;
2584 if (qualifiers == -1)
2585 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
2586 SrcType << DestType;
2587 else
2588 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
2589 TheOffendingSrcType << TheOffendingDestType << qualifiers;
2590 }
John McCall9776e432011-10-06 23:25:11 +00002591}
2592
2593ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2594 TypeSourceInfo *CastTypeInfo,
2595 SourceLocation RPLoc,
2596 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002597 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2598 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2599 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2600
David Blaikiebbafb8a2012-03-11 07:00:24 +00002601 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002602 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2603 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002604 } else {
2605 Op.CheckCStyleCast();
2606 }
2607
John McCallb50451a2011-10-05 07:41:44 +00002608 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002609 return ExprError();
2610
John McCall4124c492011-10-17 18:40:02 +00002611 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002612 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002613 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002614}
2615
2616ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2617 SourceLocation LPLoc,
2618 Expr *CastExpr,
2619 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002620 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb50451a2011-10-05 07:41:44 +00002621 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2622 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2623 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2624
Sebastian Redl2b80af42012-02-13 19:55:43 +00002625 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002626 if (Op.SrcExpr.isInvalid())
2627 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002628
2629 auto *SubExpr = Op.SrcExpr.get();
2630 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2631 SubExpr = BindExpr->getSubExpr();
2632 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002633 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002634
John McCall4124c492011-10-17 18:40:02 +00002635 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002636 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002637 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002638}