blob: ae5436cf415c47f92a9d204fb990ea6454864b0b [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000027#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000028using namespace clang;
29
Douglas Gregore81f58e2010-11-08 03:40:48 +000030
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Sebastian Redl9f831db2009-07-25 15:41:38 +000032enum TryCastResult {
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
35 TC_Failed ///< The cast method is appropriate, but failed. A
36 ///< diagnostic has been emitted.
37};
38
39enum CastType {
40 CT_Const, ///< const_cast
41 CT_Static, ///< static_cast
42 CT_Reinterpret, ///< reinterpret_cast
43 CT_Dynamic, ///< dynamic_cast
44 CT_CStyle, ///< (Type)expr
45 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000046};
47
John McCallb50451a2011-10-05 07:41:44 +000048namespace {
49 struct CastOperation {
50 CastOperation(Sema &S, QualType destType, ExprResult src)
51 : Self(S), SrcExpr(src), DestType(destType),
52 ResultType(destType.getNonLValueExprType(S.Context)),
53 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000054 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000055
56 if (const BuiltinType *placeholder =
57 src.get()->getType()->getAsPlaceholderType()) {
58 PlaceholderKind = placeholder->getKind();
59 } else {
60 PlaceholderKind = (BuiltinType::Kind) 0;
61 }
62 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000063
John McCallb50451a2011-10-05 07:41:44 +000064 Sema &Self;
65 ExprResult SrcExpr;
66 QualType DestType;
67 QualType ResultType;
68 ExprValueKind ValueKind;
69 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000070 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000071 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000072 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000073
John McCallb50451a2011-10-05 07:41:44 +000074 SourceRange OpRange;
75 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000076
John McCall9776e432011-10-06 23:25:11 +000077 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000078 void CheckConstCast();
79 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000080 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000081 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000082 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000083 void CheckCStyleCast();
84
John McCall4124c492011-10-17 18:40:02 +000085 /// Complete an apparently-successful cast operation that yields
86 /// the given expression.
87 ExprResult complete(CastExpr *castExpr) {
88 // If this is an unbridged cast, wrap the result in an implicit
89 // cast that yields the unbridged-cast placeholder type.
90 if (IsARCUnbridgedCast) {
91 castExpr = ImplicitCastExpr::Create(Self.Context,
92 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000093 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +000094 castExpr->getValueKind());
95 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000096 return castExpr;
John McCall4124c492011-10-17 18:40:02 +000097 }
98
John McCall9776e432011-10-06 23:25:11 +000099 // Internal convenience methods.
100
101 /// Try to handle the given placeholder expression kind. Return
102 /// true if the source expression has the appropriate placeholder
103 /// kind. A placeholder can only be claimed once.
104 bool claimPlaceholder(BuiltinType::Kind K) {
105 if (PlaceholderKind != K) return false;
106
107 PlaceholderKind = (BuiltinType::Kind) 0;
108 return true;
109 }
110
111 bool isPlaceholder() const {
112 return PlaceholderKind != 0;
113 }
114 bool isPlaceholder(BuiltinType::Kind K) const {
115 return PlaceholderKind == K;
116 }
John McCallb50451a2011-10-05 07:41:44 +0000117
118 void checkCastAlign() {
119 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
120 }
121
122 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000123 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall4124c492011-10-17 18:40:02 +0000124
John McCallb50451a2011-10-05 07:41:44 +0000125 Expr *src = SrcExpr.get();
John McCall4124c492011-10-17 18:40:02 +0000126 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127 Sema::ACR_unbridged)
128 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000129 SrcExpr = src;
130 }
John McCall9776e432011-10-06 23:25:11 +0000131
132 /// Check for and handle non-overload placeholder expressions.
133 void checkNonOverloadPlaceholders() {
134 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
135 return;
136
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000137 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000138 if (SrcExpr.isInvalid())
139 return;
140 PlaceholderKind = (BuiltinType::Kind) 0;
141 }
John McCallb50451a2011-10-05 07:41:44 +0000142 };
143}
Sebastian Redl842ef522008-11-08 13:00:26 +0000144
John McCall31168b02011-06-15 23:02:42 +0000145static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
146 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000147
148// The Try functions attempt a specific way of casting. If they succeed, they
149// return TC_Success. If their way of casting is not appropriate for the given
150// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
151// to emit if no other way succeeds. If their way of casting is appropriate but
152// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
153// they emit a specialized diagnostic.
154// All diagnostics returned by these functions must expect the same three
155// arguments:
156// %0: Cast Type (a value from the CastType enumeration)
157// %1: Source Type
158// %2: Destination Type
159static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000160 QualType DestType, bool CStyle,
161 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000162 CXXCastPath &BasePath,
163 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000164static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000165 QualType DestType, bool CStyle,
166 const SourceRange &OpRange,
167 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000168 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000169 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000170static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
171 QualType DestType, bool CStyle,
172 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000173 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000174 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000175 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000176static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
177 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000178 const SourceRange &OpRange,
179 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000180 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000181 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000182 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000183static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000184 QualType SrcType,
185 QualType DestType,bool CStyle,
186 const SourceRange &OpRange,
187 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000188 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000189 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000190
John Wiegley01296292011-04-08 18:41:53 +0000191static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000192 QualType DestType,
193 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000194 const SourceRange &OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000195 unsigned &msg, CastKind &Kind,
196 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000197static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000198 QualType DestType,
199 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000200 const SourceRange &OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000201 unsigned &msg, CastKind &Kind,
202 CXXCastPath &BasePath,
203 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000204static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
205 QualType DestType, bool CStyle,
206 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000207static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000208 QualType DestType, bool CStyle,
209 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000210 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000211 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000212
Douglas Gregorb491ed32011-02-19 21:32:49 +0000213
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000214/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000215ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000216Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000217 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000218 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000219 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000220 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000221
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000222 assert(!D.isInvalidType());
223
224 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
225 if (D.isInvalidType())
226 return ExprError();
227
David Blaikiebbafb8a2012-03-11 07:00:24 +0000228 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000229 // Check that there are no default arguments (C++ only).
230 CheckExtraCXXDefaultArguments(D);
231 }
232
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000233 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000234 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
235 SourceRange(LParenLoc, RParenLoc));
236}
237
John McCalldadc5752010-08-24 06:29:42 +0000238ExprResult
John McCalld377e042010-01-15 19:13:16 +0000239Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000240 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000241 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000242 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000243 QualType DestType = DestTInfo->getType();
244
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000245 // If the type is dependent, we won't do the semantic analysis now.
246 // FIXME: should we check this in a more fine-grained manner?
Eli Friedman71271082013-09-19 01:12:33 +0000247 bool TypeDependent = DestType->isDependentType() ||
248 Ex.get()->isTypeDependent() ||
249 Ex.get()->isValueDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000250
John McCallb50451a2011-10-05 07:41:44 +0000251 CastOperation Op(*this, DestType, E);
252 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
253 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000254
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000255 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000256 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000257
258 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000259 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000260 Op.CheckConstCast();
261 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000262 return ExprError();
263 }
John McCall4124c492011-10-17 18:40:02 +0000264 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000265 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000266 OpLoc, Parens.getEnd(),
267 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000268
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000269 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000270 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000271 Op.CheckDynamicCast();
272 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000273 return ExprError();
274 }
John McCall4124c492011-10-17 18:40:02 +0000275 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000276 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000277 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000278 OpLoc, Parens.getEnd(),
279 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000280 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000281 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000282 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000283 Op.CheckReinterpretCast();
284 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000285 return ExprError();
286 }
John McCall4124c492011-10-17 18:40:02 +0000287 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000288 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000289 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000290 Parens.getEnd(),
291 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000292 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000293 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000294 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000295 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000296 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000297 return ExprError();
298 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000299
John McCall4124c492011-10-17 18:40:02 +0000300 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000301 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000302 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000303 OpLoc, Parens.getEnd(),
304 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000305 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000306 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000307}
308
John McCall909acf82011-02-14 18:34:10 +0000309/// Try to diagnose a failed overloaded cast. Returns true if
310/// diagnostics were emitted.
311static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
312 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000313 QualType destType,
314 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000315 switch (CT) {
316 // These cast kinds don't consider user-defined conversions.
317 case CT_Const:
318 case CT_Reinterpret:
319 case CT_Dynamic:
320 return false;
321
322 // These do.
323 case CT_Static:
324 case CT_CStyle:
325 case CT_Functional:
326 break;
327 }
328
329 QualType srcType = src->getType();
330 if (!destType->isRecordType() && !srcType->isRecordType())
331 return false;
332
333 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
334 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000335 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000336 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000337 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000338 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000339 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000340 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000341
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000342 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000343 switch (sequence.getFailureKind()) {
344 default: return false;
345
346 case InitializationSequence::FK_ConstructorOverloadFailed:
347 case InitializationSequence::FK_UserConversionOverloadFailed:
348 break;
349 }
350
351 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
352
353 unsigned msg = 0;
354 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
355
356 switch (sequence.getFailedOverloadResult()) {
357 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000358 case OR_No_Viable_Function:
359 if (candidates.empty())
360 msg = diag::err_ovl_no_conversion_in_cast;
361 else
362 msg = diag::err_ovl_no_viable_conversion_in_cast;
363 howManyCandidates = OCD_AllCandidates;
364 break;
365
366 case OR_Ambiguous:
367 msg = diag::err_ovl_ambiguous_conversion_in_cast;
368 howManyCandidates = OCD_ViableCandidates;
369 break;
370
371 case OR_Deleted:
372 msg = diag::err_ovl_deleted_conversion_in_cast;
373 howManyCandidates = OCD_ViableCandidates;
374 break;
375 }
376
377 S.Diag(range.getBegin(), msg)
378 << CT << srcType << destType
379 << range << src->getSourceRange();
380
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000381 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000382
383 return true;
384}
385
386/// Diagnose a failed cast.
387static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000388 SourceRange opRange, Expr *src, QualType destType,
389 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000390 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000391 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
392 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000393 return;
394
395 S.Diag(opRange.getBegin(), msg) << castType
396 << src->getType() << destType << opRange << src->getSourceRange();
397}
398
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000399/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
400/// this removes one level of indirection from both types, provided that they're
401/// the same kind of pointer (plain or to-member). Unlike the Sema function,
402/// this one doesn't care if the two pointers-to-member don't point into the
403/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000404static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000405 const PointerType *T1PtrType = T1->getAs<PointerType>(),
406 *T2PtrType = T2->getAs<PointerType>();
407 if (T1PtrType && T2PtrType) {
408 T1 = T1PtrType->getPointeeType();
409 T2 = T2PtrType->getPointeeType();
410 return true;
411 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000412 const ObjCObjectPointerType *T1ObjCPtrType =
413 T1->getAs<ObjCObjectPointerType>(),
414 *T2ObjCPtrType =
415 T2->getAs<ObjCObjectPointerType>();
416 if (T1ObjCPtrType) {
417 if (T2ObjCPtrType) {
418 T1 = T1ObjCPtrType->getPointeeType();
419 T2 = T2ObjCPtrType->getPointeeType();
420 return true;
421 }
422 else if (T2PtrType) {
423 T1 = T1ObjCPtrType->getPointeeType();
424 T2 = T2PtrType->getPointeeType();
425 return true;
426 }
427 }
428 else if (T2ObjCPtrType) {
429 if (T1PtrType) {
430 T2 = T2ObjCPtrType->getPointeeType();
431 T1 = T1PtrType->getPointeeType();
432 return true;
433 }
434 }
435
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000436 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
437 *T2MPType = T2->getAs<MemberPointerType>();
438 if (T1MPType && T2MPType) {
439 T1 = T1MPType->getPointeeType();
440 T2 = T2MPType->getPointeeType();
441 return true;
442 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000443
444 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
445 *T2BPType = T2->getAs<BlockPointerType>();
446 if (T1BPType && T2BPType) {
447 T1 = T1BPType->getPointeeType();
448 T2 = T2BPType->getPointeeType();
449 return true;
450 }
451
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000452 return false;
453}
454
Sebastian Redla5a77a62009-01-27 23:18:31 +0000455/// CastsAwayConstness - Check if the pointer conversion from SrcType to
456/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
457/// the cast checkers. Both arguments must denote pointer (possibly to member)
458/// types.
John McCall31168b02011-06-15 23:02:42 +0000459///
460/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
461///
462/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000463static bool
John McCall31168b02011-06-15 23:02:42 +0000464CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
465 bool CheckCVR, bool CheckObjCLifetime) {
466 // If the only checking we care about is for Objective-C lifetime qualifiers,
467 // and we're not in ARC mode, there's nothing to check.
468 if (!CheckCVR && CheckObjCLifetime &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000469 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000470 return false;
471
Sebastian Redla5a77a62009-01-27 23:18:31 +0000472 // Casting away constness is defined in C++ 5.2.11p8 with reference to
473 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
474 // the rules are non-trivial. So first we construct Tcv *...cv* as described
475 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000476 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
477 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000478 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000479 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
480 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000481 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000482
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000483 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
484 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000485 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000486
Douglas Gregorb472e932011-04-15 17:59:54 +0000487 // Find the qualifiers. We only care about cvr-qualifiers for the
488 // purpose of this check, because other qualifiers (address spaces,
489 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000490 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000491 // Determine the relevant qualifiers at this level.
492 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000493 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000494 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000495
496 Qualifiers RetainedSrcQuals, RetainedDestQuals;
497 if (CheckCVR) {
498 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
499 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
500 }
501
502 if (CheckObjCLifetime &&
503 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
504 return true;
505
506 cv1.push_back(RetainedSrcQuals);
507 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000508 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000509 if (cv1.empty())
510 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000511
512 // Construct void pointers with those qualifiers (in reverse order of
513 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000514 QualType SrcConstruct = Self.Context.VoidTy;
515 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000516 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000517 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
518 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000519 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000520 SrcConstruct
521 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
522 DestConstruct
523 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000524 }
525
526 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000527 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000528 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000529 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
530 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000531}
532
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000533/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
534/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
535/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000536void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000537 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000538 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000539 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000540 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000541 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
542 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000543
John McCallb50451a2011-10-05 07:41:44 +0000544 QualType OrigSrcType = SrcExpr.get()->getType();
545 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000546
547 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
548 // or "pointer to cv void".
549
550 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000551 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000552 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000553 if (DestPointer) {
554 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000555 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000556 DestPointee = DestReference->getPointeeType();
557 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000558 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000559 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000560 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000561 return;
562 }
563
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000564 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000565 if (DestPointee->isVoidType()) {
566 assert(DestPointer && "Reference to void is not possible");
567 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000568 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000569 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000570 DestRange)) {
571 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000572 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000573 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000574 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000575 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000576 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000577 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000578 return;
579 }
580
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000581 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
582 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000583 // an lvalue of a complete class type, [...]. If T is an rvalue reference
584 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000585 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000586 QualType SrcPointee;
587 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000588 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000589 SrcPointee = SrcPointer->getPointeeType();
590 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000591 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000592 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000593 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000594 return;
595 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000596 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000597 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000598 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000599 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000600 }
601 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000602 } else {
Richard Smith11330852014-07-08 17:25:14 +0000603 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
604 // to materialize the prvalue before we bind the reference to it.
605 if (SrcExpr.get()->isRValue())
606 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
607 SrcType, SrcExpr.get(), /*IsLValueReference*/false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000608 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000609 }
610
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000611 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000612 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000613 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000614 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000615 SrcExpr.get())) {
616 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000617 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000618 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000619 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000620 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000621 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000622 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000623 return;
624 }
625
626 assert((DestPointer || DestReference) &&
627 "Bad destination non-ptr/ref slipped through.");
628 assert((DestRecord || DestPointee->isVoidType()) &&
629 "Bad destination pointee slipped through.");
630 assert(SrcRecord && "Bad source pointee slipped through.");
631
632 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
633 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000634 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000635 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000636 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000637 return;
638 }
639
640 // C++ 5.2.7p3: If the type of v is the same as the required result type,
641 // [except for cv].
642 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000643 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000644 return;
645 }
646
647 // C++ 5.2.7p5
648 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000649 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000650 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
651 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000652 &BasePath)) {
653 SrcExpr = ExprError();
654 return;
655 }
Richard Smith11330852014-07-08 17:25:14 +0000656
John McCalle3027922010-08-25 11:45:40 +0000657 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000658
659 // If we are casting to or through a virtual base class, we need a
660 // vtable.
661 if (Self.BasePathInvolvesVirtualBase(BasePath))
662 Self.MarkVTableUsed(OpRange.getBegin(),
663 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000664 return;
665 }
666
667 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000668 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000669 assert(SrcDecl && "Definition missing");
670 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000671 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000672 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000673 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000674 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000675 Self.MarkVTableUsed(OpRange.getBegin(),
676 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000677
Eli Friedman3ce27102013-09-24 23:21:41 +0000678 // dynamic_cast is not available with -fno-rtti.
679 // As an exception, dynamic_cast to void* is available because it doesn't
680 // use RTTI.
681 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000682 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
683 SrcExpr = ExprError();
684 return;
685 }
686
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000687 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000688 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000689}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000690
691/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
692/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
693/// like this:
694/// const char *str = "literal";
695/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000696void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000697 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000698 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000699 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000700 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000701 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
702 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000703
704 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000705 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000706 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000707 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000708 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000709 SrcExpr = ExprError();
710 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000711}
712
John McCallcda80832013-03-22 02:58:14 +0000713/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
714/// or downcast between respective pointers or references.
715static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
716 QualType DestType,
717 SourceRange OpRange) {
718 QualType SrcType = SrcExpr->getType();
719 // When casting from pointer or reference, get pointee type; use original
720 // type otherwise.
721 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
722 const CXXRecordDecl *SrcRD =
723 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
724
John McCallf2abe192013-03-27 00:03:48 +0000725 // Examining subobjects for records is only possible if the complete and
726 // valid definition is available. Also, template instantiation is not
727 // allowed here.
728 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000729 return;
730
731 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
732
John McCallf2abe192013-03-27 00:03:48 +0000733 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000734 return;
735
736 enum {
737 ReinterpretUpcast,
738 ReinterpretDowncast
739 } ReinterpretKind;
740
741 CXXBasePaths BasePaths;
742
743 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
744 ReinterpretKind = ReinterpretUpcast;
745 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
746 ReinterpretKind = ReinterpretDowncast;
747 else
748 return;
749
750 bool VirtualBase = true;
751 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000752 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000753 E = BasePaths.end();
754 I != E; ++I) {
755 const CXXBasePath &Path = *I;
756 CharUnits Offset = CharUnits::Zero();
757 bool IsVirtual = false;
758 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
759 IElem != EElem; ++IElem) {
760 IsVirtual = IElem->Base->isVirtual();
761 if (IsVirtual)
762 break;
763 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
764 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000765 // Don't check if any base has invalid declaration or has no definition
766 // since it has no layout info.
767 const CXXRecordDecl *Class = IElem->Class,
768 *ClassDefinition = Class->getDefinition();
769 if (Class->isInvalidDecl() || !ClassDefinition ||
770 !ClassDefinition->isCompleteDefinition())
771 return;
772
John McCallcda80832013-03-22 02:58:14 +0000773 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000774 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000775 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
776 }
777 if (!IsVirtual) {
778 // Don't warn if any path is a non-virtually derived base at offset zero.
779 if (Offset.isZero())
780 return;
781 // Offset makes sense only for non-virtual bases.
782 else
783 NonZeroOffset = true;
784 }
785 VirtualBase = VirtualBase && IsVirtual;
786 }
787
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000788 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000789 assert((VirtualBase || NonZeroOffset) &&
790 "Should have returned if has non-virtual base with zero offset");
791
792 QualType BaseType =
793 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
794 QualType DerivedType =
795 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
796
Jordan Rose04a94d12013-03-28 19:09:40 +0000797 SourceLocation BeginLoc = OpRange.getBegin();
798 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000799 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000800 << OpRange;
801 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000802 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000803 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000804}
805
Sebastian Redl9f831db2009-07-25 15:41:38 +0000806/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
807/// valid.
808/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
809/// like this:
810/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000811void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000812 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000813 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000814 else
815 checkNonOverloadPlaceholders();
816 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
817 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000818
819 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000820 TryCastResult tcr =
821 TryReinterpretCast(Self, SrcExpr, DestType,
822 /*CStyle*/false, OpRange, msg, Kind);
823 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000824 {
John Wiegley01296292011-04-08 18:41:53 +0000825 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
826 return;
827 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000828 //FIXME: &f<int>; is overloaded and resolvable
829 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000830 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000831 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000832 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000833
John McCall909acf82011-02-14 18:34:10 +0000834 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000835 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
836 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000837 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000838 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000839 } else if (tcr == TC_Success) {
840 if (Self.getLangOpts().ObjCAutoRefCount)
841 checkObjCARCConversion(Sema::CCK_OtherCast);
842 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000843 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000844}
845
846
847/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
848/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
849/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000850void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000851 if (isPlaceholder()) {
852 checkNonOverloadPlaceholders();
853 if (SrcExpr.isInvalid())
854 return;
855 }
856
Sebastian Redl9f831db2009-07-25 15:41:38 +0000857 // This test is outside everything else because it's the only case where
858 // a non-lvalue-reference target type does not lead to decay.
859 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000860 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000861 Kind = CK_ToVoid;
862
863 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000864 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000865 false, // Decay Function to ptr
866 true, // Complain
867 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000868 if (SrcExpr.isInvalid())
869 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000870 }
John McCall9776e432011-10-06 23:25:11 +0000871
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000872 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000873 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000874 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000875
John McCall50a2c2c2011-10-11 23:14:30 +0000876 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
877 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000878 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +0000879 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
880 return;
881 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000882
883 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000884 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000885 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000886 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000887 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000888 if (SrcExpr.isInvalid())
889 return;
890 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
891 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000892 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000893 << oe->getName() << DestType << OpRange
894 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000895 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000896 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000897 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
898 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000899 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000900 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000901 } else if (tcr == TC_Success) {
902 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000903 checkCastAlign();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000904 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smith507840d2011-11-29 22:48:16 +0000905 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000906 } else if (Kind == CK_BitCast) {
907 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000908 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000909}
910
911/// TryStaticCast - Check if a static cast can be performed, and do so if
912/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
913/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000914static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000915 QualType DestType,
916 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000917 const SourceRange &OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000918 CastKind &Kind, CXXCastPath &BasePath,
919 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000920 // Determine whether we have the semantics of a C-style cast.
921 bool CStyle
922 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
923
Sebastian Redl9f831db2009-07-25 15:41:38 +0000924 // The order the tests is not entirely arbitrary. There is one conversion
925 // that can be handled in two different ways. Given:
926 // struct A {};
927 // struct B : public A {
928 // B(); B(const A&);
929 // };
930 // const A &a = B();
931 // the cast static_cast<const B&>(a) could be seen as either a static
932 // reference downcast, or an explicit invocation of the user-defined
933 // conversion using B's conversion constructor.
934 // DR 427 specifies that the downcast is to be applied here.
935
936 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
937 // Done outside this function.
938
939 TryCastResult tcr;
940
941 // C++ 5.2.9p5, reference downcast.
942 // See the function for details.
943 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +0000944 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
945 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000946 if (tcr != TC_NotApplicable)
947 return tcr;
948
Douglas Gregor465184a2011-01-22 00:06:57 +0000949 // C++0x [expr.static.cast]p3:
950 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
951 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redld74dd492012-02-12 18:41:05 +0000952 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
953 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000954 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000955 return tcr;
956
957 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
958 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000959 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000960 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000961 if (SrcExpr.isInvalid())
962 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000963 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000964 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000965
Sebastian Redl9f831db2009-07-25 15:41:38 +0000966 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
967 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
968 // conversions, subject to further restrictions.
969 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
970 // of qualification conversions impossible.
971 // In the CStyle case, the earlier attempt to const_cast should have taken
972 // care of reverse qualification conversions.
973
John Wiegley01296292011-04-08 18:41:53 +0000974 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000975
Douglas Gregor0bf31402010-10-08 23:50:27 +0000976 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000977 // converted to an integral type. [...] A value of a scoped enumeration type
978 // can also be explicitly converted to a floating-point type [...].
979 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
980 if (Enum->getDecl()->isScoped()) {
981 if (DestType->isBooleanType()) {
982 Kind = CK_IntegralToBoolean;
983 return TC_Success;
984 } else if (DestType->isIntegralType(Self.Context)) {
985 Kind = CK_IntegralCast;
986 return TC_Success;
987 } else if (DestType->isRealFloatingType()) {
988 Kind = CK_IntegralToFloating;
989 return TC_Success;
990 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000991 }
992 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000993
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 // Reverse integral promotion/conversion. All such conversions are themselves
995 // again integral promotions or conversions and are thus already handled by
996 // p2 (TryDirectInitialization above).
997 // (Note: any data loss warnings should be suppressed.)
998 // The exception is the reverse of enum->integer, i.e. integer->enum (and
999 // enum->enum). See also C++ 5.2.9p7.
1000 // The same goes for reverse floating point promotion/conversion and
1001 // floating-integral conversions. Again, only floating->enum is relevant.
1002 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001003 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001004 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001005 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001006 } else if (SrcType->isRealFloatingType()) {
1007 Kind = CK_FloatingToIntegral;
1008 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001009 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001010 }
1011
1012 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1013 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001014 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001015 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001016 if (tcr != TC_NotApplicable)
1017 return tcr;
1018
1019 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1020 // conversion. C++ 5.2.9p9 has additional information.
1021 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001022 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001023 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001024 if (tcr != TC_NotApplicable)
1025 return tcr;
1026
1027 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1028 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1029 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001030 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001031 QualType SrcPointee = SrcPointer->getPointeeType();
1032 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001033 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001034 QualType DestPointee = DestPointer->getPointeeType();
1035 if (DestPointee->isIncompleteOrObjectType()) {
1036 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001037 // to a qualifier violation. Note that we permit Objective-C lifetime
1038 // and GC qualifier mismatches here.
1039 if (!CStyle) {
1040 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1041 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1042 DestPointeeQuals.removeObjCGCAttr();
1043 DestPointeeQuals.removeObjCLifetime();
1044 SrcPointeeQuals.removeObjCGCAttr();
1045 SrcPointeeQuals.removeObjCLifetime();
1046 if (DestPointeeQuals != SrcPointeeQuals &&
1047 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1048 msg = diag::err_bad_cxx_cast_qualifiers_away;
1049 return TC_Failed;
1050 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001051 }
John McCalle3027922010-08-25 11:45:40 +00001052 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001053 return TC_Success;
1054 }
1055 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001056 else if (DestType->isObjCObjectPointerType()) {
1057 // allow both c-style cast and static_cast of objective-c pointers as
1058 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001059 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001060 return TC_Success;
1061 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001062 else if (CStyle && DestType->isBlockPointerType()) {
1063 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001064 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001065 return TC_Success;
1066 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001067 }
1068 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001069 // Allow arbitray objective-c pointer conversion with static casts.
1070 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001071 DestType->isObjCObjectPointerType()) {
1072 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001073 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001074 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001075 // Allow ns-pointer to cf-pointer conversion in either direction
1076 // with static casts.
1077 if (!CStyle &&
1078 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1079 return TC_Success;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001080
Sebastian Redl9f831db2009-07-25 15:41:38 +00001081 // We tried everything. Everything! Nothing works! :-(
1082 return TC_NotApplicable;
1083}
1084
1085/// Tests whether a conversion according to N2844 is valid.
1086TryCastResult
1087TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +00001088 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1089 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +00001090 // C++0x [expr.static.cast]p3:
1091 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1092 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001093 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001094 if (!R)
1095 return TC_NotApplicable;
1096
Douglas Gregor465184a2011-01-22 00:06:57 +00001097 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001098 return TC_NotApplicable;
1099
1100 // Because we try the reference downcast before this function, from now on
1101 // this is the only cast possibility, so we issue an error if we fail now.
1102 // FIXME: Should allow casting away constness if CStyle.
1103 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001104 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001105 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001106 QualType FromType = SrcExpr->getType();
1107 QualType ToType = R->getPointeeType();
1108 if (CStyle) {
1109 FromType = FromType.getUnqualifiedType();
1110 ToType = ToType.getUnqualifiedType();
1111 }
1112
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001113 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +00001114 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +00001115 DerivedToBase, ObjCConversion,
1116 ObjCLifetimeConversion)
1117 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001118 msg = diag::err_bad_lvalue_to_rvalue_cast;
1119 return TC_Failed;
1120 }
1121
Douglas Gregorba278e22011-01-25 16:13:26 +00001122 if (DerivedToBase) {
1123 Kind = CK_DerivedToBase;
1124 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1125 /*DetectVirtual=*/true);
1126 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1127 return TC_NotApplicable;
1128
1129 Self.BuildBasePathArray(Paths, BasePath);
1130 } else
1131 Kind = CK_NoOp;
1132
Sebastian Redl9f831db2009-07-25 15:41:38 +00001133 return TC_Success;
1134}
1135
1136/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1137TryCastResult
1138TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1139 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001140 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001141 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001142 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1143 // cast to type "reference to cv2 D", where D is a class derived from B,
1144 // if a valid standard conversion from "pointer to D" to "pointer to B"
1145 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1146 // In addition, DR54 clarifies that the base must be accessible in the
1147 // current context. Although the wording of DR54 only applies to the pointer
1148 // variant of this rule, the intent is clearly for it to apply to the this
1149 // conversion as well.
1150
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001151 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001152 if (!DestReference) {
1153 return TC_NotApplicable;
1154 }
1155 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001156 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001157 // We know the left side is an lvalue reference, so we can suggest a reason.
1158 msg = diag::err_bad_cxx_cast_rvalue;
1159 return TC_NotApplicable;
1160 }
1161
1162 QualType DestPointee = DestReference->getPointeeType();
1163
Richard Smith11330852014-07-08 17:25:14 +00001164 // FIXME: If the source is a prvalue, we should issue a warning (because the
1165 // cast always has undefined behavior), and for AST consistency, we should
1166 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001167 return TryStaticDowncast(Self,
1168 Self.Context.getCanonicalType(SrcExpr->getType()),
1169 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001170 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1171 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001172}
1173
1174/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1175TryCastResult
1176TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001177 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001178 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001179 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001180 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1181 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1182 // is a class derived from B, if a valid standard conversion from "pointer
1183 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1184 // class of D.
1185 // In addition, DR54 clarifies that the base must be accessible in the
1186 // current context.
1187
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001188 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001189 if (!DestPointer) {
1190 return TC_NotApplicable;
1191 }
1192
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001193 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001194 if (!SrcPointer) {
1195 msg = diag::err_bad_static_cast_pointer_nonpointer;
1196 return TC_NotApplicable;
1197 }
1198
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001199 return TryStaticDowncast(Self,
1200 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1201 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001202 CStyle, OpRange, SrcType, DestType, msg, Kind,
1203 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001204}
1205
1206/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1207/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001208/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001209TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001210TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001211 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001212 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001213 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001214 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001215 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1216 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001217 return TC_NotApplicable;
1218
Sebastian Redl9f831db2009-07-25 15:41:38 +00001219 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001220 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001221 return TC_NotApplicable;
1222 }
1223
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001224 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001225 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001226 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1227 return TC_NotApplicable;
1228 }
1229
1230 // Target type does derive from source type. Now we're serious. If an error
1231 // appears now, it's not ignored.
1232 // This may not be entirely in line with the standard. Take for example:
1233 // struct A {};
1234 // struct B : virtual A {
1235 // B(A&);
1236 // };
Mike Stump11289f42009-09-09 15:08:12 +00001237 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001238 // void f()
1239 // {
1240 // (void)static_cast<const B&>(*((A*)0));
1241 // }
1242 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1243 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1244 // However, both GCC and Comeau reject this example, and accepting it would
1245 // mean more complex code if we're to preserve the nice error message.
1246 // FIXME: Being 100% compliant here would be nice to have.
1247
1248 // Must preserve cv, as always, unless we're in C-style mode.
1249 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001250 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001251 return TC_Failed;
1252 }
1253
1254 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1255 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1256 // that it builds the paths in reverse order.
1257 // To sum up: record all paths to the base and build a nice string from
1258 // them. Use it to spice up the error message.
1259 if (!Paths.isRecordingPaths()) {
1260 Paths.clear();
1261 Paths.setRecordingPaths(true);
1262 Self.IsDerivedFrom(DestType, SrcType, Paths);
1263 }
1264 std::string PathDisplayStr;
1265 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001266 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001267 PI != PE; ++PI) {
1268 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1269 // We haven't displayed a path to this particular base
1270 // class subobject yet.
1271 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001272 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1273 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001274 EI != EE; ++EI)
1275 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001276 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001277 }
1278 }
1279
1280 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001281 << QualType(SrcType).getUnqualifiedType()
1282 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001283 << PathDisplayStr << OpRange;
1284 msg = 0;
1285 return TC_Failed;
1286 }
1287
Craig Topperc3ec1492014-05-26 06:22:03 +00001288 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001289 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1290 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1291 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1292 msg = 0;
1293 return TC_Failed;
1294 }
1295
John McCallfe9cf0a2011-02-14 23:21:33 +00001296 if (!CStyle) {
1297 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1298 SrcType, DestType,
1299 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001300 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001301 case Sema::AR_accessible:
1302 case Sema::AR_delayed: // be optimistic
1303 case Sema::AR_dependent: // be optimistic
1304 break;
1305
1306 case Sema::AR_inaccessible:
1307 msg = 0;
1308 return TC_Failed;
1309 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001310 }
1311
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001312 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001313 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001314 return TC_Success;
1315}
1316
1317/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1318/// C++ 5.2.9p9 is valid:
1319///
1320/// An rvalue of type "pointer to member of D of type cv1 T" can be
1321/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1322/// where B is a base class of D [...].
1323///
1324TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001325TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001326 QualType DestType, bool CStyle,
1327 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001328 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001329 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001330 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001331 if (!DestMemPtr)
1332 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001333
1334 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001335 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001336 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001337 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001338 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001339 FoundOverload)) {
1340 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1341 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1342 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1343 WasOverloadedFunction = true;
1344 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001345 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001346
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001347 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001348 if (!SrcMemPtr) {
1349 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1350 return TC_NotApplicable;
1351 }
1352
1353 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001354 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1355 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001356 return TC_NotApplicable;
1357
1358 // B base of D
1359 QualType SrcClass(SrcMemPtr->getClass(), 0);
1360 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001361 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001362 /*DetectVirtual=*/true);
David Majnemerf5b93792014-01-16 12:02:55 +00001363 if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
1364 !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001365 return TC_NotApplicable;
1366 }
1367
1368 // 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 +00001369 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001370 Paths.clear();
1371 Paths.setRecordingPaths(true);
1372 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1373 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001374 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001375 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1376 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1377 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1378 msg = 0;
1379 return TC_Failed;
1380 }
1381
1382 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1383 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1384 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1385 msg = 0;
1386 return TC_Failed;
1387 }
1388
John McCallfe9cf0a2011-02-14 23:21:33 +00001389 if (!CStyle) {
1390 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1391 DestClass, SrcClass,
1392 Paths.front(),
1393 diag::err_upcast_to_inaccessible_base)) {
1394 case Sema::AR_accessible:
1395 case Sema::AR_delayed:
1396 case Sema::AR_dependent:
1397 // Optimistically assume that the delayed and dependent cases
1398 // will work out.
1399 break;
1400
1401 case Sema::AR_inaccessible:
1402 msg = 0;
1403 return TC_Failed;
1404 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001405 }
1406
Douglas Gregorc934bc82010-03-07 23:24:59 +00001407 if (WasOverloadedFunction) {
1408 // Resolve the address of the overloaded function again, this time
1409 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001410 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001411 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001412 true,
1413 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001414 if (!Fn) {
1415 msg = 0;
1416 return TC_Failed;
1417 }
1418
John McCall16df1e52010-03-30 21:47:33 +00001419 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001420 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001421 msg = 0;
1422 return TC_Failed;
1423 }
1424 }
1425
Anders Carlssonb78feca2010-04-24 19:22:20 +00001426 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001427 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001428 return TC_Success;
1429}
1430
1431/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1432/// is valid:
1433///
1434/// An expression e can be explicitly converted to a type T using a
1435/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1436TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001437TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001438 Sema::CheckedConversionKind CCK,
1439 const SourceRange &OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001440 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001441 if (DestType->isRecordType()) {
1442 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001443 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001444 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001445 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001446 msg = 0;
1447 return TC_Failed;
1448 }
David Majnemer763584d2014-02-06 10:59:19 +00001449 } else if (DestType->isMemberPointerType()) {
1450 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1451 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1452 }
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001453 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001454
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001455 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1456 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001457 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001458 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001459 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001460 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001461 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001462 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001463 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001464 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001465
1466 // At this point of CheckStaticCast, if the destination is a reference,
1467 // or the expression is an overload expression this has to work.
1468 // There is no other way that works.
1469 // On the other hand, if we're checking a C-style cast, we've still got
1470 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001471 bool CStyle
1472 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001473 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001474 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001475
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001476 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001477 if (Result.isInvalid()) {
1478 msg = 0;
1479 return TC_Failed;
1480 }
1481
Douglas Gregorb33eed02010-04-16 22:09:46 +00001482 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001483 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001484 else
John McCalle3027922010-08-25 11:45:40 +00001485 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001486
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001487 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001488 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001489}
1490
1491/// TryConstCast - See if a const_cast from source to destination is allowed,
1492/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001493static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1494 QualType DestType, bool CStyle,
1495 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001496 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001497 QualType SrcType = SrcExpr.get()->getType();
1498 bool NeedToMaterializeTemporary = false;
1499
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001500 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001501 // C++11 5.2.11p4:
1502 // if a pointer to T1 can be explicitly converted to the type "pointer to
1503 // T2" using a const_cast, then the following conversions can also be
1504 // made:
1505 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1506 // type T2 using the cast const_cast<T2&>;
1507 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1508 // type T2 using the cast const_cast<T2&&>; and
1509 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1510 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1511
1512 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001513 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1514 // is C-style, static_cast might find a way, so we simply suggest a
1515 // message and tell the parent to keep searching.
1516 msg = diag::err_bad_cxx_cast_rvalue;
1517 return TC_NotApplicable;
1518 }
1519
Richard Smith82c9b512013-06-14 22:27:52 +00001520 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1521 if (!SrcType->isRecordType()) {
1522 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1523 // this is C-style, static_cast can do this.
1524 msg = diag::err_bad_cxx_cast_rvalue;
1525 return TC_NotApplicable;
1526 }
1527
1528 // Materialize the class prvalue so that the const_cast can bind a
1529 // reference to it.
1530 NeedToMaterializeTemporary = true;
1531 }
1532
John McCalld25db7e2013-05-06 21:39:12 +00001533 // It's not completely clear under the standard whether we can
1534 // const_cast bit-field gl-values. Doing so would not be
1535 // intrinsically complicated, but for now, we say no for
1536 // consistency with other compilers and await the word of the
1537 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001538 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001539 msg = diag::err_bad_cxx_cast_bitfield;
1540 return TC_NotApplicable;
1541 }
1542
Sebastian Redl9f831db2009-07-25 15:41:38 +00001543 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1544 SrcType = Self.Context.getPointerType(SrcType);
1545 }
1546
1547 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1548 // the rules for const_cast are the same as those used for pointers.
1549
John McCall0e704f72010-05-18 09:35:29 +00001550 if (!DestType->isPointerType() &&
1551 !DestType->isMemberPointerType() &&
1552 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001553 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1554 // was a reference type, we converted it to a pointer above.
1555 // The status of rvalue references isn't entirely clear, but it looks like
1556 // conversion to them is simply invalid.
1557 // C++ 5.2.11p3: For two pointer types [...]
1558 if (!CStyle)
1559 msg = diag::err_bad_const_cast_dest;
1560 return TC_NotApplicable;
1561 }
1562 if (DestType->isFunctionPointerType() ||
1563 DestType->isMemberFunctionPointerType()) {
1564 // Cannot cast direct function pointers.
1565 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1566 // T is the ultimate pointee of source and target type.
1567 if (!CStyle)
1568 msg = diag::err_bad_const_cast_dest;
1569 return TC_NotApplicable;
1570 }
1571 SrcType = Self.Context.getCanonicalType(SrcType);
1572
1573 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1574 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001575 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1576 // in multi-level pointers may change, but the level count must be the same,
1577 // as must be the final pointee type.
1578 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001579 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001580 Qualifiers SrcQuals, DestQuals;
1581 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1582 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1583
1584 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1585 // the other qualifiers (e.g., address spaces) are identical.
1586 SrcQuals.removeCVRQualifiers();
1587 DestQuals.removeCVRQualifiers();
1588 if (SrcQuals != DestQuals)
1589 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001590 }
1591
1592 // Since we're dealing in canonical types, the remainder must be the same.
1593 if (SrcType != DestType)
1594 return TC_NotApplicable;
1595
Richard Smith82c9b512013-06-14 22:27:52 +00001596 if (NeedToMaterializeTemporary)
1597 // This is a const_cast from a class prvalue to an rvalue reference type.
1598 // Materialize a temporary to store the result of the conversion.
1599 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001600 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001601
Sebastian Redl9f831db2009-07-25 15:41:38 +00001602 return TC_Success;
1603}
1604
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001605// Checks for undefined behavior in reinterpret_cast.
1606// The cases that is checked for is:
1607// *reinterpret_cast<T*>(&a)
1608// reinterpret_cast<T&>(a)
1609// where accessing 'a' as type 'T' will result in undefined behavior.
1610void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1611 bool IsDereference,
1612 SourceRange Range) {
1613 unsigned DiagID = IsDereference ?
1614 diag::warn_pointer_indirection_from_incompatible_type :
1615 diag::warn_undefined_reinterpret_cast;
1616
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001617 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001618 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001619
1620 QualType SrcTy, DestTy;
1621 if (IsDereference) {
1622 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1623 return;
1624 }
1625 SrcTy = SrcType->getPointeeType();
1626 DestTy = DestType->getPointeeType();
1627 } else {
1628 if (!DestType->getAs<ReferenceType>()) {
1629 return;
1630 }
1631 SrcTy = SrcType;
1632 DestTy = DestType->getPointeeType();
1633 }
1634
1635 // Cast is compatible if the types are the same.
1636 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1637 return;
1638 }
1639 // or one of the types is a char or void type
1640 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1641 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1642 return;
1643 }
1644 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001645 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001646 return;
1647 }
1648
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001649 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001650 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1651 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1652 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1653 return;
1654 }
1655 }
1656
1657 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1658}
Douglas Gregor1beec452011-03-12 01:48:56 +00001659
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001660static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1661 QualType DestType) {
1662 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001663 if (Self.Context.hasSameType(SrcType, DestType))
1664 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001665 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1666 if (SrcPtrTy->isObjCSelType()) {
1667 QualType DT = DestType;
1668 if (isa<PointerType>(DestType))
1669 DT = DestType->getPointeeType();
1670 if (!DT.getUnqualifiedType()->isVoidType())
1671 Self.Diag(SrcExpr.get()->getExprLoc(),
1672 diag::warn_cast_pointer_from_sel)
1673 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1674 }
1675}
1676
David Blaikie282ad872012-10-16 18:53:14 +00001677static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1678 const Expr *SrcExpr, QualType DestType,
1679 Sema &Self) {
1680 QualType SrcType = SrcExpr->getType();
1681
1682 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1683 // are not explicit design choices, but consistent with GCC's behavior.
1684 // Feel free to modify them if you've reason/evidence for an alternative.
1685 if (CStyle && SrcType->isIntegralType(Self.Context)
1686 && !SrcType->isBooleanType()
1687 && !SrcType->isEnumeralType()
1688 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001689 && Self.Context.getTypeSize(DestType) >
1690 Self.Context.getTypeSize(SrcType)) {
1691 // Separate between casts to void* and non-void* pointers.
1692 // Some APIs use (abuse) void* for something like a user context,
1693 // and often that value is an integer even if it isn't a pointer itself.
1694 // Having a separate warning flag allows users to control the warning
1695 // for their workflow.
1696 unsigned Diag = DestType->isVoidPointerType() ?
1697 diag::warn_int_to_void_pointer_cast
1698 : diag::warn_int_to_pointer_cast;
1699 Self.Diag(Loc, Diag) << SrcType << DestType;
1700 }
David Blaikie282ad872012-10-16 18:53:14 +00001701}
1702
John Wiegley01296292011-04-08 18:41:53 +00001703static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001704 QualType DestType, bool CStyle,
1705 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001706 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001707 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001708 bool IsLValueCast = false;
1709
Sebastian Redl9f831db2009-07-25 15:41:38 +00001710 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001711 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001712
1713 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001714 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1715 if (SrcType == Self.Context.OverloadTy) {
John McCall50a2c2c2011-10-11 23:14:30 +00001716 // ... unless foo<int> resolves to an lvalue unambiguously.
1717 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1718 // like it?
1719 ExprResult SingleFunctionExpr = SrcExpr;
1720 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1721 SingleFunctionExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001722 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall50a2c2c2011-10-11 23:14:30 +00001723 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001724 SrcExpr = SingleFunctionExpr;
John Wiegley01296292011-04-08 18:41:53 +00001725 SrcType = SrcExpr.get()->getType();
John McCall50a2c2c2011-10-11 23:14:30 +00001726 } else {
Douglas Gregorb491ed32011-02-19 21:32:49 +00001727 return TC_NotApplicable;
John McCall50a2c2c2011-10-11 23:14:30 +00001728 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001729 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001730
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001731 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001732 if (!SrcExpr.get()->isGLValue()) {
1733 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1734 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001735 msg = diag::err_bad_cxx_cast_rvalue;
1736 return TC_NotApplicable;
1737 }
1738
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001739 if (!CStyle) {
1740 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1741 /*isDereference=*/false, OpRange);
1742 }
1743
Sebastian Redl9f831db2009-07-25 15:41:38 +00001744 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1745 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1746 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001747
Craig Topperc3ec1492014-05-26 06:22:03 +00001748 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001749 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001750 case OK_Ordinary:
1751 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001752 case OK_BitField: inappropriate = "bit-field"; break;
1753 case OK_VectorComponent: inappropriate = "vector element"; break;
1754 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001755 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1756 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001757 }
1758 if (inappropriate) {
1759 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1760 << inappropriate << DestType
1761 << OpRange << SrcExpr.get()->getSourceRange();
1762 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001763 return TC_NotApplicable;
1764 }
1765
Sebastian Redl9f831db2009-07-25 15:41:38 +00001766 // This code does this transformation for the checked types.
1767 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1768 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001769
Douglas Gregor51954272010-07-13 23:17:26 +00001770 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001771 }
1772
1773 // Canonicalize source for comparison.
1774 SrcType = Self.Context.getCanonicalType(SrcType);
1775
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001776 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1777 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001778 if (DestMemPtr && SrcMemPtr) {
1779 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1780 // can be explicitly converted to an rvalue of type "pointer to member
1781 // of Y of type T2" if T1 and T2 are both function types or both object
1782 // types.
1783 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1784 SrcMemPtr->getPointeeType()->isFunctionType())
1785 return TC_NotApplicable;
1786
1787 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1788 // constness.
1789 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1790 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001791 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1792 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001793 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001794 return TC_Failed;
1795 }
1796
David Majnemer1cdd96d2014-01-17 09:01:00 +00001797 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1798 // We need to determine the inheritance model that the class will use if
1799 // haven't yet.
1800 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
1801 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1802 }
1803
Charles Davisebab1ed2010-08-16 05:30:44 +00001804 // Don't allow casting between member pointers of different sizes.
1805 if (Self.Context.getTypeSize(DestMemPtr) !=
1806 Self.Context.getTypeSize(SrcMemPtr)) {
1807 msg = diag::err_bad_cxx_cast_member_pointer_size;
1808 return TC_Failed;
1809 }
1810
Sebastian Redl9f831db2009-07-25 15:41:38 +00001811 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00001812 assert(!IsLValueCast);
1813 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001814 return TC_Success;
1815 }
1816
1817 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001818 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001819 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1820 // type large enough to hold it. A value of std::nullptr_t can be
1821 // converted to an integral type; the conversion has the same meaning
1822 // and validity as a conversion of (void*)0 to the integral type.
1823 if (Self.Context.getTypeSize(SrcType) >
1824 Self.Context.getTypeSize(DestType)) {
1825 msg = diag::err_bad_reinterpret_cast_small_int;
1826 return TC_Failed;
1827 }
John McCalle3027922010-08-25 11:45:40 +00001828 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001829 return TC_Success;
1830 }
1831
Anders Carlsson570af5d2009-09-16 19:19:43 +00001832 bool destIsVector = DestType->isVectorType();
1833 bool srcIsVector = SrcType->isVectorType();
1834 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001835 // FIXME: Should this also apply to floating point types?
1836 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1837 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001838
1839 // Check if this is a cast between a vector and something else.
1840 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1841 !(srcIsVector && destIsVector))
1842 return TC_NotApplicable;
1843
1844 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001845 if (Self.Context.getTypeSize(SrcType)
1846 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001847 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001848 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001849 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001850
1851 if (destIsScalar)
1852 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1853 else if (srcIsScalar)
1854 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1855 else
1856 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1857
1858 return TC_Failed;
1859 }
Chad Rosier96c755d12012-02-03 02:54:37 +00001860
1861 if (SrcType == DestType) {
1862 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1863 // restrictions, a cast to the same type is allowed so long as it does not
1864 // cast away constness. In C++98, the intent was not entirely clear here,
1865 // since all other paragraphs explicitly forbid casts to the same type.
1866 // C++11 clarifies this case with p2.
1867 //
1868 // The only allowed types are: integral, enumeration, pointer, or
1869 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1870 Kind = CK_NoOp;
1871 TryCastResult Result = TC_NotApplicable;
1872 if (SrcType->isIntegralOrEnumerationType() ||
1873 SrcType->isAnyPointerType() ||
1874 SrcType->isMemberPointerType() ||
1875 SrcType->isBlockPointerType()) {
1876 Result = TC_Success;
1877 }
1878 return Result;
1879 }
1880
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001881 bool destIsPtr = DestType->isAnyPointerType() ||
1882 DestType->isBlockPointerType();
1883 bool srcIsPtr = SrcType->isAnyPointerType() ||
1884 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001885 if (!destIsPtr && !srcIsPtr) {
1886 // Except for std::nullptr_t->integer and lvalue->reference, which are
1887 // handled above, at least one of the two arguments must be a pointer.
1888 return TC_NotApplicable;
1889 }
1890
Douglas Gregor6972a622010-06-16 00:35:25 +00001891 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001892 assert(srcIsPtr && "One type must be a pointer");
1893 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001894 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00001895 // integral type size doesn't matter (except we don't allow bool).
1896 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1897 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00001898 if ((Self.Context.getTypeSize(SrcType) >
1899 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00001900 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001901 msg = diag::err_bad_reinterpret_cast_small_int;
1902 return TC_Failed;
1903 }
John McCalle3027922010-08-25 11:45:40 +00001904 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001905 return TC_Success;
1906 }
1907
Douglas Gregorb90df602010-06-16 00:17:44 +00001908 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001909 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00001910 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1911 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001912 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1913 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001914 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1915 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001916 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001917 return TC_Success;
1918 }
1919
1920 if (!destIsPtr || !srcIsPtr) {
1921 // With the valid non-pointer conversions out of the way, we can be even
1922 // more stringent.
1923 return TC_NotApplicable;
1924 }
1925
1926 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1927 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001928 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1929 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001930 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001931 return TC_Failed;
1932 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001933
1934 // Cannot convert between block pointers and Objective-C object pointers.
1935 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1936 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1937 return TC_NotApplicable;
1938
John McCall9320b872011-09-09 05:25:32 +00001939 if (IsLValueCast) {
1940 Kind = CK_LValueBitCast;
1941 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001942 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001943 } else if (DestType->isBlockPointerType()) {
1944 if (!SrcType->isBlockPointerType()) {
1945 Kind = CK_AnyPointerToBlockPointerCast;
1946 } else {
1947 Kind = CK_BitCast;
1948 }
1949 } else {
1950 Kind = CK_BitCast;
1951 }
1952
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001953 // Any pointer can be cast to an Objective-C pointer type with a C-style
1954 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001955 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001956 return TC_Success;
1957 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001958 if (CStyle)
1959 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1960
Sebastian Redl9f831db2009-07-25 15:41:38 +00001961 // Not casting away constness, so the only remaining check is for compatible
1962 // pointer categories.
1963
1964 if (SrcType->isFunctionPointerType()) {
1965 if (DestType->isFunctionPointerType()) {
1966 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1967 // a pointer to a function of a different type.
1968 return TC_Success;
1969 }
1970
1971 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1972 // an object type or vice versa is conditionally-supported.
1973 // Compilers support it in C++03 too, though, because it's necessary for
1974 // casting the return value of dlsym() and GetProcAddress().
1975 // FIXME: Conditionally-supported behavior should be configurable in the
1976 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00001977 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001978 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001979 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1980 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001981 return TC_Success;
1982 }
1983
1984 if (DestType->isFunctionPointerType()) {
1985 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00001986 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001987 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001988 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1989 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001990 return TC_Success;
1991 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001992
Sebastian Redl9f831db2009-07-25 15:41:38 +00001993 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1994 // a pointer to an object of different type.
1995 // Void pointers are not specified, but supported by every compiler out there.
1996 // So we finish by allowing everything that remains - it's got to be two
1997 // object pointers.
1998 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001999}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002000
Sebastian Redld74dd492012-02-12 18:41:05 +00002001void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2002 bool ListInitialization) {
John McCall9776e432011-10-06 23:25:11 +00002003 // Handle placeholders.
2004 if (isPlaceholder()) {
2005 // C-style casts can resolve __unknown_any types.
2006 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2007 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2008 SrcExpr.get(), Kind,
2009 ValueKind, BasePath);
2010 return;
2011 }
John McCallb50451a2011-10-05 07:41:44 +00002012
John McCall9776e432011-10-06 23:25:11 +00002013 checkNonOverloadPlaceholders();
2014 if (SrcExpr.isInvalid())
2015 return;
John McCalla072f5d2011-10-17 17:42:19 +00002016 }
John McCall9776e432011-10-06 23:25:11 +00002017
2018 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002019 // This test is outside everything else because it's the only case where
2020 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002021 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002022 Kind = CK_ToVoid;
2023
John McCall9776e432011-10-06 23:25:11 +00002024 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002025 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2026 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002027 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002028 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002029 if (SrcExpr.isInvalid())
2030 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002031 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002032
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002033 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002034 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002035 }
2036
Sebastian Redl9f831db2009-07-25 15:41:38 +00002037 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002038 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2039 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002040 assert(Kind == CK_Dependent);
2041 return;
John McCall8cb679e2010-11-15 09:13:47 +00002042 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002043
John McCall50a2c2c2011-10-11 23:14:30 +00002044 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2045 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002046 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002047 if (SrcExpr.isInvalid())
2048 return;
John Wiegley01296292011-04-08 18:41:53 +00002049 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002050
John McCall3aef3d82011-04-10 19:13:55 +00002051 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002052 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002053 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002054 && (SrcExpr.get()->getType()->isIntegerType()
2055 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002056 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00002057 return;
John McCall3aef3d82011-04-10 19:13:55 +00002058 }
2059
Sebastian Redl9f831db2009-07-25 15:41:38 +00002060 // C++ [expr.cast]p5: The conversions performed by
2061 // - a const_cast,
2062 // - a static_cast,
2063 // - a static_cast followed by a const_cast,
2064 // - a reinterpret_cast, or
2065 // - a reinterpret_cast followed by a const_cast,
2066 // can be performed using the cast notation of explicit type conversion.
2067 // [...] If a conversion can be interpreted in more than one of the ways
2068 // listed above, the interpretation that appears first in the list is used,
2069 // even if a cast resulting from that interpretation is ill-formed.
2070 // In plain language, this means trying a const_cast ...
2071 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002072 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002073 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002074 if (SrcExpr.isInvalid())
2075 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002076 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002077 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002078
John McCall31168b02011-06-15 23:02:42 +00002079 Sema::CheckedConversionKind CCK
2080 = FunctionalStyle? Sema::CCK_FunctionalCast
2081 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002082 if (tcr == TC_NotApplicable) {
2083 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002084 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002085 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002086 if (SrcExpr.isInvalid())
2087 return;
2088
Sebastian Redl9f831db2009-07-25 15:41:38 +00002089 if (tcr == TC_NotApplicable) {
2090 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002091 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2092 OpRange, msg, Kind);
2093 if (SrcExpr.isInvalid())
2094 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002095 }
2096 }
2097
David Blaikiebbafb8a2012-03-11 07:00:24 +00002098 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002099 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002100
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002101 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002102 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002103 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002104 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2105 DestType,
2106 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002107 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002108 if (Fn) {
2109 // If DestType is a function type (not to be confused with the function
2110 // pointer type), it will be possible to resolve the function address,
2111 // but the type cast should be considered as failure.
2112 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2113 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2114 << OE->getName() << DestType << OpRange
2115 << OE->getQualifierLoc().getSourceRange();
2116 Self.NoteAllOverloadCandidates(SrcExpr.get());
2117 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002118 } else {
John McCallb50451a2011-10-05 07:41:44 +00002119 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002120 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002121 }
John McCallb50451a2011-10-05 07:41:44 +00002122 } else if (Kind == CK_BitCast) {
2123 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002124 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002125
John McCallb50451a2011-10-05 07:41:44 +00002126 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002127 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002128 SrcExpr = ExprError();
2129}
2130
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002131/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2132/// non-matching type. Such as enum function call to int, int call to
2133/// pointer; etc. Cast to 'void' is an exception.
2134static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2135 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002136 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2137 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002138 return;
2139
2140 if (!isa<CallExpr>(SrcExpr.get()))
2141 return;
2142
2143 QualType SrcType = SrcExpr.get()->getType();
2144 if (DestType.getUnqualifiedType()->isVoidType())
2145 return;
2146 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2147 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2148 return;
2149 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2150 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2151 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2152 return;
2153 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2154 return;
2155 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2156 return;
2157 if (SrcType->isComplexType() && DestType->isComplexType())
2158 return;
2159 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2160 return;
2161
2162 Self.Diag(SrcExpr.get()->getExprLoc(),
2163 diag::warn_bad_function_cast)
2164 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2165}
2166
John McCall9776e432011-10-06 23:25:11 +00002167/// Check the semantics of a C-style cast operation, in C.
2168void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002169 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002170
John McCall4124c492011-10-17 18:40:02 +00002171 // C-style casts can resolve __unknown_any types.
2172 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2173 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2174 SrcExpr.get(), Kind,
2175 ValueKind, BasePath);
2176 return;
2177 }
John McCall9776e432011-10-06 23:25:11 +00002178
2179 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2180 // type needs to be scalar.
2181 if (DestType->isVoidType()) {
2182 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002183 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002184 if (SrcExpr.isInvalid())
2185 return;
2186
2187 // Cast to void allows any expr type.
2188 Kind = CK_ToVoid;
2189 return;
2190 }
2191
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002192 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002193 if (SrcExpr.isInvalid())
2194 return;
2195 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002196
John McCall4124c492011-10-17 18:40:02 +00002197 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002198
Joey Gouly8fc32f02014-01-14 12:47:29 +00002199 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2200 // address space B is illegal.
2201 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2202 SrcType->isPointerType()) {
2203 if (DestType->getPointeeType().getAddressSpace() !=
2204 SrcType->getPointeeType().getAddressSpace()) {
2205 Self.Diag(OpRange.getBegin(),
2206 diag::err_typecheck_incompatible_address_space)
2207 << SrcType << DestType << Sema::AA_Casting
2208 << SrcExpr.get()->getSourceRange();
2209 SrcExpr = ExprError();
2210 return;
2211 }
2212 }
2213
John McCall9776e432011-10-06 23:25:11 +00002214 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2215 diag::err_typecheck_cast_to_incomplete)) {
2216 SrcExpr = ExprError();
2217 return;
2218 }
2219
2220 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2221 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2222
2223 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2224 // GCC struct/union extension: allow cast to self.
2225 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2226 << DestType << SrcExpr.get()->getSourceRange();
2227 Kind = CK_NoOp;
2228 return;
2229 }
2230
2231 // GCC's cast to union extension.
2232 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2233 RecordDecl *RD = DestRecordTy->getDecl();
2234 RecordDecl::field_iterator Field, FieldEnd;
2235 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2236 Field != FieldEnd; ++Field) {
2237 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2238 !Field->isUnnamedBitfield()) {
2239 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2240 << SrcExpr.get()->getSourceRange();
2241 break;
2242 }
2243 }
2244 if (Field == FieldEnd) {
2245 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2246 << SrcType << SrcExpr.get()->getSourceRange();
2247 SrcExpr = ExprError();
2248 return;
2249 }
2250 Kind = CK_ToUnion;
2251 return;
2252 }
2253
2254 // Reject any other conversions to non-scalar types.
2255 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2256 << DestType << SrcExpr.get()->getSourceRange();
2257 SrcExpr = ExprError();
2258 return;
2259 }
2260
2261 // The type we're casting to is known to be a scalar or vector.
2262
2263 // Require the operand to be a scalar or vector.
2264 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2265 Self.Diag(SrcExpr.get()->getExprLoc(),
2266 diag::err_typecheck_expect_scalar_operand)
2267 << SrcType << SrcExpr.get()->getSourceRange();
2268 SrcExpr = ExprError();
2269 return;
2270 }
2271
2272 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002273 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002274 return;
2275 }
2276
2277 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2278 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2279 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2280 Kind = CK_VectorSplat;
2281 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2282 SrcExpr = ExprError();
2283 }
2284 return;
2285 }
2286
2287 if (SrcType->isVectorType()) {
2288 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2289 SrcExpr = ExprError();
2290 return;
2291 }
2292
2293 // The source and target types are both scalars, i.e.
2294 // - arithmetic types (fundamental, enum, and complex)
2295 // - all kinds of pointers
2296 // Note that member pointers were filtered out with C++, above.
2297
2298 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2299 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2300 SrcExpr = ExprError();
2301 return;
2302 }
2303
2304 // If either type is a pointer, the other type has to be either an
2305 // integer or a pointer.
2306 if (!DestType->isArithmeticType()) {
2307 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2308 Self.Diag(SrcExpr.get()->getExprLoc(),
2309 diag::err_cast_pointer_from_non_pointer_int)
2310 << SrcType << SrcExpr.get()->getSourceRange();
2311 SrcExpr = ExprError();
2312 return;
2313 }
David Blaikie282ad872012-10-16 18:53:14 +00002314 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2315 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002316 } else if (!SrcType->isArithmeticType()) {
2317 if (!DestType->isIntegralType(Self.Context) &&
2318 DestType->isArithmeticType()) {
2319 Self.Diag(SrcExpr.get()->getLocStart(),
2320 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002321 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002322 SrcExpr = ExprError();
2323 return;
2324 }
2325 }
2326
Joey Goulydd7f4562013-01-23 11:56:20 +00002327 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2328 if (DestType->isHalfType()) {
2329 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2330 << DestType << SrcExpr.get()->getSourceRange();
2331 SrcExpr = ExprError();
2332 return;
2333 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002334 }
2335
John McCall9776e432011-10-06 23:25:11 +00002336 // ARC imposes extra restrictions on casts.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002337 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCall9776e432011-10-06 23:25:11 +00002338 checkObjCARCConversion(Sema::CCK_CStyleCast);
2339 if (SrcExpr.isInvalid())
2340 return;
2341
2342 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2343 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2344 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2345 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2346 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2347 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2348 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2349 Self.Diag(SrcExpr.get()->getLocStart(),
2350 diag::err_typecheck_incompatible_ownership)
2351 << SrcType << DestType << Sema::AA_Casting
2352 << SrcExpr.get()->getSourceRange();
2353 return;
2354 }
2355 }
2356 }
2357 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2358 Self.Diag(SrcExpr.get()->getLocStart(),
2359 diag::err_arc_convesion_of_weak_unavailable)
2360 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2361 SrcExpr = ExprError();
2362 return;
2363 }
2364 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002365
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002366 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002367 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002368 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2369 if (SrcExpr.isInvalid())
2370 return;
2371
2372 if (Kind == CK_BitCast)
2373 checkCastAlign();
2374}
2375
2376ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2377 TypeSourceInfo *CastTypeInfo,
2378 SourceLocation RPLoc,
2379 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002380 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2381 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2382 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2383
David Blaikiebbafb8a2012-03-11 07:00:24 +00002384 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002385 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2386 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002387 } else {
2388 Op.CheckCStyleCast();
2389 }
2390
John McCallb50451a2011-10-05 07:41:44 +00002391 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002392 return ExprError();
2393
John McCall4124c492011-10-17 18:40:02 +00002394 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002395 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002396 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002397}
2398
2399ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2400 SourceLocation LPLoc,
2401 Expr *CastExpr,
2402 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002403 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb50451a2011-10-05 07:41:44 +00002404 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2405 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2406 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2407
Sebastian Redl2b80af42012-02-13 19:55:43 +00002408 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002409 if (Op.SrcExpr.isInvalid())
2410 return ExprError();
Daniel Jasper3e1a9cf2012-07-16 08:05:07 +00002411
2412 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002413 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002414
John McCall4124c492011-10-17 18:40:02 +00002415 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002416 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002417 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002418}