blob: 925f468cfd2f8f745000679afa40b21b54bf6685 [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCall3cec19f2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000019#include "clang/AST/ExprCXX.h"
John McCall9776e432011-10-06 23:25:11 +000020#include "clang/AST/ExprObjC.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000024#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000025#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026using namespace clang;
27
Douglas Gregore81f58e2010-11-08 03:40:48 +000028
Douglas Gregore81f58e2010-11-08 03:40:48 +000029
Sebastian Redl9f831db2009-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 Redl842ef522008-11-08 13:00:26 +000044};
45
John McCallb50451a2011-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 McCall4124c492011-10-17 18:40:02 +000052 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-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 Gregore81f58e2010-11-08 03:40:48 +000061
John McCallb50451a2011-10-05 07:41:44 +000062 Sema &Self;
63 ExprResult SrcExpr;
64 QualType DestType;
65 QualType ResultType;
66 ExprValueKind ValueKind;
67 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000068 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000069 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000070 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000071
John McCallb50451a2011-10-05 07:41:44 +000072 SourceRange OpRange;
73 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000074
John McCall9776e432011-10-06 23:25:11 +000075 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000076 void CheckConstCast();
77 void CheckReinterpretCast();
78 void CheckStaticCast();
79 void CheckDynamicCast();
John McCall9776e432011-10-06 23:25:11 +000080 void CheckCXXCStyleCast(bool FunctionalCast);
81 void CheckCStyleCast();
82
John McCall4124c492011-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 McCall9776e432011-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 McCallb50451a2011-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 McCall4124c492011-10-17 18:40:02 +0000121 assert(Self.getLangOptions().ObjCAutoRefCount);
122
John McCallb50451a2011-10-05 07:41:44 +0000123 Expr *src = SrcExpr.get();
John McCall4124c492011-10-17 18:40:02 +0000124 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
125 Sema::ACR_unbridged)
126 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000127 SrcExpr = src;
128 }
John McCall9776e432011-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 McCallb50451a2011-10-05 07:41:44 +0000140 };
141}
Sebastian Redl842ef522008-11-08 13:00:26 +0000142
John McCall31168b02011-06-15 23:02:42 +0000143static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
144 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9f831db2009-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 Gregorce950842011-01-26 21:04:06 +0000158 QualType DestType, bool CStyle,
159 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000160 CXXCastPath &BasePath,
161 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000162static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000163 QualType DestType, bool CStyle,
164 const SourceRange &OpRange,
165 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000166 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000167 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000168static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
169 QualType DestType, bool CStyle,
170 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000171 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000172 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000173 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000174static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
175 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000176 const SourceRange &OpRange,
177 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000178 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000179 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000180 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000181static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000182 QualType SrcType,
183 QualType DestType,bool CStyle,
184 const SourceRange &OpRange,
185 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000186 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000187 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000188
John Wiegley01296292011-04-08 18:41:53 +0000189static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000190 QualType DestType,
191 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000192 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000193 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000194 CastKind &Kind);
John Wiegley01296292011-04-08 18:41:53 +0000195static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000196 QualType DestType,
197 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000198 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000199 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000200 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000201 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000202static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
203 bool CStyle, unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000205 QualType DestType, bool CStyle,
206 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000207 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000208 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000209
Douglas Gregorb491ed32011-02-19 21:32:49 +0000210
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000212ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000214 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000216 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000217 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000218
Argyrios Kyrtzidis7451d1c2011-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 McCalld377e042010-01-15 19:13:16 +0000231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
233}
234
John McCalldadc5752010-08-24 06:29:42 +0000235ExprResult
John McCalld377e042010-01-15 19:13:16 +0000236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000237 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000238 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley01296292011-04-08 18:41:53 +0000239 ExprResult Ex = Owned(E);
John McCalld377e042010-01-15 19:13:16 +0000240 QualType DestType = DestTInfo->getType();
241
Douglas Gregor19b8c4f2008-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 Wiegley01296292011-04-08 18:41:53 +0000244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000245
John McCallb50451a2011-10-05 07:41:44 +0000246 CastOperation Op(*this, DestType, E);
247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000249
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000250 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000251 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000252
253 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000254 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000255 Op.CheckConstCast();
256 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000257 return ExprError();
258 }
John McCall4124c492011-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 Redl3c5aa4d2008-11-05 21:50:06 +0000262
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000263 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000264 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000265 Op.CheckDynamicCast();
266 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000267 return ExprError();
268 }
John McCall4124c492011-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 Carlsson4ab4f7f2009-08-02 19:07:59 +0000273 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000274 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000275 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000276 Op.CheckReinterpretCast();
277 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000278 return ExprError();
279 }
John McCall4124c492011-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 Carlsson7cd39e02009-09-15 04:48:33 +0000284 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000285 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000286 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000287 Op.CheckStaticCast();
288 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000289 return ExprError();
290 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000291
John McCall4124c492011-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 Carlssonf10e4142009-08-07 22:21:05 +0000296 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000297 }
298
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000299 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000300}
301
John McCall909acf82011-02-14 18:34:10 +0000302/// Try to diagnose a failed overloaded cast. Returns true if
303/// diagnostics were emitted.
304static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
305 SourceRange range, Expr *src,
306 QualType destType) {
307 switch (CT) {
308 // These cast kinds don't consider user-defined conversions.
309 case CT_Const:
310 case CT_Reinterpret:
311 case CT_Dynamic:
312 return false;
313
314 // These do.
315 case CT_Static:
316 case CT_CStyle:
317 case CT_Functional:
318 break;
319 }
320
321 QualType srcType = src->getType();
322 if (!destType->isRecordType() && !srcType->isRecordType())
323 return false;
324
325 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
326 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000327 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
328 range)
329 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
330 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall909acf82011-02-14 18:34:10 +0000331 InitializationSequence sequence(S, entity, initKind, &src, 1);
332
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000333 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-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");
349 return false;
350 case OR_No_Viable_Function:
351 if (candidates.empty())
352 msg = diag::err_ovl_no_conversion_in_cast;
353 else
354 msg = diag::err_ovl_no_viable_conversion_in_cast;
355 howManyCandidates = OCD_AllCandidates;
356 break;
357
358 case OR_Ambiguous:
359 msg = diag::err_ovl_ambiguous_conversion_in_cast;
360 howManyCandidates = OCD_ViableCandidates;
361 break;
362
363 case OR_Deleted:
364 msg = diag::err_ovl_deleted_conversion_in_cast;
365 howManyCandidates = OCD_ViableCandidates;
366 break;
367 }
368
369 S.Diag(range.getBegin(), msg)
370 << CT << srcType << destType
371 << range << src->getSourceRange();
372
373 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
374
375 return true;
376}
377
378/// Diagnose a failed cast.
379static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
380 SourceRange opRange, Expr *src, QualType destType) {
John McCall0009fcc2011-04-26 20:42:42 +0000381 if (src->getType() == S.Context.BoundMemberTy) {
382 (void) S.CheckPlaceholderExpr(src); // will always fail
383 return;
384 }
385
John McCall909acf82011-02-14 18:34:10 +0000386 if (msg == diag::err_bad_cxx_cast_generic &&
387 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
388 return;
389
390 S.Diag(opRange.getBegin(), msg) << castType
391 << src->getType() << destType << opRange << src->getSourceRange();
392}
393
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000394/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
395/// this removes one level of indirection from both types, provided that they're
396/// the same kind of pointer (plain or to-member). Unlike the Sema function,
397/// this one doesn't care if the two pointers-to-member don't point into the
398/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000399static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000400 const PointerType *T1PtrType = T1->getAs<PointerType>(),
401 *T2PtrType = T2->getAs<PointerType>();
402 if (T1PtrType && T2PtrType) {
403 T1 = T1PtrType->getPointeeType();
404 T2 = T2PtrType->getPointeeType();
405 return true;
406 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000407 const ObjCObjectPointerType *T1ObjCPtrType =
408 T1->getAs<ObjCObjectPointerType>(),
409 *T2ObjCPtrType =
410 T2->getAs<ObjCObjectPointerType>();
411 if (T1ObjCPtrType) {
412 if (T2ObjCPtrType) {
413 T1 = T1ObjCPtrType->getPointeeType();
414 T2 = T2ObjCPtrType->getPointeeType();
415 return true;
416 }
417 else if (T2PtrType) {
418 T1 = T1ObjCPtrType->getPointeeType();
419 T2 = T2PtrType->getPointeeType();
420 return true;
421 }
422 }
423 else if (T2ObjCPtrType) {
424 if (T1PtrType) {
425 T2 = T2ObjCPtrType->getPointeeType();
426 T1 = T1PtrType->getPointeeType();
427 return true;
428 }
429 }
430
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000431 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
432 *T2MPType = T2->getAs<MemberPointerType>();
433 if (T1MPType && T2MPType) {
434 T1 = T1MPType->getPointeeType();
435 T2 = T2MPType->getPointeeType();
436 return true;
437 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000438
439 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
440 *T2BPType = T2->getAs<BlockPointerType>();
441 if (T1BPType && T2BPType) {
442 T1 = T1BPType->getPointeeType();
443 T2 = T2BPType->getPointeeType();
444 return true;
445 }
446
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000447 return false;
448}
449
Sebastian Redla5a77a62009-01-27 23:18:31 +0000450/// CastsAwayConstness - Check if the pointer conversion from SrcType to
451/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
452/// the cast checkers. Both arguments must denote pointer (possibly to member)
453/// types.
John McCall31168b02011-06-15 23:02:42 +0000454///
455/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
456///
457/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000458static bool
John McCall31168b02011-06-15 23:02:42 +0000459CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
460 bool CheckCVR, bool CheckObjCLifetime) {
461 // If the only checking we care about is for Objective-C lifetime qualifiers,
462 // and we're not in ARC mode, there's nothing to check.
463 if (!CheckCVR && CheckObjCLifetime &&
464 !Self.Context.getLangOptions().ObjCAutoRefCount)
465 return false;
466
Sebastian Redla5a77a62009-01-27 23:18:31 +0000467 // Casting away constness is defined in C++ 5.2.11p8 with reference to
468 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
469 // the rules are non-trivial. So first we construct Tcv *...cv* as described
470 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000471 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
472 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000473 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000474 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
475 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000476 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000477
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000478 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
479 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000481
Douglas Gregorb472e932011-04-15 17:59:54 +0000482 // Find the qualifiers. We only care about cvr-qualifiers for the
483 // purpose of this check, because other qualifiers (address spaces,
484 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000485 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000486 // Determine the relevant qualifiers at this level.
487 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000488 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000489 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000490
491 Qualifiers RetainedSrcQuals, RetainedDestQuals;
492 if (CheckCVR) {
493 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
494 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
495 }
496
497 if (CheckObjCLifetime &&
498 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
499 return true;
500
501 cv1.push_back(RetainedSrcQuals);
502 cv2.push_back(RetainedDestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000503 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000504 if (cv1.empty())
505 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000506
507 // Construct void pointers with those qualifiers (in reverse order of
508 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000509 QualType SrcConstruct = Self.Context.VoidTy;
510 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000511 ASTContext &Context = Self.Context;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000512 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall8ccfcb52009-09-24 19:53:00 +0000513 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000514 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000515 SrcConstruct
516 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
517 DestConstruct
518 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000519 }
520
521 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000522 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000523 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000524 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
525 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000526}
527
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000528/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
529/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
530/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000531void CastOperation::CheckDynamicCast() {
532 QualType OrigSrcType = SrcExpr.get()->getType();
533 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000534
535 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
536 // or "pointer to cv void".
537
538 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000539 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000540 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000541 if (DestPointer) {
542 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000543 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000544 DestPointee = DestReference->getPointeeType();
545 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000546 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000547 << this->DestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000548 return;
549 }
550
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000551 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000552 if (DestPointee->isVoidType()) {
553 assert(DestPointer && "Reference to void is not possible");
554 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000555 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000556 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000557 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000558 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000559 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000560 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000561 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000562 return;
563 }
564
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000565 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
566 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000567 // an lvalue of a complete class type, [...]. If T is an rvalue reference
568 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000569 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000570 QualType SrcPointee;
571 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000572 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000573 SrcPointee = SrcPointer->getPointeeType();
574 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000575 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000576 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000577 return;
578 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000579 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000580 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000581 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000582 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000583 }
584 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000585 } else {
586 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000587 }
588
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000589 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000590 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000591 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000592 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley01296292011-04-08 18:41:53 +0000593 << SrcExpr.get()->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000594 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000595 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000596 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000597 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000598 return;
599 }
600
601 assert((DestPointer || DestReference) &&
602 "Bad destination non-ptr/ref slipped through.");
603 assert((DestRecord || DestPointee->isVoidType()) &&
604 "Bad destination pointee slipped through.");
605 assert(SrcRecord && "Bad source pointee slipped through.");
606
607 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
608 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000609 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000610 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000611 return;
612 }
613
614 // C++ 5.2.7p3: If the type of v is the same as the required result type,
615 // [except for cv].
616 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000617 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000618 return;
619 }
620
621 // C++ 5.2.7p5
622 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000623 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000624 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
625 OpRange.getBegin(), OpRange,
626 &BasePath))
627 return;
628
John McCalle3027922010-08-25 11:45:40 +0000629 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000630
631 // If we are casting to or through a virtual base class, we need a
632 // vtable.
633 if (Self.BasePathInvolvesVirtualBase(BasePath))
634 Self.MarkVTableUsed(OpRange.getBegin(),
635 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000636 return;
637 }
638
639 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000640 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000641 assert(SrcDecl && "Definition missing");
642 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000643 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000644 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000645 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000646 Self.MarkVTableUsed(OpRange.getBegin(),
647 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000648
649 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000650 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000651}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000652
653/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
654/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
655/// like this:
656/// const char *str = "literal";
657/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000658void CastOperation::CheckConstCast() {
John McCall50a2c2c2011-10-11 23:14:30 +0000659 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000660 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
661 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
662 return;
663 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000664
665 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley01296292011-04-08 18:41:53 +0000666 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9f831db2009-07-25 15:41:38 +0000667 && msg != 0)
668 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000669 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000670}
671
672/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
673/// valid.
674/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
675/// like this:
676/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000677void CastOperation::CheckReinterpretCast() {
John McCall50a2c2c2011-10-11 23:14:30 +0000678 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000679 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
680 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
681 return;
682 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000683
684 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000685 TryCastResult tcr =
686 TryReinterpretCast(Self, SrcExpr, DestType,
687 /*CStyle*/false, OpRange, msg, Kind);
688 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000689 {
John Wiegley01296292011-04-08 18:41:53 +0000690 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
691 return;
692 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000693 //FIXME: &f<int>; is overloaded and resolvable
694 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000695 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000696 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000697 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000698
John McCall909acf82011-02-14 18:34:10 +0000699 } else {
John Wiegley01296292011-04-08 18:41:53 +0000700 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000701 }
John McCall31168b02011-06-15 23:02:42 +0000702 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb50451a2011-10-05 07:41:44 +0000703 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCall31168b02011-06-15 23:02:42 +0000704 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000705}
706
707
708/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
709/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
710/// implicit conversions explicit and getting rid of data loss warnings.
John McCallb50451a2011-10-05 07:41:44 +0000711void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000712 if (isPlaceholder()) {
713 checkNonOverloadPlaceholders();
714 if (SrcExpr.isInvalid())
715 return;
716 }
717
Sebastian Redl9f831db2009-07-25 15:41:38 +0000718 // This test is outside everything else because it's the only case where
719 // a non-lvalue-reference target type does not lead to decay.
720 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000721 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000722 Kind = CK_ToVoid;
723
724 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000725 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000726 false, // Decay Function to ptr
727 true, // Complain
728 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000729 if (SrcExpr.isInvalid())
730 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000731 }
John McCall9776e432011-10-06 23:25:11 +0000732
733 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000734 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000735 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000736
John McCall50a2c2c2011-10-11 23:14:30 +0000737 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
738 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley01296292011-04-08 18:41:53 +0000739 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
740 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
741 return;
742 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000743
744 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000745 TryCastResult tcr
746 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
747 Kind, BasePath);
748 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000749 if (SrcExpr.isInvalid())
750 return;
751 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
752 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000753 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000754 << oe->getName() << DestType << OpRange
755 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000756 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000757 } else {
John Wiegley01296292011-04-08 18:41:53 +0000758 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000759 }
John McCall31168b02011-06-15 23:02:42 +0000760 } else if (tcr == TC_Success) {
761 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000762 checkCastAlign();
763 if (Self.getLangOptions().ObjCAutoRefCount)
764 checkObjCARCConversion(Sema::CCK_OtherCast);
765 } else if (Kind == CK_BitCast) {
766 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000767 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000768}
769
770/// TryStaticCast - Check if a static cast can be performed, and do so if
771/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
772/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000773static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000774 QualType DestType,
775 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000776 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000777 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000778 CXXCastPath &BasePath) {
John McCall31168b02011-06-15 23:02:42 +0000779 // Determine whether we have the semantics of a C-style cast.
780 bool CStyle
781 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
782
Sebastian Redl9f831db2009-07-25 15:41:38 +0000783 // The order the tests is not entirely arbitrary. There is one conversion
784 // that can be handled in two different ways. Given:
785 // struct A {};
786 // struct B : public A {
787 // B(); B(const A&);
788 // };
789 // const A &a = B();
790 // the cast static_cast<const B&>(a) could be seen as either a static
791 // reference downcast, or an explicit invocation of the user-defined
792 // conversion using B's conversion constructor.
793 // DR 427 specifies that the downcast is to be applied here.
794
795 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
796 // Done outside this function.
797
798 TryCastResult tcr;
799
800 // C++ 5.2.9p5, reference downcast.
801 // See the function for details.
802 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley01296292011-04-08 18:41:53 +0000803 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000804 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000805 if (tcr != TC_NotApplicable)
806 return tcr;
807
Douglas Gregor465184a2011-01-22 00:06:57 +0000808 // C++0x [expr.static.cast]p3:
809 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
810 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley01296292011-04-08 18:41:53 +0000811 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregorce950842011-01-26 21:04:06 +0000812 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000813 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000814 return tcr;
815
816 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
817 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000818 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000819 Kind);
John Wiegley01296292011-04-08 18:41:53 +0000820 if (SrcExpr.isInvalid())
821 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000822 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000823 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000824
Sebastian Redl9f831db2009-07-25 15:41:38 +0000825 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
826 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
827 // conversions, subject to further restrictions.
828 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
829 // of qualification conversions impossible.
830 // In the CStyle case, the earlier attempt to const_cast should have taken
831 // care of reverse qualification conversions.
832
John Wiegley01296292011-04-08 18:41:53 +0000833 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000834
Douglas Gregor0bf31402010-10-08 23:50:27 +0000835 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000836 // converted to an integral type. [...] A value of a scoped enumeration type
837 // can also be explicitly converted to a floating-point type [...].
838 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
839 if (Enum->getDecl()->isScoped()) {
840 if (DestType->isBooleanType()) {
841 Kind = CK_IntegralToBoolean;
842 return TC_Success;
843 } else if (DestType->isIntegralType(Self.Context)) {
844 Kind = CK_IntegralCast;
845 return TC_Success;
846 } else if (DestType->isRealFloatingType()) {
847 Kind = CK_IntegralToFloating;
848 return TC_Success;
849 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000850 }
851 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000852
Sebastian Redl9f831db2009-07-25 15:41:38 +0000853 // Reverse integral promotion/conversion. All such conversions are themselves
854 // again integral promotions or conversions and are thus already handled by
855 // p2 (TryDirectInitialization above).
856 // (Note: any data loss warnings should be suppressed.)
857 // The exception is the reverse of enum->integer, i.e. integer->enum (and
858 // enum->enum). See also C++ 5.2.9p7.
859 // The same goes for reverse floating point promotion/conversion and
860 // floating-integral conversions. Again, only floating->enum is relevant.
861 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +0000862 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +0000863 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000864 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +0000865 } else if (SrcType->isRealFloatingType()) {
866 Kind = CK_FloatingToIntegral;
867 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000868 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000869 }
870
871 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
872 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000873 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000874 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000875 if (tcr != TC_NotApplicable)
876 return tcr;
877
878 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
879 // conversion. C++ 5.2.9p9 has additional information.
880 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000881 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000882 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000883 if (tcr != TC_NotApplicable)
884 return tcr;
885
886 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
887 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
888 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000889 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000890 QualType SrcPointee = SrcPointer->getPointeeType();
891 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000892 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000893 QualType DestPointee = DestPointer->getPointeeType();
894 if (DestPointee->isIncompleteOrObjectType()) {
895 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +0000896 // to a qualifier violation. Note that we permit Objective-C lifetime
897 // and GC qualifier mismatches here.
898 if (!CStyle) {
899 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
900 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
901 DestPointeeQuals.removeObjCGCAttr();
902 DestPointeeQuals.removeObjCLifetime();
903 SrcPointeeQuals.removeObjCGCAttr();
904 SrcPointeeQuals.removeObjCLifetime();
905 if (DestPointeeQuals != SrcPointeeQuals &&
906 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
907 msg = diag::err_bad_cxx_cast_qualifiers_away;
908 return TC_Failed;
909 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000910 }
John McCalle3027922010-08-25 11:45:40 +0000911 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000912 return TC_Success;
913 }
914 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000915 else if (DestType->isObjCObjectPointerType()) {
916 // allow both c-style cast and static_cast of objective-c pointers as
917 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +0000918 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000919 return TC_Success;
920 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000921 else if (CStyle && DestType->isBlockPointerType()) {
922 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000923 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000924 return TC_Success;
925 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000926 }
927 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000928 // Allow arbitray objective-c pointer conversion with static casts.
929 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000930 DestType->isObjCObjectPointerType()) {
931 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000932 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000933 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000934
Sebastian Redl9f831db2009-07-25 15:41:38 +0000935 // We tried everything. Everything! Nothing works! :-(
936 return TC_NotApplicable;
937}
938
939/// Tests whether a conversion according to N2844 is valid.
940TryCastResult
941TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000942 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
943 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000944 // C++0x [expr.static.cast]p3:
945 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
946 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000947 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000948 if (!R)
949 return TC_NotApplicable;
950
Douglas Gregor465184a2011-01-22 00:06:57 +0000951 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000952 return TC_NotApplicable;
953
954 // Because we try the reference downcast before this function, from now on
955 // this is the only cast possibility, so we issue an error if we fail now.
956 // FIXME: Should allow casting away constness if CStyle.
957 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000958 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +0000959 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000960 QualType FromType = SrcExpr->getType();
961 QualType ToType = R->getPointeeType();
962 if (CStyle) {
963 FromType = FromType.getUnqualifiedType();
964 ToType = ToType.getUnqualifiedType();
965 }
966
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000967 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000968 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +0000969 DerivedToBase, ObjCConversion,
970 ObjCLifetimeConversion)
971 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000972 msg = diag::err_bad_lvalue_to_rvalue_cast;
973 return TC_Failed;
974 }
975
Douglas Gregorba278e22011-01-25 16:13:26 +0000976 if (DerivedToBase) {
977 Kind = CK_DerivedToBase;
978 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
979 /*DetectVirtual=*/true);
980 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
981 return TC_NotApplicable;
982
983 Self.BuildBasePathArray(Paths, BasePath);
984 } else
985 Kind = CK_NoOp;
986
Sebastian Redl9f831db2009-07-25 15:41:38 +0000987 return TC_Success;
988}
989
990/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
991TryCastResult
992TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
993 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000994 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000995 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000996 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
997 // cast to type "reference to cv2 D", where D is a class derived from B,
998 // if a valid standard conversion from "pointer to D" to "pointer to B"
999 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1000 // In addition, DR54 clarifies that the base must be accessible in the
1001 // current context. Although the wording of DR54 only applies to the pointer
1002 // variant of this rule, the intent is clearly for it to apply to the this
1003 // conversion as well.
1004
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001005 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001006 if (!DestReference) {
1007 return TC_NotApplicable;
1008 }
1009 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001010 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001011 // We know the left side is an lvalue reference, so we can suggest a reason.
1012 msg = diag::err_bad_cxx_cast_rvalue;
1013 return TC_NotApplicable;
1014 }
1015
1016 QualType DestPointee = DestReference->getPointeeType();
1017
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001018 return TryStaticDowncast(Self,
1019 Self.Context.getCanonicalType(SrcExpr->getType()),
1020 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001021 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1022 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001023}
1024
1025/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1026TryCastResult
1027TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001028 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001029 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001030 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001031 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1032 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1033 // is a class derived from B, if a valid standard conversion from "pointer
1034 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1035 // class of D.
1036 // In addition, DR54 clarifies that the base must be accessible in the
1037 // current context.
1038
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001039 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001040 if (!DestPointer) {
1041 return TC_NotApplicable;
1042 }
1043
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001044 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001045 if (!SrcPointer) {
1046 msg = diag::err_bad_static_cast_pointer_nonpointer;
1047 return TC_NotApplicable;
1048 }
1049
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001050 return TryStaticDowncast(Self,
1051 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1052 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001053 CStyle, OpRange, SrcType, DestType, msg, Kind,
1054 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001055}
1056
1057/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1058/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001059/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001060TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001061TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001062 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001063 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001064 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001065 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +00001066 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1067 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001068 return TC_NotApplicable;
1069
Sebastian Redl9f831db2009-07-25 15:41:38 +00001070 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001071 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001072 return TC_NotApplicable;
1073 }
1074
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001075 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001076 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001077 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1078 return TC_NotApplicable;
1079 }
1080
1081 // Target type does derive from source type. Now we're serious. If an error
1082 // appears now, it's not ignored.
1083 // This may not be entirely in line with the standard. Take for example:
1084 // struct A {};
1085 // struct B : virtual A {
1086 // B(A&);
1087 // };
Mike Stump11289f42009-09-09 15:08:12 +00001088 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001089 // void f()
1090 // {
1091 // (void)static_cast<const B&>(*((A*)0));
1092 // }
1093 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1094 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1095 // However, both GCC and Comeau reject this example, and accepting it would
1096 // mean more complex code if we're to preserve the nice error message.
1097 // FIXME: Being 100% compliant here would be nice to have.
1098
1099 // Must preserve cv, as always, unless we're in C-style mode.
1100 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001101 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001102 return TC_Failed;
1103 }
1104
1105 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1106 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1107 // that it builds the paths in reverse order.
1108 // To sum up: record all paths to the base and build a nice string from
1109 // them. Use it to spice up the error message.
1110 if (!Paths.isRecordingPaths()) {
1111 Paths.clear();
1112 Paths.setRecordingPaths(true);
1113 Self.IsDerivedFrom(DestType, SrcType, Paths);
1114 }
1115 std::string PathDisplayStr;
1116 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001117 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001118 PI != PE; ++PI) {
1119 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1120 // We haven't displayed a path to this particular base
1121 // class subobject yet.
1122 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001123 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1124 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001125 EI != EE; ++EI)
1126 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001127 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001128 }
1129 }
1130
1131 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001132 << QualType(SrcType).getUnqualifiedType()
1133 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001134 << PathDisplayStr << OpRange;
1135 msg = 0;
1136 return TC_Failed;
1137 }
1138
1139 if (Paths.getDetectedVirtual() != 0) {
1140 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1141 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1142 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1143 msg = 0;
1144 return TC_Failed;
1145 }
1146
John McCallfe9cf0a2011-02-14 23:21:33 +00001147 if (!CStyle) {
1148 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1149 SrcType, DestType,
1150 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001151 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001152 case Sema::AR_accessible:
1153 case Sema::AR_delayed: // be optimistic
1154 case Sema::AR_dependent: // be optimistic
1155 break;
1156
1157 case Sema::AR_inaccessible:
1158 msg = 0;
1159 return TC_Failed;
1160 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001161 }
1162
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001163 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001164 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001165 return TC_Success;
1166}
1167
1168/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1169/// C++ 5.2.9p9 is valid:
1170///
1171/// An rvalue of type "pointer to member of D of type cv1 T" can be
1172/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1173/// where B is a base class of D [...].
1174///
1175TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001176TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001177 QualType DestType, bool CStyle,
1178 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001179 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001180 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001181 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001182 if (!DestMemPtr)
1183 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001184
1185 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001186 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001187 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001188 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001189 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001190 FoundOverload)) {
1191 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1192 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1193 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1194 WasOverloadedFunction = true;
1195 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001196 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001197
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001198 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001199 if (!SrcMemPtr) {
1200 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1201 return TC_NotApplicable;
1202 }
1203
1204 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001205 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1206 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001207 return TC_NotApplicable;
1208
1209 // B base of D
1210 QualType SrcClass(SrcMemPtr->getClass(), 0);
1211 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001212 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001213 /*DetectVirtual=*/true);
1214 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1215 return TC_NotApplicable;
1216 }
1217
1218 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +00001219 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001220 Paths.clear();
1221 Paths.setRecordingPaths(true);
1222 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1223 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001224 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001225 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1226 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1227 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1228 msg = 0;
1229 return TC_Failed;
1230 }
1231
1232 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1233 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1234 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1235 msg = 0;
1236 return TC_Failed;
1237 }
1238
John McCallfe9cf0a2011-02-14 23:21:33 +00001239 if (!CStyle) {
1240 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1241 DestClass, SrcClass,
1242 Paths.front(),
1243 diag::err_upcast_to_inaccessible_base)) {
1244 case Sema::AR_accessible:
1245 case Sema::AR_delayed:
1246 case Sema::AR_dependent:
1247 // Optimistically assume that the delayed and dependent cases
1248 // will work out.
1249 break;
1250
1251 case Sema::AR_inaccessible:
1252 msg = 0;
1253 return TC_Failed;
1254 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001255 }
1256
Douglas Gregorc934bc82010-03-07 23:24:59 +00001257 if (WasOverloadedFunction) {
1258 // Resolve the address of the overloaded function again, this time
1259 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001260 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001261 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001262 true,
1263 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001264 if (!Fn) {
1265 msg = 0;
1266 return TC_Failed;
1267 }
1268
John McCall16df1e52010-03-30 21:47:33 +00001269 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001270 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001271 msg = 0;
1272 return TC_Failed;
1273 }
1274 }
1275
Anders Carlssonb78feca2010-04-24 19:22:20 +00001276 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001277 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001278 return TC_Success;
1279}
1280
1281/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1282/// is valid:
1283///
1284/// An expression e can be explicitly converted to a type T using a
1285/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1286TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001287TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001288 Sema::CheckedConversionKind CCK,
1289 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001290 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001291 if (DestType->isRecordType()) {
1292 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1293 diag::err_bad_dynamic_cast_incomplete)) {
1294 msg = 0;
1295 return TC_Failed;
1296 }
1297 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001298
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001299 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1300 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001301 = (CCK == Sema::CCK_CStyleCast)
1302 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1303 : (CCK == Sema::CCK_FunctionalCast)
1304 ? InitializationKind::CreateFunctionalCast(OpRange)
1305 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001306 Expr *SrcExprRaw = SrcExpr.get();
1307 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001308
1309 // At this point of CheckStaticCast, if the destination is a reference,
1310 // or the expression is an overload expression this has to work.
1311 // There is no other way that works.
1312 // On the other hand, if we're checking a C-style cast, we've still got
1313 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001314 bool CStyle
1315 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001316 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001317 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001318
John McCalldadc5752010-08-24 06:29:42 +00001319 ExprResult Result
John Wiegley01296292011-04-08 18:41:53 +00001320 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001321 if (Result.isInvalid()) {
1322 msg = 0;
1323 return TC_Failed;
1324 }
1325
Douglas Gregorb33eed02010-04-16 22:09:46 +00001326 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001327 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001328 else
John McCalle3027922010-08-25 11:45:40 +00001329 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001330
John Wiegley01296292011-04-08 18:41:53 +00001331 SrcExpr = move(Result);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001332 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001333}
1334
1335/// TryConstCast - See if a const_cast from source to destination is allowed,
1336/// and perform it if it is.
1337static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1338 bool CStyle, unsigned &msg) {
1339 DestType = Self.Context.getCanonicalType(DestType);
1340 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001341 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1342 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001343 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1344 // is C-style, static_cast might find a way, so we simply suggest a
1345 // message and tell the parent to keep searching.
1346 msg = diag::err_bad_cxx_cast_rvalue;
1347 return TC_NotApplicable;
1348 }
1349
1350 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1351 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1352 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1353 SrcType = Self.Context.getPointerType(SrcType);
1354 }
1355
1356 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1357 // the rules for const_cast are the same as those used for pointers.
1358
John McCall0e704f72010-05-18 09:35:29 +00001359 if (!DestType->isPointerType() &&
1360 !DestType->isMemberPointerType() &&
1361 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001362 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1363 // was a reference type, we converted it to a pointer above.
1364 // The status of rvalue references isn't entirely clear, but it looks like
1365 // conversion to them is simply invalid.
1366 // C++ 5.2.11p3: For two pointer types [...]
1367 if (!CStyle)
1368 msg = diag::err_bad_const_cast_dest;
1369 return TC_NotApplicable;
1370 }
1371 if (DestType->isFunctionPointerType() ||
1372 DestType->isMemberFunctionPointerType()) {
1373 // Cannot cast direct function pointers.
1374 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1375 // T is the ultimate pointee of source and target type.
1376 if (!CStyle)
1377 msg = diag::err_bad_const_cast_dest;
1378 return TC_NotApplicable;
1379 }
1380 SrcType = Self.Context.getCanonicalType(SrcType);
1381
1382 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1383 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001384 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1385 // in multi-level pointers may change, but the level count must be the same,
1386 // as must be the final pointee type.
1387 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001388 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001389 Qualifiers SrcQuals, DestQuals;
1390 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1391 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1392
1393 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1394 // the other qualifiers (e.g., address spaces) are identical.
1395 SrcQuals.removeCVRQualifiers();
1396 DestQuals.removeCVRQualifiers();
1397 if (SrcQuals != DestQuals)
1398 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001399 }
1400
1401 // Since we're dealing in canonical types, the remainder must be the same.
1402 if (SrcType != DestType)
1403 return TC_NotApplicable;
1404
1405 return TC_Success;
1406}
1407
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001408// Checks for undefined behavior in reinterpret_cast.
1409// The cases that is checked for is:
1410// *reinterpret_cast<T*>(&a)
1411// reinterpret_cast<T&>(a)
1412// where accessing 'a' as type 'T' will result in undefined behavior.
1413void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1414 bool IsDereference,
1415 SourceRange Range) {
1416 unsigned DiagID = IsDereference ?
1417 diag::warn_pointer_indirection_from_incompatible_type :
1418 diag::warn_undefined_reinterpret_cast;
1419
1420 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikie9c902b52011-09-25 23:23:43 +00001421 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001422 return;
1423 }
1424
1425 QualType SrcTy, DestTy;
1426 if (IsDereference) {
1427 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1428 return;
1429 }
1430 SrcTy = SrcType->getPointeeType();
1431 DestTy = DestType->getPointeeType();
1432 } else {
1433 if (!DestType->getAs<ReferenceType>()) {
1434 return;
1435 }
1436 SrcTy = SrcType;
1437 DestTy = DestType->getPointeeType();
1438 }
1439
1440 // Cast is compatible if the types are the same.
1441 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1442 return;
1443 }
1444 // or one of the types is a char or void type
1445 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1446 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1447 return;
1448 }
1449 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001450 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001451 return;
1452 }
1453
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001454 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001455 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1456 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1457 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1458 return;
1459 }
1460 }
1461
1462 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1463}
Douglas Gregor1beec452011-03-12 01:48:56 +00001464
John Wiegley01296292011-04-08 18:41:53 +00001465static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001466 QualType DestType, bool CStyle,
1467 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001468 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001469 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001470 bool IsLValueCast = false;
1471
Sebastian Redl9f831db2009-07-25 15:41:38 +00001472 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001473 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001474
1475 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001476 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1477 if (SrcType == Self.Context.OverloadTy) {
John McCall50a2c2c2011-10-11 23:14:30 +00001478 // ... unless foo<int> resolves to an lvalue unambiguously.
1479 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1480 // like it?
1481 ExprResult SingleFunctionExpr = SrcExpr;
1482 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1483 SingleFunctionExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001484 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall50a2c2c2011-10-11 23:14:30 +00001485 ) && SingleFunctionExpr.isUsable()) {
John Wiegley01296292011-04-08 18:41:53 +00001486 SrcExpr = move(SingleFunctionExpr);
1487 SrcType = SrcExpr.get()->getType();
John McCall50a2c2c2011-10-11 23:14:30 +00001488 } else {
Douglas Gregorb491ed32011-02-19 21:32:49 +00001489 return TC_NotApplicable;
John McCall50a2c2c2011-10-11 23:14:30 +00001490 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001491 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001492
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001493 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001494 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00001495 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001496 // Cannot cast non-lvalue to lvalue reference type. See the similar
1497 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001498 msg = diag::err_bad_cxx_cast_rvalue;
1499 return TC_NotApplicable;
1500 }
1501
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001502 if (!CStyle) {
1503 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1504 /*isDereference=*/false, OpRange);
1505 }
1506
Sebastian Redl9f831db2009-07-25 15:41:38 +00001507 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1508 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1509 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001510
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001511 const char *inappropriate = 0;
1512 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001513 case OK_Ordinary:
1514 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001515 case OK_BitField: inappropriate = "bit-field"; break;
1516 case OK_VectorComponent: inappropriate = "vector element"; break;
1517 case OK_ObjCProperty: inappropriate = "property expression"; break;
1518 }
1519 if (inappropriate) {
1520 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1521 << inappropriate << DestType
1522 << OpRange << SrcExpr.get()->getSourceRange();
1523 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001524 return TC_NotApplicable;
1525 }
1526
Sebastian Redl9f831db2009-07-25 15:41:38 +00001527 // This code does this transformation for the checked types.
1528 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1529 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001530
Douglas Gregor51954272010-07-13 23:17:26 +00001531 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001532 }
1533
1534 // Canonicalize source for comparison.
1535 SrcType = Self.Context.getCanonicalType(SrcType);
1536
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001537 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1538 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001539 if (DestMemPtr && SrcMemPtr) {
1540 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1541 // can be explicitly converted to an rvalue of type "pointer to member
1542 // of Y of type T2" if T1 and T2 are both function types or both object
1543 // types.
1544 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1545 SrcMemPtr->getPointeeType()->isFunctionType())
1546 return TC_NotApplicable;
1547
1548 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1549 // constness.
1550 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1551 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001552 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1553 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001554 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001555 return TC_Failed;
1556 }
1557
Charles Davisebab1ed2010-08-16 05:30:44 +00001558 // Don't allow casting between member pointers of different sizes.
1559 if (Self.Context.getTypeSize(DestMemPtr) !=
1560 Self.Context.getTypeSize(SrcMemPtr)) {
1561 msg = diag::err_bad_cxx_cast_member_pointer_size;
1562 return TC_Failed;
1563 }
1564
Sebastian Redl9f831db2009-07-25 15:41:38 +00001565 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001566 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001567 return TC_Success;
1568 }
1569
1570 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001571 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001572 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1573 // type large enough to hold it. A value of std::nullptr_t can be
1574 // converted to an integral type; the conversion has the same meaning
1575 // and validity as a conversion of (void*)0 to the integral type.
1576 if (Self.Context.getTypeSize(SrcType) >
1577 Self.Context.getTypeSize(DestType)) {
1578 msg = diag::err_bad_reinterpret_cast_small_int;
1579 return TC_Failed;
1580 }
John McCalle3027922010-08-25 11:45:40 +00001581 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001582 return TC_Success;
1583 }
1584
Anders Carlsson570af5d2009-09-16 19:19:43 +00001585 bool destIsVector = DestType->isVectorType();
1586 bool srcIsVector = SrcType->isVectorType();
1587 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001588 // FIXME: Should this also apply to floating point types?
1589 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1590 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001591
1592 // Check if this is a cast between a vector and something else.
1593 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1594 !(srcIsVector && destIsVector))
1595 return TC_NotApplicable;
1596
1597 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001598 if (Self.Context.getTypeSize(SrcType)
1599 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001600 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001601 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001602 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001603
1604 if (destIsScalar)
1605 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1606 else if (srcIsScalar)
1607 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1608 else
1609 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1610
1611 return TC_Failed;
1612 }
1613
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001614 bool destIsPtr = DestType->isAnyPointerType() ||
1615 DestType->isBlockPointerType();
1616 bool srcIsPtr = SrcType->isAnyPointerType() ||
1617 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001618 if (!destIsPtr && !srcIsPtr) {
1619 // Except for std::nullptr_t->integer and lvalue->reference, which are
1620 // handled above, at least one of the two arguments must be a pointer.
1621 return TC_NotApplicable;
1622 }
1623
1624 if (SrcType == DestType) {
1625 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1626 // restrictions, a cast to the same type is allowed. The intent is not
1627 // entirely clear here, since all other paragraphs explicitly forbid casts
1628 // to the same type. However, the behavior of compilers is pretty consistent
1629 // on this point: allow same-type conversion if the involved types are
1630 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001631 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001632 return TC_Success;
1633 }
1634
Douglas Gregor6972a622010-06-16 00:35:25 +00001635 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001636 assert(srcIsPtr && "One type must be a pointer");
1637 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001638 // type large enough to hold it; except in Microsoft mode, where the
1639 // integral type size doesn't matter.
1640 if ((Self.Context.getTypeSize(SrcType) >
1641 Self.Context.getTypeSize(DestType)) &&
Francois Pichet0706d202011-09-17 17:15:52 +00001642 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001643 msg = diag::err_bad_reinterpret_cast_small_int;
1644 return TC_Failed;
1645 }
John McCalle3027922010-08-25 11:45:40 +00001646 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001647 return TC_Success;
1648 }
1649
Douglas Gregorb90df602010-06-16 00:17:44 +00001650 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001651 assert(destIsPtr && "One type must be a pointer");
1652 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1653 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001654 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1655 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001656 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001657 return TC_Success;
1658 }
1659
1660 if (!destIsPtr || !srcIsPtr) {
1661 // With the valid non-pointer conversions out of the way, we can be even
1662 // more stringent.
1663 return TC_NotApplicable;
1664 }
1665
1666 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1667 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001668 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1669 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001670 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001671 return TC_Failed;
1672 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001673
1674 // Cannot convert between block pointers and Objective-C object pointers.
1675 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1676 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1677 return TC_NotApplicable;
1678
John McCall9320b872011-09-09 05:25:32 +00001679 if (IsLValueCast) {
1680 Kind = CK_LValueBitCast;
1681 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001682 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001683 } else if (DestType->isBlockPointerType()) {
1684 if (!SrcType->isBlockPointerType()) {
1685 Kind = CK_AnyPointerToBlockPointerCast;
1686 } else {
1687 Kind = CK_BitCast;
1688 }
1689 } else {
1690 Kind = CK_BitCast;
1691 }
1692
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001693 // Any pointer can be cast to an Objective-C pointer type with a C-style
1694 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001695 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001696 return TC_Success;
1697 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001698
Sebastian Redl9f831db2009-07-25 15:41:38 +00001699 // Not casting away constness, so the only remaining check is for compatible
1700 // pointer categories.
1701
1702 if (SrcType->isFunctionPointerType()) {
1703 if (DestType->isFunctionPointerType()) {
1704 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1705 // a pointer to a function of a different type.
1706 return TC_Success;
1707 }
1708
1709 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1710 // an object type or vice versa is conditionally-supported.
1711 // Compilers support it in C++03 too, though, because it's necessary for
1712 // casting the return value of dlsym() and GetProcAddress().
1713 // FIXME: Conditionally-supported behavior should be configurable in the
1714 // TargetInfo or similar.
1715 if (!Self.getLangOptions().CPlusPlus0x)
1716 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1717 return TC_Success;
1718 }
1719
1720 if (DestType->isFunctionPointerType()) {
1721 // See above.
1722 if (!Self.getLangOptions().CPlusPlus0x)
1723 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1724 return TC_Success;
1725 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001726
Sebastian Redl9f831db2009-07-25 15:41:38 +00001727 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1728 // a pointer to an object of different type.
1729 // Void pointers are not specified, but supported by every compiler out there.
1730 // So we finish by allowing everything that remains - it's got to be two
1731 // object pointers.
1732 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001733}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001734
John McCall9776e432011-10-06 23:25:11 +00001735void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
1736 // Handle placeholders.
1737 if (isPlaceholder()) {
1738 // C-style casts can resolve __unknown_any types.
1739 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1740 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1741 SrcExpr.get(), Kind,
1742 ValueKind, BasePath);
1743 return;
1744 }
John McCallb50451a2011-10-05 07:41:44 +00001745
John McCall9776e432011-10-06 23:25:11 +00001746 checkNonOverloadPlaceholders();
1747 if (SrcExpr.isInvalid())
1748 return;
John McCalla072f5d2011-10-17 17:42:19 +00001749 }
John McCall9776e432011-10-06 23:25:11 +00001750
1751 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00001752 // This test is outside everything else because it's the only case where
1753 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00001754 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00001755 Kind = CK_ToVoid;
1756
John McCall9776e432011-10-06 23:25:11 +00001757 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001758 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1759 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00001760 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00001761 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00001762 if (SrcExpr.isInvalid())
1763 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001764 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001765
John McCall9776e432011-10-06 23:25:11 +00001766 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1767 if (SrcExpr.isInvalid())
John McCallb50451a2011-10-05 07:41:44 +00001768 return;
John McCallb50451a2011-10-05 07:41:44 +00001769
1770 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00001771 }
1772
Sebastian Redl9f831db2009-07-25 15:41:38 +00001773 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb50451a2011-10-05 07:41:44 +00001774 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1775 assert(Kind == CK_Dependent);
1776 return;
John McCall8cb679e2010-11-15 09:13:47 +00001777 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00001778
John McCall50a2c2c2011-10-11 23:14:30 +00001779 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1780 !isPlaceholder(BuiltinType::Overload)) {
John McCallb50451a2011-10-05 07:41:44 +00001781 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1782 if (SrcExpr.isInvalid())
1783 return;
John Wiegley01296292011-04-08 18:41:53 +00001784 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001785
John McCall3aef3d82011-04-10 19:13:55 +00001786 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00001787 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00001788 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00001789 && (SrcExpr.get()->getType()->isIntegerType()
1790 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00001791 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00001792 return;
John McCall3aef3d82011-04-10 19:13:55 +00001793 }
1794
Sebastian Redl9f831db2009-07-25 15:41:38 +00001795 // C++ [expr.cast]p5: The conversions performed by
1796 // - a const_cast,
1797 // - a static_cast,
1798 // - a static_cast followed by a const_cast,
1799 // - a reinterpret_cast, or
1800 // - a reinterpret_cast followed by a const_cast,
1801 // can be performed using the cast notation of explicit type conversion.
1802 // [...] If a conversion can be interpreted in more than one of the ways
1803 // listed above, the interpretation that appears first in the list is used,
1804 // even if a cast resulting from that interpretation is ill-formed.
1805 // In plain language, this means trying a const_cast ...
1806 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb50451a2011-10-05 07:41:44 +00001807 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1808 /*CStyle*/true, msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001809 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001810 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001811
John McCall31168b02011-06-15 23:02:42 +00001812 Sema::CheckedConversionKind CCK
1813 = FunctionalStyle? Sema::CCK_FunctionalCast
1814 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001815 if (tcr == TC_NotApplicable) {
1816 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00001817 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1818 msg, Kind, BasePath);
1819 if (SrcExpr.isInvalid())
1820 return;
1821
Sebastian Redl9f831db2009-07-25 15:41:38 +00001822 if (tcr == TC_NotApplicable) {
1823 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00001824 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1825 OpRange, msg, Kind);
1826 if (SrcExpr.isInvalid())
1827 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001828 }
1829 }
1830
John McCallb50451a2011-10-05 07:41:44 +00001831 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1832 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00001833
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001834 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00001835 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001836 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00001837 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1838 DestType,
1839 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001840 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001841
Richard Trieu70d14f52011-04-16 01:09:30 +00001842 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001843 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001844
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001845 } else {
John McCallb50451a2011-10-05 07:41:44 +00001846 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1847 OpRange, SrcExpr.get(), DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001848 }
John McCallb50451a2011-10-05 07:41:44 +00001849 } else if (Kind == CK_BitCast) {
1850 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001851 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001852
John McCallb50451a2011-10-05 07:41:44 +00001853 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00001854 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00001855 SrcExpr = ExprError();
1856}
1857
John McCall9776e432011-10-06 23:25:11 +00001858/// Check the semantics of a C-style cast operation, in C.
1859void CastOperation::CheckCStyleCast() {
1860 assert(!Self.getLangOptions().CPlusPlus);
1861
John McCall4124c492011-10-17 18:40:02 +00001862 // C-style casts can resolve __unknown_any types.
1863 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1864 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1865 SrcExpr.get(), Kind,
1866 ValueKind, BasePath);
1867 return;
1868 }
John McCall9776e432011-10-06 23:25:11 +00001869
1870 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1871 // type needs to be scalar.
1872 if (DestType->isVoidType()) {
1873 // We don't necessarily do lvalue-to-rvalue conversions on this.
1874 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1875 if (SrcExpr.isInvalid())
1876 return;
1877
1878 // Cast to void allows any expr type.
1879 Kind = CK_ToVoid;
1880 return;
1881 }
1882
1883 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1884 if (SrcExpr.isInvalid())
1885 return;
1886 QualType SrcType = SrcExpr.get()->getType();
John McCall4124c492011-10-17 18:40:02 +00001887 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00001888
1889 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1890 diag::err_typecheck_cast_to_incomplete)) {
1891 SrcExpr = ExprError();
1892 return;
1893 }
1894
1895 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1896 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1897
1898 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1899 // GCC struct/union extension: allow cast to self.
1900 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1901 << DestType << SrcExpr.get()->getSourceRange();
1902 Kind = CK_NoOp;
1903 return;
1904 }
1905
1906 // GCC's cast to union extension.
1907 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1908 RecordDecl *RD = DestRecordTy->getDecl();
1909 RecordDecl::field_iterator Field, FieldEnd;
1910 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1911 Field != FieldEnd; ++Field) {
1912 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1913 !Field->isUnnamedBitfield()) {
1914 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1915 << SrcExpr.get()->getSourceRange();
1916 break;
1917 }
1918 }
1919 if (Field == FieldEnd) {
1920 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1921 << SrcType << SrcExpr.get()->getSourceRange();
1922 SrcExpr = ExprError();
1923 return;
1924 }
1925 Kind = CK_ToUnion;
1926 return;
1927 }
1928
1929 // Reject any other conversions to non-scalar types.
1930 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1931 << DestType << SrcExpr.get()->getSourceRange();
1932 SrcExpr = ExprError();
1933 return;
1934 }
1935
1936 // The type we're casting to is known to be a scalar or vector.
1937
1938 // Require the operand to be a scalar or vector.
1939 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1940 Self.Diag(SrcExpr.get()->getExprLoc(),
1941 diag::err_typecheck_expect_scalar_operand)
1942 << SrcType << SrcExpr.get()->getSourceRange();
1943 SrcExpr = ExprError();
1944 return;
1945 }
1946
1947 if (DestType->isExtVectorType()) {
1948 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1949 return;
1950 }
1951
1952 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1953 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1954 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1955 Kind = CK_VectorSplat;
1956 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1957 SrcExpr = ExprError();
1958 }
1959 return;
1960 }
1961
1962 if (SrcType->isVectorType()) {
1963 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1964 SrcExpr = ExprError();
1965 return;
1966 }
1967
1968 // The source and target types are both scalars, i.e.
1969 // - arithmetic types (fundamental, enum, and complex)
1970 // - all kinds of pointers
1971 // Note that member pointers were filtered out with C++, above.
1972
1973 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
1974 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
1975 SrcExpr = ExprError();
1976 return;
1977 }
1978
1979 // If either type is a pointer, the other type has to be either an
1980 // integer or a pointer.
1981 if (!DestType->isArithmeticType()) {
1982 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
1983 Self.Diag(SrcExpr.get()->getExprLoc(),
1984 diag::err_cast_pointer_from_non_pointer_int)
1985 << SrcType << SrcExpr.get()->getSourceRange();
1986 SrcExpr = ExprError();
1987 return;
1988 }
1989 } else if (!SrcType->isArithmeticType()) {
1990 if (!DestType->isIntegralType(Self.Context) &&
1991 DestType->isArithmeticType()) {
1992 Self.Diag(SrcExpr.get()->getLocStart(),
1993 diag::err_cast_pointer_to_non_pointer_int)
1994 << SrcType << SrcExpr.get()->getSourceRange();
1995 SrcExpr = ExprError();
1996 return;
1997 }
1998 }
1999
2000 // ARC imposes extra restrictions on casts.
2001 if (Self.getLangOptions().ObjCAutoRefCount) {
2002 checkObjCARCConversion(Sema::CCK_CStyleCast);
2003 if (SrcExpr.isInvalid())
2004 return;
2005
2006 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2007 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2008 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2009 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2010 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2011 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2012 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2013 Self.Diag(SrcExpr.get()->getLocStart(),
2014 diag::err_typecheck_incompatible_ownership)
2015 << SrcType << DestType << Sema::AA_Casting
2016 << SrcExpr.get()->getSourceRange();
2017 return;
2018 }
2019 }
2020 }
2021 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2022 Self.Diag(SrcExpr.get()->getLocStart(),
2023 diag::err_arc_convesion_of_weak_unavailable)
2024 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2025 SrcExpr = ExprError();
2026 return;
2027 }
2028 }
2029
2030 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2031 if (SrcExpr.isInvalid())
2032 return;
2033
2034 if (Kind == CK_BitCast)
2035 checkCastAlign();
2036}
2037
2038ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2039 TypeSourceInfo *CastTypeInfo,
2040 SourceLocation RPLoc,
2041 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002042 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2043 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2044 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2045
John McCall9776e432011-10-06 23:25:11 +00002046 if (getLangOptions().CPlusPlus) {
2047 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false);
2048 } else {
2049 Op.CheckCStyleCast();
2050 }
2051
John McCallb50451a2011-10-05 07:41:44 +00002052 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002053 return ExprError();
2054
John McCall4124c492011-10-17 18:40:02 +00002055 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2056 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2057 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002058}
2059
2060ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2061 SourceLocation LPLoc,
2062 Expr *CastExpr,
2063 SourceLocation RPLoc) {
2064 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2065 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2066 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2067
John McCall9776e432011-10-06 23:25:11 +00002068 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true);
John McCallb50451a2011-10-05 07:41:44 +00002069 if (Op.SrcExpr.isInvalid())
2070 return ExprError();
2071
John McCall4124c492011-10-17 18:40:02 +00002072 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2073 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2074 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002075}