blob: c74bb9a067d39757923565a900dbb38c64ae66d3 [file] [log] [blame]
John McCalld8d3ced2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl26d85b12008-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 McCalld8d3ced2011-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 Redl26d85b12008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000019#include "clang/AST/ExprCXX.h"
John McCalla180f042011-10-06 23:25:11 +000020#include "clang/AST/ExprObjC.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000024#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000025#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000026using namespace clang;
27
Douglas Gregor8e960432010-11-08 03:40:48 +000028
Douglas Gregor8e960432010-11-08 03:40:48 +000029
Sebastian Redl9cc11e72009-07-25 15:41:38 +000030enum TryCastResult {
31 TC_NotApplicable, ///< The cast method is not applicable.
32 TC_Success, ///< The cast method is appropriate and successful.
33 TC_Failed ///< The cast method is appropriate, but failed. A
34 ///< diagnostic has been emitted.
35};
36
37enum CastType {
38 CT_Const, ///< const_cast
39 CT_Static, ///< static_cast
40 CT_Reinterpret, ///< reinterpret_cast
41 CT_Dynamic, ///< dynamic_cast
42 CT_CStyle, ///< (Type)expr
43 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000044};
45
John McCallb45ae252011-10-05 07:41:44 +000046namespace {
47 struct CastOperation {
48 CastOperation(Sema &S, QualType destType, ExprResult src)
49 : Self(S), SrcExpr(src), DestType(destType),
50 ResultType(destType.getNonLValueExprType(S.Context)),
51 ValueKind(Expr::getValueKindForType(destType)),
John McCall5acb0c92011-10-17 18:40:02 +000052 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCalla180f042011-10-06 23:25:11 +000053
54 if (const BuiltinType *placeholder =
55 src.get()->getType()->getAsPlaceholderType()) {
56 PlaceholderKind = placeholder->getKind();
57 } else {
58 PlaceholderKind = (BuiltinType::Kind) 0;
59 }
60 }
Douglas Gregor8e960432010-11-08 03:40:48 +000061
John McCallb45ae252011-10-05 07:41:44 +000062 Sema &Self;
63 ExprResult SrcExpr;
64 QualType DestType;
65 QualType ResultType;
66 ExprValueKind ValueKind;
67 CastKind Kind;
John McCalla180f042011-10-06 23:25:11 +000068 BuiltinType::Kind PlaceholderKind;
John McCallb45ae252011-10-05 07:41:44 +000069 CXXCastPath BasePath;
John McCall5acb0c92011-10-17 18:40:02 +000070 bool IsARCUnbridgedCast;
Douglas Gregor8e960432010-11-08 03:40:48 +000071
John McCallb45ae252011-10-05 07:41:44 +000072 SourceRange OpRange;
73 SourceRange DestRange;
Douglas Gregor8e960432010-11-08 03:40:48 +000074
John McCalla180f042011-10-06 23:25:11 +000075 // Top-level semantics-checking routines.
John McCallb45ae252011-10-05 07:41:44 +000076 void CheckConstCast();
77 void CheckReinterpretCast();
Richard Smithc8d7f582011-11-29 22:48:16 +000078 void CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +000079 void CheckDynamicCast();
Richard Smithc8d7f582011-11-29 22:48:16 +000080 void CheckCXXCStyleCast(bool FunctionalCast);
John McCalla180f042011-10-06 23:25:11 +000081 void CheckCStyleCast();
82
John McCall5acb0c92011-10-17 18:40:02 +000083 /// Complete an apparently-successful cast operation that yields
84 /// the given expression.
85 ExprResult complete(CastExpr *castExpr) {
86 // If this is an unbridged cast, wrap the result in an implicit
87 // cast that yields the unbridged-cast placeholder type.
88 if (IsARCUnbridgedCast) {
89 castExpr = ImplicitCastExpr::Create(Self.Context,
90 Self.Context.ARCUnbridgedCastTy,
91 CK_Dependent, castExpr, 0,
92 castExpr->getValueKind());
93 }
94 return Self.Owned(castExpr);
95 }
96
John McCalla180f042011-10-06 23:25:11 +000097 // Internal convenience methods.
98
99 /// Try to handle the given placeholder expression kind. Return
100 /// true if the source expression has the appropriate placeholder
101 /// kind. A placeholder can only be claimed once.
102 bool claimPlaceholder(BuiltinType::Kind K) {
103 if (PlaceholderKind != K) return false;
104
105 PlaceholderKind = (BuiltinType::Kind) 0;
106 return true;
107 }
108
109 bool isPlaceholder() const {
110 return PlaceholderKind != 0;
111 }
112 bool isPlaceholder(BuiltinType::Kind K) const {
113 return PlaceholderKind == K;
114 }
John McCallb45ae252011-10-05 07:41:44 +0000115
116 void checkCastAlign() {
117 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
118 }
119
120 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
John McCall5acb0c92011-10-17 18:40:02 +0000121 assert(Self.getLangOptions().ObjCAutoRefCount);
122
John McCallb45ae252011-10-05 07:41:44 +0000123 Expr *src = SrcExpr.get();
John McCall5acb0c92011-10-17 18:40:02 +0000124 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
125 Sema::ACR_unbridged)
126 IsARCUnbridgedCast = true;
John McCallb45ae252011-10-05 07:41:44 +0000127 SrcExpr = src;
128 }
John McCalla180f042011-10-06 23:25:11 +0000129
130 /// Check for and handle non-overload placeholder expressions.
131 void checkNonOverloadPlaceholders() {
132 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
133 return;
134
135 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
136 if (SrcExpr.isInvalid())
137 return;
138 PlaceholderKind = (BuiltinType::Kind) 0;
139 }
John McCallb45ae252011-10-05 07:41:44 +0000140 };
141}
Sebastian Redl37d6de32008-11-08 13:00:26 +0000142
John McCallf85e1932011-06-15 23:02:42 +0000143static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
144 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000145
146// The Try functions attempt a specific way of casting. If they succeed, they
147// return TC_Success. If their way of casting is not appropriate for the given
148// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
149// to emit if no other way succeeds. If their way of casting is appropriate but
150// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
151// they emit a specialized diagnostic.
152// All diagnostics returned by these functions must expect the same three
153// arguments:
154// %0: Cast Type (a value from the CastType enumeration)
155// %1: Source Type
156// %2: Destination Type
157static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000158 QualType DestType, bool CStyle,
159 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +0000160 CXXCastPath &BasePath,
161 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000162static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000163 QualType DestType, bool CStyle,
164 const SourceRange &OpRange,
165 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000166 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000167 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000168static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
169 QualType DestType, bool CStyle,
170 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000171 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000172 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000173 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000174static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
175 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000176 const SourceRange &OpRange,
177 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000178 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000179 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000180 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000181static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000182 QualType SrcType,
183 QualType DestType,bool CStyle,
184 const SourceRange &OpRange,
185 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000186 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000187 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000188
John Wiegley429bb272011-04-08 18:41:53 +0000189static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000190 QualType DestType,
191 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000192 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000193 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000194 CastKind &Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000195static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000196 QualType DestType,
197 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000198 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000199 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000200 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000201 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000202static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
203 bool CStyle, unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000205 QualType DestType, bool CStyle,
206 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000207 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000208 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000209
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000210
Sebastian Redl26d85b12008-11-05 21:50:06 +0000211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000212ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000214 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000216 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000217 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000218
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000219 assert(!D.isInvalidType());
220
221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
222 if (D.isInvalidType())
223 return ExprError();
224
225 if (getLangOptions().CPlusPlus) {
226 // Check that there are no default arguments (C++ only).
227 CheckExtraCXXDefaultArguments(D);
228 }
229
230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
John McCallc89724c2010-01-15 19:13:16 +0000231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
233}
234
John McCall60d7b3a2010-08-24 06:29:42 +0000235ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000237 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000238 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000239 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000240 QualType DestType = DestTInfo->getType();
241
Douglas Gregor9103bb22008-12-17 22:52:20 +0000242 // If the type is dependent, we won't do the semantic analysis now.
243 // FIXME: should we check this in a more fine-grained manner?
John Wiegley429bb272011-04-08 18:41:53 +0000244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000245
John McCallb45ae252011-10-05 07:41:44 +0000246 CastOperation Op(*this, DestType, E);
247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000249
Sebastian Redl26d85b12008-11-05 21:50:06 +0000250 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000251 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252
253 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000254 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000255 Op.CheckConstCast();
256 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000257 return ExprError();
258 }
John McCall5acb0c92011-10-17 18:40:02 +0000259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
260 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
261 OpLoc, Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000262
Anders Carlsson714179b2009-08-02 19:07:59 +0000263 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000264 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000265 Op.CheckDynamicCast();
266 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000267 return ExprError();
268 }
John McCall5acb0c92011-10-17 18:40:02 +0000269 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
270 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
271 &Op.BasePath, DestTInfo,
272 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000273 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000274 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000275 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000276 Op.CheckReinterpretCast();
277 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000278 return ExprError();
279 }
John McCall5acb0c92011-10-17 18:40:02 +0000280 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
281 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
282 0, DestTInfo, OpLoc,
283 Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000284 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000285 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000286 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000287 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000288 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000289 return ExprError();
290 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000291
John McCall5acb0c92011-10-17 18:40:02 +0000292 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
293 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
294 &Op.BasePath, DestTInfo,
295 OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000296 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000297 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000298}
299
John McCall79ab2c82011-02-14 18:34:10 +0000300/// Try to diagnose a failed overloaded cast. Returns true if
301/// diagnostics were emitted.
302static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
303 SourceRange range, Expr *src,
304 QualType destType) {
305 switch (CT) {
306 // These cast kinds don't consider user-defined conversions.
307 case CT_Const:
308 case CT_Reinterpret:
309 case CT_Dynamic:
310 return false;
311
312 // These do.
313 case CT_Static:
314 case CT_CStyle:
315 case CT_Functional:
316 break;
317 }
318
319 QualType srcType = src->getType();
320 if (!destType->isRecordType() && !srcType->isRecordType())
321 return false;
322
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000323 bool initList = isa<InitListExpr>(src);
John McCall79ab2c82011-02-14 18:34:10 +0000324 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
325 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000326 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000327 range, initList)
328 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
329 initList)
Richard Smithc8d7f582011-11-29 22:48:16 +0000330 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall79ab2c82011-02-14 18:34:10 +0000331 InitializationSequence sequence(S, entity, initKind, &src, 1);
332
Sebastian Redl383616c2011-06-05 12:23:28 +0000333 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000334 switch (sequence.getFailureKind()) {
335 default: return false;
336
337 case InitializationSequence::FK_ConstructorOverloadFailed:
338 case InitializationSequence::FK_UserConversionOverloadFailed:
339 break;
340 }
341
342 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
343
344 unsigned msg = 0;
345 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
346
347 switch (sequence.getFailedOverloadResult()) {
348 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000349 case OR_No_Viable_Function:
350 if (candidates.empty())
351 msg = diag::err_ovl_no_conversion_in_cast;
352 else
353 msg = diag::err_ovl_no_viable_conversion_in_cast;
354 howManyCandidates = OCD_AllCandidates;
355 break;
356
357 case OR_Ambiguous:
358 msg = diag::err_ovl_ambiguous_conversion_in_cast;
359 howManyCandidates = OCD_ViableCandidates;
360 break;
361
362 case OR_Deleted:
363 msg = diag::err_ovl_deleted_conversion_in_cast;
364 howManyCandidates = OCD_ViableCandidates;
365 break;
366 }
367
368 S.Diag(range.getBegin(), msg)
369 << CT << srcType << destType
370 << range << src->getSourceRange();
371
372 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
373
374 return true;
375}
376
377/// Diagnose a failed cast.
378static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
379 SourceRange opRange, Expr *src, QualType destType) {
John McCall864c0412011-04-26 20:42:42 +0000380 if (src->getType() == S.Context.BoundMemberTy) {
381 (void) S.CheckPlaceholderExpr(src); // will always fail
382 return;
383 }
384
John McCall79ab2c82011-02-14 18:34:10 +0000385 if (msg == diag::err_bad_cxx_cast_generic &&
386 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
387 return;
388
389 S.Diag(opRange.getBegin(), msg) << castType
390 << src->getType() << destType << opRange << src->getSourceRange();
391}
392
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000393/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
394/// this removes one level of indirection from both types, provided that they're
395/// the same kind of pointer (plain or to-member). Unlike the Sema function,
396/// this one doesn't care if the two pointers-to-member don't point into the
397/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000398static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000399 const PointerType *T1PtrType = T1->getAs<PointerType>(),
400 *T2PtrType = T2->getAs<PointerType>();
401 if (T1PtrType && T2PtrType) {
402 T1 = T1PtrType->getPointeeType();
403 T2 = T2PtrType->getPointeeType();
404 return true;
405 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000406 const ObjCObjectPointerType *T1ObjCPtrType =
407 T1->getAs<ObjCObjectPointerType>(),
408 *T2ObjCPtrType =
409 T2->getAs<ObjCObjectPointerType>();
410 if (T1ObjCPtrType) {
411 if (T2ObjCPtrType) {
412 T1 = T1ObjCPtrType->getPointeeType();
413 T2 = T2ObjCPtrType->getPointeeType();
414 return true;
415 }
416 else if (T2PtrType) {
417 T1 = T1ObjCPtrType->getPointeeType();
418 T2 = T2PtrType->getPointeeType();
419 return true;
420 }
421 }
422 else if (T2ObjCPtrType) {
423 if (T1PtrType) {
424 T2 = T2ObjCPtrType->getPointeeType();
425 T1 = T1PtrType->getPointeeType();
426 return true;
427 }
428 }
429
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000430 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
431 *T2MPType = T2->getAs<MemberPointerType>();
432 if (T1MPType && T2MPType) {
433 T1 = T1MPType->getPointeeType();
434 T2 = T2MPType->getPointeeType();
435 return true;
436 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000437
438 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
439 *T2BPType = T2->getAs<BlockPointerType>();
440 if (T1BPType && T2BPType) {
441 T1 = T1BPType->getPointeeType();
442 T2 = T2BPType->getPointeeType();
443 return true;
444 }
445
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000446 return false;
447}
448
Sebastian Redldb647282009-01-27 23:18:31 +0000449/// CastsAwayConstness - Check if the pointer conversion from SrcType to
450/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
451/// the cast checkers. Both arguments must denote pointer (possibly to member)
452/// types.
John McCallf85e1932011-06-15 23:02:42 +0000453///
454/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
455///
456/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000457static bool
John McCallf85e1932011-06-15 23:02:42 +0000458CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
459 bool CheckCVR, bool CheckObjCLifetime) {
460 // If the only checking we care about is for Objective-C lifetime qualifiers,
461 // and we're not in ARC mode, there's nothing to check.
462 if (!CheckCVR && CheckObjCLifetime &&
463 !Self.Context.getLangOptions().ObjCAutoRefCount)
464 return false;
465
Sebastian Redldb647282009-01-27 23:18:31 +0000466 // Casting away constness is defined in C++ 5.2.11p8 with reference to
467 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
468 // the rules are non-trivial. So first we construct Tcv *...cv* as described
469 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000470 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
471 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000472 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000473 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
474 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000475 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000476
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000477 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
478 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000479 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000480
Douglas Gregord4c5f842011-04-15 17:59:54 +0000481 // Find the qualifiers. We only care about cvr-qualifiers for the
482 // purpose of this check, because other qualifiers (address spaces,
483 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000484 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000485 // Determine the relevant qualifiers at this level.
486 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000487 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000488 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000489
490 Qualifiers RetainedSrcQuals, RetainedDestQuals;
491 if (CheckCVR) {
492 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
493 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
494 }
495
496 if (CheckObjCLifetime &&
497 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
498 return true;
499
500 cv1.push_back(RetainedSrcQuals);
501 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000502 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000503 if (cv1.empty())
504 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000505
506 // Construct void pointers with those qualifiers (in reverse order of
507 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000508 QualType SrcConstruct = Self.Context.VoidTy;
509 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000510 ASTContext &Context = Self.Context;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000511 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall0953e762009-09-24 19:53:00 +0000512 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000513 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000514 SrcConstruct
515 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
516 DestConstruct
517 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000518 }
519
520 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000521 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000522 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000523 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
524 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000525}
526
Sebastian Redl26d85b12008-11-05 21:50:06 +0000527/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
528/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
529/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000530void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000531 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000532 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000533 else if (isPlaceholder())
534 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
535 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
536 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000537
John McCallb45ae252011-10-05 07:41:44 +0000538 QualType OrigSrcType = SrcExpr.get()->getType();
539 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000540
541 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
542 // or "pointer to cv void".
543
544 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000546 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000547 if (DestPointer) {
548 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000549 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000550 DestPointee = DestReference->getPointeeType();
551 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000552 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000553 << this->DestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000554 return;
555 }
556
Ted Kremenek6217b802009-07-29 21:53:49 +0000557 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000558 if (DestPointee->isVoidType()) {
559 assert(DestPointer && "Reference to void is not possible");
560 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000561 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000562 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000563 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000564 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000565 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000566 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000567 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000568 return;
569 }
570
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000571 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
572 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000573 // an lvalue of a complete class type, [...]. If T is an rvalue reference
574 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000575 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000576 QualType SrcPointee;
577 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000578 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000579 SrcPointee = SrcPointer->getPointeeType();
580 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000581 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000582 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000583 return;
584 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000585 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000586 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000587 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000588 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000589 }
590 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000591 } else {
592 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000593 }
594
Ted Kremenek6217b802009-07-29 21:53:49 +0000595 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000596 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000597 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000598 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley429bb272011-04-08 18:41:53 +0000599 << SrcExpr.get()->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000600 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000601 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000602 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000603 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000604 return;
605 }
606
607 assert((DestPointer || DestReference) &&
608 "Bad destination non-ptr/ref slipped through.");
609 assert((DestRecord || DestPointee->isVoidType()) &&
610 "Bad destination pointee slipped through.");
611 assert(SrcRecord && "Bad source pointee slipped through.");
612
613 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
614 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000615 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000616 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000617 return;
618 }
619
620 // C++ 5.2.7p3: If the type of v is the same as the required result type,
621 // [except for cv].
622 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000623 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000624 return;
625 }
626
627 // C++ 5.2.7p5
628 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000629 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000630 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
631 OpRange.getBegin(), OpRange,
632 &BasePath))
633 return;
634
John McCall2de56d12010-08-25 11:45:40 +0000635 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000636
637 // If we are casting to or through a virtual base class, we need a
638 // vtable.
639 if (Self.BasePathInvolvesVirtualBase(BasePath))
640 Self.MarkVTableUsed(OpRange.getBegin(),
641 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000642 return;
643 }
644
645 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000646 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000647 assert(SrcDecl && "Definition missing");
648 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000649 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000650 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000651 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000652 Self.MarkVTableUsed(OpRange.getBegin(),
653 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000654
655 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000656 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000657}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000658
659/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
660/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
661/// like this:
662/// const char *str = "literal";
663/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000664void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000665 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000666 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000667 else if (isPlaceholder())
668 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
669 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
670 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000671
672 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000673 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000674 && msg != 0)
675 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000676 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000677}
678
679/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
680/// valid.
681/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
682/// like this:
683/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000684void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000685 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000686 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000687 else
688 checkNonOverloadPlaceholders();
689 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
690 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000691
692 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000693 TryCastResult tcr =
694 TryReinterpretCast(Self, SrcExpr, DestType,
695 /*CStyle*/false, OpRange, msg, Kind);
696 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000697 {
John Wiegley429bb272011-04-08 18:41:53 +0000698 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
699 return;
700 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000701 //FIXME: &f<int>; is overloaded and resolvable
702 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000703 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000704 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000705 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000706
John McCall79ab2c82011-02-14 18:34:10 +0000707 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000708 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000709 }
John McCallf85e1932011-06-15 23:02:42 +0000710 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb45ae252011-10-05 07:41:44 +0000711 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallf85e1932011-06-15 23:02:42 +0000712 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000713}
714
715
716/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
717/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
718/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000719void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000720 if (isPlaceholder()) {
721 checkNonOverloadPlaceholders();
722 if (SrcExpr.isInvalid())
723 return;
724 }
725
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000726 // This test is outside everything else because it's the only case where
727 // a non-lvalue-reference target type does not lead to decay.
728 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000729 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000730 Kind = CK_ToVoid;
731
732 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000733 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000734 false, // Decay Function to ptr
735 true, // Complain
736 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000737 if (SrcExpr.isInvalid())
738 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000739 }
John McCalla180f042011-10-06 23:25:11 +0000740
741 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000742 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000743 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000744
John McCall6dbba4f2011-10-11 23:14:30 +0000745 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
746 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000747 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
748 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
749 return;
750 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000751
752 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000753 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000754 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
John McCallf85e1932011-06-15 23:02:42 +0000755 Kind, BasePath);
756 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000757 if (SrcExpr.isInvalid())
758 return;
759 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
760 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000761 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000762 << oe->getName() << DestType << OpRange
763 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000764 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000765 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000766 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000767 }
John McCallf85e1932011-06-15 23:02:42 +0000768 } else if (tcr == TC_Success) {
769 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000770 checkCastAlign();
771 if (Self.getLangOptions().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000772 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000773 } else if (Kind == CK_BitCast) {
774 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000775 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000776}
777
778/// TryStaticCast - Check if a static cast can be performed, and do so if
779/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
780/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000781static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000782 QualType DestType,
783 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000784 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000785 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000786 CXXCastPath &BasePath) {
John McCallf85e1932011-06-15 23:02:42 +0000787 // Determine whether we have the semantics of a C-style cast.
788 bool CStyle
789 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
790
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000791 // The order the tests is not entirely arbitrary. There is one conversion
792 // that can be handled in two different ways. Given:
793 // struct A {};
794 // struct B : public A {
795 // B(); B(const A&);
796 // };
797 // const A &a = B();
798 // the cast static_cast<const B&>(a) could be seen as either a static
799 // reference downcast, or an explicit invocation of the user-defined
800 // conversion using B's conversion constructor.
801 // DR 427 specifies that the downcast is to be applied here.
802
803 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
804 // Done outside this function.
805
806 TryCastResult tcr;
807
808 // C++ 5.2.9p5, reference downcast.
809 // See the function for details.
810 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley429bb272011-04-08 18:41:53 +0000811 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000812 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000813 if (tcr != TC_NotApplicable)
814 return tcr;
815
Douglas Gregordc843f22011-01-22 00:06:57 +0000816 // C++0x [expr.static.cast]p3:
817 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
818 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley429bb272011-04-08 18:41:53 +0000819 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000820 msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000821 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000822 return tcr;
823
824 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
825 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000826 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000827 Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000828 if (SrcExpr.isInvalid())
829 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000830 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000831 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000832
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000833 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
834 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
835 // conversions, subject to further restrictions.
836 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
837 // of qualification conversions impossible.
838 // In the CStyle case, the earlier attempt to const_cast should have taken
839 // care of reverse qualification conversions.
840
John Wiegley429bb272011-04-08 18:41:53 +0000841 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000842
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000843 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000844 // converted to an integral type. [...] A value of a scoped enumeration type
845 // can also be explicitly converted to a floating-point type [...].
846 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
847 if (Enum->getDecl()->isScoped()) {
848 if (DestType->isBooleanType()) {
849 Kind = CK_IntegralToBoolean;
850 return TC_Success;
851 } else if (DestType->isIntegralType(Self.Context)) {
852 Kind = CK_IntegralCast;
853 return TC_Success;
854 } else if (DestType->isRealFloatingType()) {
855 Kind = CK_IntegralToFloating;
856 return TC_Success;
857 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000858 }
859 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000860
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000861 // Reverse integral promotion/conversion. All such conversions are themselves
862 // again integral promotions or conversions and are thus already handled by
863 // p2 (TryDirectInitialization above).
864 // (Note: any data loss warnings should be suppressed.)
865 // The exception is the reverse of enum->integer, i.e. integer->enum (and
866 // enum->enum). See also C++ 5.2.9p7.
867 // The same goes for reverse floating point promotion/conversion and
868 // floating-integral conversions. Again, only floating->enum is relevant.
869 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000870 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000871 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000872 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000873 } else if (SrcType->isRealFloatingType()) {
874 Kind = CK_FloatingToIntegral;
875 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000876 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000877 }
878
879 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
880 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000881 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000882 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000883 if (tcr != TC_NotApplicable)
884 return tcr;
885
886 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
887 // conversion. C++ 5.2.9p9 has additional information.
888 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000889 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000890 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000891 if (tcr != TC_NotApplicable)
892 return tcr;
893
894 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
895 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
896 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000897 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000898 QualType SrcPointee = SrcPointer->getPointeeType();
899 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000900 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000901 QualType DestPointee = DestPointer->getPointeeType();
902 if (DestPointee->isIncompleteOrObjectType()) {
903 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +0000904 // to a qualifier violation. Note that we permit Objective-C lifetime
905 // and GC qualifier mismatches here.
906 if (!CStyle) {
907 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
908 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
909 DestPointeeQuals.removeObjCGCAttr();
910 DestPointeeQuals.removeObjCLifetime();
911 SrcPointeeQuals.removeObjCGCAttr();
912 SrcPointeeQuals.removeObjCLifetime();
913 if (DestPointeeQuals != SrcPointeeQuals &&
914 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
915 msg = diag::err_bad_cxx_cast_qualifiers_away;
916 return TC_Failed;
917 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000918 }
John McCall2de56d12010-08-25 11:45:40 +0000919 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000920 return TC_Success;
921 }
922 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000923 else if (DestType->isObjCObjectPointerType()) {
924 // allow both c-style cast and static_cast of objective-c pointers as
925 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +0000926 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000927 return TC_Success;
928 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000929 else if (CStyle && DestType->isBlockPointerType()) {
930 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000931 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000932 return TC_Success;
933 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000934 }
935 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000936 // Allow arbitray objective-c pointer conversion with static casts.
937 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000938 DestType->isObjCObjectPointerType()) {
939 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000940 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000941 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000942
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000943 // We tried everything. Everything! Nothing works! :-(
944 return TC_NotApplicable;
945}
946
947/// Tests whether a conversion according to N2844 is valid.
948TryCastResult
949TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000950 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
951 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000952 // C++0x [expr.static.cast]p3:
953 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
954 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000955 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000956 if (!R)
957 return TC_NotApplicable;
958
Douglas Gregordc843f22011-01-22 00:06:57 +0000959 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000960 return TC_NotApplicable;
961
962 // Because we try the reference downcast before this function, from now on
963 // this is the only cast possibility, so we issue an error if we fail now.
964 // FIXME: Should allow casting away constness if CStyle.
965 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000966 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +0000967 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000968 QualType FromType = SrcExpr->getType();
969 QualType ToType = R->getPointeeType();
970 if (CStyle) {
971 FromType = FromType.getUnqualifiedType();
972 ToType = ToType.getUnqualifiedType();
973 }
974
Douglas Gregor393896f2009-11-05 13:06:35 +0000975 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000976 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +0000977 DerivedToBase, ObjCConversion,
978 ObjCLifetimeConversion)
979 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000980 msg = diag::err_bad_lvalue_to_rvalue_cast;
981 return TC_Failed;
982 }
983
Douglas Gregor88b22a42011-01-25 16:13:26 +0000984 if (DerivedToBase) {
985 Kind = CK_DerivedToBase;
986 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
987 /*DetectVirtual=*/true);
988 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
989 return TC_NotApplicable;
990
991 Self.BuildBasePathArray(Paths, BasePath);
992 } else
993 Kind = CK_NoOp;
994
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000995 return TC_Success;
996}
997
998/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
999TryCastResult
1000TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1001 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001002 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001003 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001004 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1005 // cast to type "reference to cv2 D", where D is a class derived from B,
1006 // if a valid standard conversion from "pointer to D" to "pointer to B"
1007 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1008 // In addition, DR54 clarifies that the base must be accessible in the
1009 // current context. Although the wording of DR54 only applies to the pointer
1010 // variant of this rule, the intent is clearly for it to apply to the this
1011 // conversion as well.
1012
Ted Kremenek6217b802009-07-29 21:53:49 +00001013 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001014 if (!DestReference) {
1015 return TC_NotApplicable;
1016 }
1017 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001018 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001019 // We know the left side is an lvalue reference, so we can suggest a reason.
1020 msg = diag::err_bad_cxx_cast_rvalue;
1021 return TC_NotApplicable;
1022 }
1023
1024 QualType DestPointee = DestReference->getPointeeType();
1025
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001026 return TryStaticDowncast(Self,
1027 Self.Context.getCanonicalType(SrcExpr->getType()),
1028 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001029 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1030 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001031}
1032
1033/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1034TryCastResult
1035TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001036 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001037 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001038 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001039 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1040 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1041 // is a class derived from B, if a valid standard conversion from "pointer
1042 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1043 // class of D.
1044 // In addition, DR54 clarifies that the base must be accessible in the
1045 // current context.
1046
Ted Kremenek6217b802009-07-29 21:53:49 +00001047 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048 if (!DestPointer) {
1049 return TC_NotApplicable;
1050 }
1051
Ted Kremenek6217b802009-07-29 21:53:49 +00001052 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001053 if (!SrcPointer) {
1054 msg = diag::err_bad_static_cast_pointer_nonpointer;
1055 return TC_NotApplicable;
1056 }
1057
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001058 return TryStaticDowncast(Self,
1059 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1060 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001061 CStyle, OpRange, SrcType, DestType, msg, Kind,
1062 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001063}
1064
1065/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1066/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001067/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001068TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001069TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001070 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001071 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001072 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001073 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00001074 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1075 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001076 return TC_NotApplicable;
1077
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001078 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001079 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001080 return TC_NotApplicable;
1081 }
1082
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001083 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001084 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001085 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1086 return TC_NotApplicable;
1087 }
1088
1089 // Target type does derive from source type. Now we're serious. If an error
1090 // appears now, it's not ignored.
1091 // This may not be entirely in line with the standard. Take for example:
1092 // struct A {};
1093 // struct B : virtual A {
1094 // B(A&);
1095 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001096 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001097 // void f()
1098 // {
1099 // (void)static_cast<const B&>(*((A*)0));
1100 // }
1101 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1102 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1103 // However, both GCC and Comeau reject this example, and accepting it would
1104 // mean more complex code if we're to preserve the nice error message.
1105 // FIXME: Being 100% compliant here would be nice to have.
1106
1107 // Must preserve cv, as always, unless we're in C-style mode.
1108 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001109 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001110 return TC_Failed;
1111 }
1112
1113 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1114 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1115 // that it builds the paths in reverse order.
1116 // To sum up: record all paths to the base and build a nice string from
1117 // them. Use it to spice up the error message.
1118 if (!Paths.isRecordingPaths()) {
1119 Paths.clear();
1120 Paths.setRecordingPaths(true);
1121 Self.IsDerivedFrom(DestType, SrcType, Paths);
1122 }
1123 std::string PathDisplayStr;
1124 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001125 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001126 PI != PE; ++PI) {
1127 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1128 // We haven't displayed a path to this particular base
1129 // class subobject yet.
1130 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001131 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1132 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001133 EI != EE; ++EI)
1134 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001135 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001136 }
1137 }
1138
1139 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001140 << QualType(SrcType).getUnqualifiedType()
1141 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001142 << PathDisplayStr << OpRange;
1143 msg = 0;
1144 return TC_Failed;
1145 }
1146
1147 if (Paths.getDetectedVirtual() != 0) {
1148 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1149 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1150 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1151 msg = 0;
1152 return TC_Failed;
1153 }
1154
John McCall417d39f2011-02-14 23:21:33 +00001155 if (!CStyle) {
1156 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1157 SrcType, DestType,
1158 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001159 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001160 case Sema::AR_accessible:
1161 case Sema::AR_delayed: // be optimistic
1162 case Sema::AR_dependent: // be optimistic
1163 break;
1164
1165 case Sema::AR_inaccessible:
1166 msg = 0;
1167 return TC_Failed;
1168 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001169 }
1170
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001171 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001172 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001173 return TC_Success;
1174}
1175
1176/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1177/// C++ 5.2.9p9 is valid:
1178///
1179/// An rvalue of type "pointer to member of D of type cv1 T" can be
1180/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1181/// where B is a base class of D [...].
1182///
1183TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001184TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001185 QualType DestType, bool CStyle,
1186 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001187 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001188 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001189 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001190 if (!DestMemPtr)
1191 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001192
1193 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001194 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001195 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001196 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001197 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001198 FoundOverload)) {
1199 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1200 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1201 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1202 WasOverloadedFunction = true;
1203 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001204 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001205
Ted Kremenek6217b802009-07-29 21:53:49 +00001206 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001207 if (!SrcMemPtr) {
1208 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1209 return TC_NotApplicable;
1210 }
1211
1212 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001213 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1214 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001215 return TC_NotApplicable;
1216
1217 // B base of D
1218 QualType SrcClass(SrcMemPtr->getClass(), 0);
1219 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001220 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001221 /*DetectVirtual=*/true);
1222 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1223 return TC_NotApplicable;
1224 }
1225
1226 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +00001227 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001228 Paths.clear();
1229 Paths.setRecordingPaths(true);
1230 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1231 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001232 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001233 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1234 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1235 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1236 msg = 0;
1237 return TC_Failed;
1238 }
1239
1240 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1241 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1242 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1243 msg = 0;
1244 return TC_Failed;
1245 }
1246
John McCall417d39f2011-02-14 23:21:33 +00001247 if (!CStyle) {
1248 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1249 DestClass, SrcClass,
1250 Paths.front(),
1251 diag::err_upcast_to_inaccessible_base)) {
1252 case Sema::AR_accessible:
1253 case Sema::AR_delayed:
1254 case Sema::AR_dependent:
1255 // Optimistically assume that the delayed and dependent cases
1256 // will work out.
1257 break;
1258
1259 case Sema::AR_inaccessible:
1260 msg = 0;
1261 return TC_Failed;
1262 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001263 }
1264
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001265 if (WasOverloadedFunction) {
1266 // Resolve the address of the overloaded function again, this time
1267 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001268 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001269 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001270 true,
1271 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001272 if (!Fn) {
1273 msg = 0;
1274 return TC_Failed;
1275 }
1276
John McCall6bb80172010-03-30 21:47:33 +00001277 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001278 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001279 msg = 0;
1280 return TC_Failed;
1281 }
1282 }
1283
Anders Carlssoncee22422010-04-24 19:22:20 +00001284 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001285 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001286 return TC_Success;
1287}
1288
1289/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1290/// is valid:
1291///
1292/// An expression e can be explicitly converted to a type T using a
1293/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1294TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001295TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001296 Sema::CheckedConversionKind CCK,
1297 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001298 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +00001299 if (DestType->isRecordType()) {
1300 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1301 diag::err_bad_dynamic_cast_incomplete)) {
1302 msg = 0;
1303 return TC_Failed;
1304 }
1305 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001306
1307 // FIXME: doesn't correctly identify T({1})
1308 bool InitList = isa<InitListExpr>(SrcExpr.get());
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001309 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1310 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001311 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001312 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1313 InitList)
John McCallf85e1932011-06-15 23:02:42 +00001314 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001315 ? InitializationKind::CreateFunctionalCast(OpRange, InitList)
Richard Smithc8d7f582011-11-29 22:48:16 +00001316 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001317 Expr *SrcExprRaw = SrcExpr.get();
1318 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001319
1320 // At this point of CheckStaticCast, if the destination is a reference,
1321 // or the expression is an overload expression this has to work.
1322 // There is no other way that works.
1323 // On the other hand, if we're checking a C-style cast, we've still got
1324 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001325 bool CStyle
1326 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001327 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001328 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001329
John McCall60d7b3a2010-08-24 06:29:42 +00001330 ExprResult Result
John Wiegley429bb272011-04-08 18:41:53 +00001331 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001332 if (Result.isInvalid()) {
1333 msg = 0;
1334 return TC_Failed;
1335 }
1336
Douglas Gregord6e44a32010-04-16 22:09:46 +00001337 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001338 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001339 else
John McCall2de56d12010-08-25 11:45:40 +00001340 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001341
John Wiegley429bb272011-04-08 18:41:53 +00001342 SrcExpr = move(Result);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001343 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001344}
1345
1346/// TryConstCast - See if a const_cast from source to destination is allowed,
1347/// and perform it if it is.
1348static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1349 bool CStyle, unsigned &msg) {
1350 DestType = Self.Context.getCanonicalType(DestType);
1351 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001352 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1353 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001354 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1355 // is C-style, static_cast might find a way, so we simply suggest a
1356 // message and tell the parent to keep searching.
1357 msg = diag::err_bad_cxx_cast_rvalue;
1358 return TC_NotApplicable;
1359 }
1360
1361 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1362 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1363 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1364 SrcType = Self.Context.getPointerType(SrcType);
1365 }
1366
1367 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1368 // the rules for const_cast are the same as those used for pointers.
1369
John McCalld425d2b2010-05-18 09:35:29 +00001370 if (!DestType->isPointerType() &&
1371 !DestType->isMemberPointerType() &&
1372 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001373 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1374 // was a reference type, we converted it to a pointer above.
1375 // The status of rvalue references isn't entirely clear, but it looks like
1376 // conversion to them is simply invalid.
1377 // C++ 5.2.11p3: For two pointer types [...]
1378 if (!CStyle)
1379 msg = diag::err_bad_const_cast_dest;
1380 return TC_NotApplicable;
1381 }
1382 if (DestType->isFunctionPointerType() ||
1383 DestType->isMemberFunctionPointerType()) {
1384 // Cannot cast direct function pointers.
1385 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1386 // T is the ultimate pointee of source and target type.
1387 if (!CStyle)
1388 msg = diag::err_bad_const_cast_dest;
1389 return TC_NotApplicable;
1390 }
1391 SrcType = Self.Context.getCanonicalType(SrcType);
1392
1393 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1394 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001395 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1396 // in multi-level pointers may change, but the level count must be the same,
1397 // as must be the final pointee type.
1398 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001399 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001400 Qualifiers SrcQuals, DestQuals;
1401 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1402 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1403
1404 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1405 // the other qualifiers (e.g., address spaces) are identical.
1406 SrcQuals.removeCVRQualifiers();
1407 DestQuals.removeCVRQualifiers();
1408 if (SrcQuals != DestQuals)
1409 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001410 }
1411
1412 // Since we're dealing in canonical types, the remainder must be the same.
1413 if (SrcType != DestType)
1414 return TC_NotApplicable;
1415
1416 return TC_Success;
1417}
1418
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001419// Checks for undefined behavior in reinterpret_cast.
1420// The cases that is checked for is:
1421// *reinterpret_cast<T*>(&a)
1422// reinterpret_cast<T&>(a)
1423// where accessing 'a' as type 'T' will result in undefined behavior.
1424void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1425 bool IsDereference,
1426 SourceRange Range) {
1427 unsigned DiagID = IsDereference ?
1428 diag::warn_pointer_indirection_from_incompatible_type :
1429 diag::warn_undefined_reinterpret_cast;
1430
1431 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001432 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001433 return;
1434 }
1435
1436 QualType SrcTy, DestTy;
1437 if (IsDereference) {
1438 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1439 return;
1440 }
1441 SrcTy = SrcType->getPointeeType();
1442 DestTy = DestType->getPointeeType();
1443 } else {
1444 if (!DestType->getAs<ReferenceType>()) {
1445 return;
1446 }
1447 SrcTy = SrcType;
1448 DestTy = DestType->getPointeeType();
1449 }
1450
1451 // Cast is compatible if the types are the same.
1452 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1453 return;
1454 }
1455 // or one of the types is a char or void type
1456 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1457 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1458 return;
1459 }
1460 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001461 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001462 return;
1463 }
1464
Douglas Gregor575a1c92011-05-20 16:38:50 +00001465 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001466 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1467 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1468 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1469 return;
1470 }
1471 }
1472
1473 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1474}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001475
John Wiegley429bb272011-04-08 18:41:53 +00001476static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001477 QualType DestType, bool CStyle,
1478 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001479 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001480 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001481 bool IsLValueCast = false;
1482
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001483 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001484 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001485
1486 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001487 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1488 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001489 // ... unless foo<int> resolves to an lvalue unambiguously.
1490 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1491 // like it?
1492 ExprResult SingleFunctionExpr = SrcExpr;
1493 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1494 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001495 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001496 ) && SingleFunctionExpr.isUsable()) {
John Wiegley429bb272011-04-08 18:41:53 +00001497 SrcExpr = move(SingleFunctionExpr);
1498 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001499 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001500 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001501 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001502 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001503
Ted Kremenek6217b802009-07-29 21:53:49 +00001504 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001505 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00001506 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregor575d2a32011-01-22 00:19:52 +00001507 // Cannot cast non-lvalue to lvalue reference type. See the similar
1508 // comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001509 msg = diag::err_bad_cxx_cast_rvalue;
1510 return TC_NotApplicable;
1511 }
1512
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001513 if (!CStyle) {
1514 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1515 /*isDereference=*/false, OpRange);
1516 }
1517
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001518 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1519 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1520 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001521
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001522 const char *inappropriate = 0;
1523 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001524 case OK_Ordinary:
1525 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001526 case OK_BitField: inappropriate = "bit-field"; break;
1527 case OK_VectorComponent: inappropriate = "vector element"; break;
1528 case OK_ObjCProperty: inappropriate = "property expression"; break;
1529 }
1530 if (inappropriate) {
1531 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1532 << inappropriate << DestType
1533 << OpRange << SrcExpr.get()->getSourceRange();
1534 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001535 return TC_NotApplicable;
1536 }
1537
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001538 // This code does this transformation for the checked types.
1539 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1540 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001541
Douglas Gregore39a3892010-07-13 23:17:26 +00001542 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001543 }
1544
1545 // Canonicalize source for comparison.
1546 SrcType = Self.Context.getCanonicalType(SrcType);
1547
Ted Kremenek6217b802009-07-29 21:53:49 +00001548 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1549 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001550 if (DestMemPtr && SrcMemPtr) {
1551 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1552 // can be explicitly converted to an rvalue of type "pointer to member
1553 // of Y of type T2" if T1 and T2 are both function types or both object
1554 // types.
1555 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1556 SrcMemPtr->getPointeeType()->isFunctionType())
1557 return TC_NotApplicable;
1558
1559 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1560 // constness.
1561 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1562 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001563 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1564 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001565 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001566 return TC_Failed;
1567 }
1568
Charles Davisf231df32010-08-16 05:30:44 +00001569 // Don't allow casting between member pointers of different sizes.
1570 if (Self.Context.getTypeSize(DestMemPtr) !=
1571 Self.Context.getTypeSize(SrcMemPtr)) {
1572 msg = diag::err_bad_cxx_cast_member_pointer_size;
1573 return TC_Failed;
1574 }
1575
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001576 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001577 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001578 return TC_Success;
1579 }
1580
1581 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001582 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001583 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1584 // type large enough to hold it. A value of std::nullptr_t can be
1585 // converted to an integral type; the conversion has the same meaning
1586 // and validity as a conversion of (void*)0 to the integral type.
1587 if (Self.Context.getTypeSize(SrcType) >
1588 Self.Context.getTypeSize(DestType)) {
1589 msg = diag::err_bad_reinterpret_cast_small_int;
1590 return TC_Failed;
1591 }
John McCall2de56d12010-08-25 11:45:40 +00001592 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001593 return TC_Success;
1594 }
1595
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001596 bool destIsVector = DestType->isVectorType();
1597 bool srcIsVector = SrcType->isVectorType();
1598 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001599 // FIXME: Should this also apply to floating point types?
1600 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1601 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001602
1603 // Check if this is a cast between a vector and something else.
1604 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1605 !(srcIsVector && destIsVector))
1606 return TC_NotApplicable;
1607
1608 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001609 if (Self.Context.getTypeSize(SrcType)
1610 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001611 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001612 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001613 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001614
1615 if (destIsScalar)
1616 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1617 else if (srcIsScalar)
1618 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1619 else
1620 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1621
1622 return TC_Failed;
1623 }
Chad Rosier41f44312012-02-03 02:54:37 +00001624
1625 if (SrcType == DestType) {
1626 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1627 // restrictions, a cast to the same type is allowed so long as it does not
1628 // cast away constness. In C++98, the intent was not entirely clear here,
1629 // since all other paragraphs explicitly forbid casts to the same type.
1630 // C++11 clarifies this case with p2.
1631 //
1632 // The only allowed types are: integral, enumeration, pointer, or
1633 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1634 Kind = CK_NoOp;
1635 TryCastResult Result = TC_NotApplicable;
1636 if (SrcType->isIntegralOrEnumerationType() ||
1637 SrcType->isAnyPointerType() ||
1638 SrcType->isMemberPointerType() ||
1639 SrcType->isBlockPointerType()) {
1640 Result = TC_Success;
1641 }
1642 return Result;
1643 }
1644
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001645 bool destIsPtr = DestType->isAnyPointerType() ||
1646 DestType->isBlockPointerType();
1647 bool srcIsPtr = SrcType->isAnyPointerType() ||
1648 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001649 if (!destIsPtr && !srcIsPtr) {
1650 // Except for std::nullptr_t->integer and lvalue->reference, which are
1651 // handled above, at least one of the two arguments must be a pointer.
1652 return TC_NotApplicable;
1653 }
1654
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001655 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001656 assert(srcIsPtr && "One type must be a pointer");
1657 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001658 // type large enough to hold it; except in Microsoft mode, where the
1659 // integral type size doesn't matter.
1660 if ((Self.Context.getTypeSize(SrcType) >
1661 Self.Context.getTypeSize(DestType)) &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00001662 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001663 msg = diag::err_bad_reinterpret_cast_small_int;
1664 return TC_Failed;
1665 }
John McCall2de56d12010-08-25 11:45:40 +00001666 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001667 return TC_Success;
1668 }
1669
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001670 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001671 assert(destIsPtr && "One type must be a pointer");
1672 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1673 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001674 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1675 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001676 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001677 return TC_Success;
1678 }
1679
1680 if (!destIsPtr || !srcIsPtr) {
1681 // With the valid non-pointer conversions out of the way, we can be even
1682 // more stringent.
1683 return TC_NotApplicable;
1684 }
1685
1686 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1687 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001688 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1689 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001690 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001691 return TC_Failed;
1692 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001693
1694 // Cannot convert between block pointers and Objective-C object pointers.
1695 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1696 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1697 return TC_NotApplicable;
1698
John McCall1d9b3b22011-09-09 05:25:32 +00001699 if (IsLValueCast) {
1700 Kind = CK_LValueBitCast;
1701 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001702 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001703 } else if (DestType->isBlockPointerType()) {
1704 if (!SrcType->isBlockPointerType()) {
1705 Kind = CK_AnyPointerToBlockPointerCast;
1706 } else {
1707 Kind = CK_BitCast;
1708 }
1709 } else {
1710 Kind = CK_BitCast;
1711 }
1712
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001713 // Any pointer can be cast to an Objective-C pointer type with a C-style
1714 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001715 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001716 return TC_Success;
1717 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001718
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001719 // Not casting away constness, so the only remaining check is for compatible
1720 // pointer categories.
1721
1722 if (SrcType->isFunctionPointerType()) {
1723 if (DestType->isFunctionPointerType()) {
1724 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1725 // a pointer to a function of a different type.
1726 return TC_Success;
1727 }
1728
1729 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1730 // an object type or vice versa is conditionally-supported.
1731 // Compilers support it in C++03 too, though, because it's necessary for
1732 // casting the return value of dlsym() and GetProcAddress().
1733 // FIXME: Conditionally-supported behavior should be configurable in the
1734 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001735 Self.Diag(OpRange.getBegin(),
1736 Self.getLangOptions().CPlusPlus0x ?
1737 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1738 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001739 return TC_Success;
1740 }
1741
1742 if (DestType->isFunctionPointerType()) {
1743 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001744 Self.Diag(OpRange.getBegin(),
1745 Self.getLangOptions().CPlusPlus0x ?
1746 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1747 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001748 return TC_Success;
1749 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001750
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001751 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1752 // a pointer to an object of different type.
1753 // Void pointers are not specified, but supported by every compiler out there.
1754 // So we finish by allowing everything that remains - it's got to be two
1755 // object pointers.
1756 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001757}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001758
Richard Smithc8d7f582011-11-29 22:48:16 +00001759void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
John McCalla180f042011-10-06 23:25:11 +00001760 // Handle placeholders.
1761 if (isPlaceholder()) {
1762 // C-style casts can resolve __unknown_any types.
1763 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1764 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1765 SrcExpr.get(), Kind,
1766 ValueKind, BasePath);
1767 return;
1768 }
John McCallb45ae252011-10-05 07:41:44 +00001769
John McCalla180f042011-10-06 23:25:11 +00001770 checkNonOverloadPlaceholders();
1771 if (SrcExpr.isInvalid())
1772 return;
John McCall4919dfd2011-10-17 17:42:19 +00001773 }
John McCalla180f042011-10-06 23:25:11 +00001774
1775 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001776 // This test is outside everything else because it's the only case where
1777 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001778 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001779 Kind = CK_ToVoid;
1780
John McCalla180f042011-10-06 23:25:11 +00001781 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001782 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1783 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00001784 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001785 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00001786 if (SrcExpr.isInvalid())
1787 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001788 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001789
John McCalla180f042011-10-06 23:25:11 +00001790 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1791 if (SrcExpr.isInvalid())
John McCallb45ae252011-10-05 07:41:44 +00001792 return;
John McCallb45ae252011-10-05 07:41:44 +00001793
1794 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00001795 }
1796
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001797 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb45ae252011-10-05 07:41:44 +00001798 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1799 assert(Kind == CK_Dependent);
1800 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00001801 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00001802
John McCall6dbba4f2011-10-11 23:14:30 +00001803 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1804 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00001805 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1806 if (SrcExpr.isInvalid())
1807 return;
John Wiegley429bb272011-04-08 18:41:53 +00001808 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001809
John McCallfb8721c2011-04-10 19:13:55 +00001810 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00001811 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00001812 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00001813 && (SrcExpr.get()->getType()->isIntegerType()
1814 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00001815 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00001816 return;
John McCallfb8721c2011-04-10 19:13:55 +00001817 }
1818
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001819 // C++ [expr.cast]p5: The conversions performed by
1820 // - a const_cast,
1821 // - a static_cast,
1822 // - a static_cast followed by a const_cast,
1823 // - a reinterpret_cast, or
1824 // - a reinterpret_cast followed by a const_cast,
1825 // can be performed using the cast notation of explicit type conversion.
1826 // [...] If a conversion can be interpreted in more than one of the ways
1827 // listed above, the interpretation that appears first in the list is used,
1828 // even if a cast resulting from that interpretation is ill-formed.
1829 // In plain language, this means trying a const_cast ...
1830 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb45ae252011-10-05 07:41:44 +00001831 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1832 /*CStyle*/true, msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001833 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001834 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001835
John McCallf85e1932011-06-15 23:02:42 +00001836 Sema::CheckedConversionKind CCK
1837 = FunctionalStyle? Sema::CCK_FunctionalCast
1838 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001839 if (tcr == TC_NotApplicable) {
1840 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00001841 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1842 msg, Kind, BasePath);
1843 if (SrcExpr.isInvalid())
1844 return;
1845
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001846 if (tcr == TC_NotApplicable) {
1847 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00001848 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1849 OpRange, msg, Kind);
1850 if (SrcExpr.isInvalid())
1851 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001852 }
1853 }
1854
John McCallb45ae252011-10-05 07:41:44 +00001855 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1856 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00001857
Nick Lewycky43328e92010-11-09 00:19:31 +00001858 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00001859 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001860 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00001861 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1862 DestType,
1863 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00001864 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001865
Richard Trieu32ac00d2011-04-16 01:09:30 +00001866 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001867 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001868
Nick Lewycky43328e92010-11-09 00:19:31 +00001869 } else {
John McCallb45ae252011-10-05 07:41:44 +00001870 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1871 OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001872 }
John McCallb45ae252011-10-05 07:41:44 +00001873 } else if (Kind == CK_BitCast) {
1874 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00001875 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001876
John McCallb45ae252011-10-05 07:41:44 +00001877 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00001878 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001879 SrcExpr = ExprError();
1880}
1881
John McCalla180f042011-10-06 23:25:11 +00001882/// Check the semantics of a C-style cast operation, in C.
1883void CastOperation::CheckCStyleCast() {
1884 assert(!Self.getLangOptions().CPlusPlus);
1885
John McCall5acb0c92011-10-17 18:40:02 +00001886 // C-style casts can resolve __unknown_any types.
1887 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1888 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1889 SrcExpr.get(), Kind,
1890 ValueKind, BasePath);
1891 return;
1892 }
John McCalla180f042011-10-06 23:25:11 +00001893
1894 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1895 // type needs to be scalar.
1896 if (DestType->isVoidType()) {
1897 // We don't necessarily do lvalue-to-rvalue conversions on this.
1898 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1899 if (SrcExpr.isInvalid())
1900 return;
1901
1902 // Cast to void allows any expr type.
1903 Kind = CK_ToVoid;
1904 return;
1905 }
1906
1907 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1908 if (SrcExpr.isInvalid())
1909 return;
1910 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00001911
1912 // You can cast an _Atomic(T) to anything you can cast a T to.
1913 if (const AtomicType *AtomicSrcType = SrcType->getAs<AtomicType>())
1914 SrcType = AtomicSrcType->getValueType();
1915
John McCall5acb0c92011-10-17 18:40:02 +00001916 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00001917
1918 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1919 diag::err_typecheck_cast_to_incomplete)) {
1920 SrcExpr = ExprError();
1921 return;
1922 }
1923
1924 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1925 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1926
1927 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1928 // GCC struct/union extension: allow cast to self.
1929 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1930 << DestType << SrcExpr.get()->getSourceRange();
1931 Kind = CK_NoOp;
1932 return;
1933 }
1934
1935 // GCC's cast to union extension.
1936 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1937 RecordDecl *RD = DestRecordTy->getDecl();
1938 RecordDecl::field_iterator Field, FieldEnd;
1939 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1940 Field != FieldEnd; ++Field) {
1941 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1942 !Field->isUnnamedBitfield()) {
1943 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1944 << SrcExpr.get()->getSourceRange();
1945 break;
1946 }
1947 }
1948 if (Field == FieldEnd) {
1949 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1950 << SrcType << SrcExpr.get()->getSourceRange();
1951 SrcExpr = ExprError();
1952 return;
1953 }
1954 Kind = CK_ToUnion;
1955 return;
1956 }
1957
1958 // Reject any other conversions to non-scalar types.
1959 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1960 << DestType << SrcExpr.get()->getSourceRange();
1961 SrcExpr = ExprError();
1962 return;
1963 }
1964
1965 // The type we're casting to is known to be a scalar or vector.
1966
1967 // Require the operand to be a scalar or vector.
1968 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1969 Self.Diag(SrcExpr.get()->getExprLoc(),
1970 diag::err_typecheck_expect_scalar_operand)
1971 << SrcType << SrcExpr.get()->getSourceRange();
1972 SrcExpr = ExprError();
1973 return;
1974 }
1975
1976 if (DestType->isExtVectorType()) {
1977 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1978 return;
1979 }
1980
1981 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1982 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1983 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1984 Kind = CK_VectorSplat;
1985 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1986 SrcExpr = ExprError();
1987 }
1988 return;
1989 }
1990
1991 if (SrcType->isVectorType()) {
1992 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1993 SrcExpr = ExprError();
1994 return;
1995 }
1996
1997 // The source and target types are both scalars, i.e.
1998 // - arithmetic types (fundamental, enum, and complex)
1999 // - all kinds of pointers
2000 // Note that member pointers were filtered out with C++, above.
2001
2002 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2003 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2004 SrcExpr = ExprError();
2005 return;
2006 }
2007
2008 // If either type is a pointer, the other type has to be either an
2009 // integer or a pointer.
2010 if (!DestType->isArithmeticType()) {
2011 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2012 Self.Diag(SrcExpr.get()->getExprLoc(),
2013 diag::err_cast_pointer_from_non_pointer_int)
2014 << SrcType << SrcExpr.get()->getSourceRange();
2015 SrcExpr = ExprError();
2016 return;
2017 }
2018 } else if (!SrcType->isArithmeticType()) {
2019 if (!DestType->isIntegralType(Self.Context) &&
2020 DestType->isArithmeticType()) {
2021 Self.Diag(SrcExpr.get()->getLocStart(),
2022 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002023 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002024 SrcExpr = ExprError();
2025 return;
2026 }
2027 }
2028
2029 // ARC imposes extra restrictions on casts.
2030 if (Self.getLangOptions().ObjCAutoRefCount) {
2031 checkObjCARCConversion(Sema::CCK_CStyleCast);
2032 if (SrcExpr.isInvalid())
2033 return;
2034
2035 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2036 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2037 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2038 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2039 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2040 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2041 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2042 Self.Diag(SrcExpr.get()->getLocStart(),
2043 diag::err_typecheck_incompatible_ownership)
2044 << SrcType << DestType << Sema::AA_Casting
2045 << SrcExpr.get()->getSourceRange();
2046 return;
2047 }
2048 }
2049 }
2050 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2051 Self.Diag(SrcExpr.get()->getLocStart(),
2052 diag::err_arc_convesion_of_weak_unavailable)
2053 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2054 SrcExpr = ExprError();
2055 return;
2056 }
2057 }
2058
2059 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2060 if (SrcExpr.isInvalid())
2061 return;
2062
2063 if (Kind == CK_BitCast)
2064 checkCastAlign();
2065}
2066
2067ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2068 TypeSourceInfo *CastTypeInfo,
2069 SourceLocation RPLoc,
2070 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002071 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2072 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2073 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2074
John McCalla180f042011-10-06 23:25:11 +00002075 if (getLangOptions().CPlusPlus) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002076 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false);
John McCalla180f042011-10-06 23:25:11 +00002077 } else {
2078 Op.CheckCStyleCast();
2079 }
2080
John McCallb45ae252011-10-05 07:41:44 +00002081 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002082 return ExprError();
2083
John McCall5acb0c92011-10-17 18:40:02 +00002084 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2085 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2086 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002087}
2088
2089ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2090 SourceLocation LPLoc,
2091 Expr *CastExpr,
2092 SourceLocation RPLoc) {
2093 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2094 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2095 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2096
Richard Smithc8d7f582011-11-29 22:48:16 +00002097 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true);
John McCallb45ae252011-10-05 07:41:44 +00002098 if (Op.SrcExpr.isInvalid())
2099 return ExprError();
2100
John McCall5acb0c92011-10-17 18:40:02 +00002101 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2102 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2103 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002104}