SemaCast.cpp revision 41f4431f3989ff23029eaf2ad947f07e39fb268c
1//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// 2// 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// 10// 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)' 14// 15//===----------------------------------------------------------------------===// 16 17#include "clang/Sema/SemaInternal.h" 18#include "clang/Sema/Initialization.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "llvm/ADT/SmallVector.h" 25#include <set> 26using namespace clang; 27 28 29 30enum 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) 44}; 45 46namespace { 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)), 52 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 53 54 if (const BuiltinType *placeholder = 55 src.get()->getType()->getAsPlaceholderType()) { 56 PlaceholderKind = placeholder->getKind(); 57 } else { 58 PlaceholderKind = (BuiltinType::Kind) 0; 59 } 60 } 61 62 Sema &Self; 63 ExprResult SrcExpr; 64 QualType DestType; 65 QualType ResultType; 66 ExprValueKind ValueKind; 67 CastKind Kind; 68 BuiltinType::Kind PlaceholderKind; 69 CXXCastPath BasePath; 70 bool IsARCUnbridgedCast; 71 72 SourceRange OpRange; 73 SourceRange DestRange; 74 75 // Top-level semantics-checking routines. 76 void CheckConstCast(); 77 void CheckReinterpretCast(); 78 void CheckStaticCast(); 79 void CheckDynamicCast(); 80 void CheckCXXCStyleCast(bool FunctionalCast); 81 void CheckCStyleCast(); 82 83 /// 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 97 // 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 } 115 116 void checkCastAlign() { 117 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 118 } 119 120 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) { 121 assert(Self.getLangOptions().ObjCAutoRefCount); 122 123 Expr *src = SrcExpr.get(); 124 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) == 125 Sema::ACR_unbridged) 126 IsARCUnbridgedCast = true; 127 SrcExpr = src; 128 } 129 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 } 140 }; 141} 142 143static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 144 bool CheckCVR, bool CheckObjCLifetime); 145 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, 158 QualType DestType, bool CStyle, 159 CastKind &Kind, 160 CXXCastPath &BasePath, 161 unsigned &msg); 162static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 163 QualType DestType, bool CStyle, 164 const SourceRange &OpRange, 165 unsigned &msg, 166 CastKind &Kind, 167 CXXCastPath &BasePath); 168static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 169 QualType DestType, bool CStyle, 170 const SourceRange &OpRange, 171 unsigned &msg, 172 CastKind &Kind, 173 CXXCastPath &BasePath); 174static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 175 CanQualType DestType, bool CStyle, 176 const SourceRange &OpRange, 177 QualType OrigSrcType, 178 QualType OrigDestType, unsigned &msg, 179 CastKind &Kind, 180 CXXCastPath &BasePath); 181static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 182 QualType SrcType, 183 QualType DestType,bool CStyle, 184 const SourceRange &OpRange, 185 unsigned &msg, 186 CastKind &Kind, 187 CXXCastPath &BasePath); 188 189static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 190 QualType DestType, 191 Sema::CheckedConversionKind CCK, 192 const SourceRange &OpRange, 193 unsigned &msg, 194 CastKind &Kind); 195static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 196 QualType DestType, 197 Sema::CheckedConversionKind CCK, 198 const SourceRange &OpRange, 199 unsigned &msg, 200 CastKind &Kind, 201 CXXCastPath &BasePath); 202static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 203 bool CStyle, unsigned &msg); 204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 205 QualType DestType, bool CStyle, 206 const SourceRange &OpRange, 207 unsigned &msg, 208 CastKind &Kind); 209 210 211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 212ExprResult 213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 214 SourceLocation LAngleBracketLoc, Declarator &D, 215 SourceLocation RAngleBracketLoc, 216 SourceLocation LParenLoc, Expr *E, 217 SourceLocation RParenLoc) { 218 219 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), 231 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 232 SourceRange(LParenLoc, RParenLoc)); 233} 234 235ExprResult 236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 237 TypeSourceInfo *DestTInfo, Expr *E, 238 SourceRange AngleBrackets, SourceRange Parens) { 239 ExprResult Ex = Owned(E); 240 QualType DestType = DestTInfo->getType(); 241 242 // 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? 244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent(); 245 246 CastOperation Op(*this, DestType, E); 247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 248 Op.DestRange = AngleBrackets; 249 250 switch (Kind) { 251 default: llvm_unreachable("Unknown C++ cast!"); 252 253 case tok::kw_const_cast: 254 if (!TypeDependent) { 255 Op.CheckConstCast(); 256 if (Op.SrcExpr.isInvalid()) 257 return ExprError(); 258 } 259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, 260 Op.ValueKind, Op.SrcExpr.take(), DestTInfo, 261 OpLoc, Parens.getEnd())); 262 263 case tok::kw_dynamic_cast: { 264 if (!TypeDependent) { 265 Op.CheckDynamicCast(); 266 if (Op.SrcExpr.isInvalid()) 267 return ExprError(); 268 } 269 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 270 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 271 &Op.BasePath, DestTInfo, 272 OpLoc, Parens.getEnd())); 273 } 274 case tok::kw_reinterpret_cast: { 275 if (!TypeDependent) { 276 Op.CheckReinterpretCast(); 277 if (Op.SrcExpr.isInvalid()) 278 return ExprError(); 279 } 280 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 281 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 282 0, DestTInfo, OpLoc, 283 Parens.getEnd())); 284 } 285 case tok::kw_static_cast: { 286 if (!TypeDependent) { 287 Op.CheckStaticCast(); 288 if (Op.SrcExpr.isInvalid()) 289 return ExprError(); 290 } 291 292 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, 293 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 294 &Op.BasePath, DestTInfo, 295 OpLoc, Parens.getEnd())); 296 } 297 } 298} 299 300/// Try to diagnose a failed overloaded cast. Returns true if 301/// diagnostics were emitted. 302static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 303 SourceRange range, Expr *src, 304 QualType destType) { 305 switch (CT) { 306 // These cast kinds don't consider user-defined conversions. 307 case CT_Const: 308 case CT_Reinterpret: 309 case CT_Dynamic: 310 return false; 311 312 // These do. 313 case CT_Static: 314 case CT_CStyle: 315 case CT_Functional: 316 break; 317 } 318 319 QualType srcType = src->getType(); 320 if (!destType->isRecordType() && !srcType->isRecordType()) 321 return false; 322 323 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 324 InitializationKind initKind 325 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 326 range) 327 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range) 328 : InitializationKind::CreateCast(/*type range?*/ range); 329 InitializationSequence sequence(S, entity, initKind, &src, 1); 330 331 assert(sequence.Failed() && "initialization succeeded on second try?"); 332 switch (sequence.getFailureKind()) { 333 default: return false; 334 335 case InitializationSequence::FK_ConstructorOverloadFailed: 336 case InitializationSequence::FK_UserConversionOverloadFailed: 337 break; 338 } 339 340 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 341 342 unsigned msg = 0; 343 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 344 345 switch (sequence.getFailedOverloadResult()) { 346 case OR_Success: llvm_unreachable("successful failed overload"); 347 case OR_No_Viable_Function: 348 if (candidates.empty()) 349 msg = diag::err_ovl_no_conversion_in_cast; 350 else 351 msg = diag::err_ovl_no_viable_conversion_in_cast; 352 howManyCandidates = OCD_AllCandidates; 353 break; 354 355 case OR_Ambiguous: 356 msg = diag::err_ovl_ambiguous_conversion_in_cast; 357 howManyCandidates = OCD_ViableCandidates; 358 break; 359 360 case OR_Deleted: 361 msg = diag::err_ovl_deleted_conversion_in_cast; 362 howManyCandidates = OCD_ViableCandidates; 363 break; 364 } 365 366 S.Diag(range.getBegin(), msg) 367 << CT << srcType << destType 368 << range << src->getSourceRange(); 369 370 candidates.NoteCandidates(S, howManyCandidates, &src, 1); 371 372 return true; 373} 374 375/// Diagnose a failed cast. 376static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 377 SourceRange opRange, Expr *src, QualType destType) { 378 if (src->getType() == S.Context.BoundMemberTy) { 379 (void) S.CheckPlaceholderExpr(src); // will always fail 380 return; 381 } 382 383 if (msg == diag::err_bad_cxx_cast_generic && 384 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType)) 385 return; 386 387 S.Diag(opRange.getBegin(), msg) << castType 388 << src->getType() << destType << opRange << src->getSourceRange(); 389} 390 391/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes, 392/// this removes one level of indirection from both types, provided that they're 393/// the same kind of pointer (plain or to-member). Unlike the Sema function, 394/// this one doesn't care if the two pointers-to-member don't point into the 395/// same class. This is because CastsAwayConstness doesn't care. 396static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) { 397 const PointerType *T1PtrType = T1->getAs<PointerType>(), 398 *T2PtrType = T2->getAs<PointerType>(); 399 if (T1PtrType && T2PtrType) { 400 T1 = T1PtrType->getPointeeType(); 401 T2 = T2PtrType->getPointeeType(); 402 return true; 403 } 404 const ObjCObjectPointerType *T1ObjCPtrType = 405 T1->getAs<ObjCObjectPointerType>(), 406 *T2ObjCPtrType = 407 T2->getAs<ObjCObjectPointerType>(); 408 if (T1ObjCPtrType) { 409 if (T2ObjCPtrType) { 410 T1 = T1ObjCPtrType->getPointeeType(); 411 T2 = T2ObjCPtrType->getPointeeType(); 412 return true; 413 } 414 else if (T2PtrType) { 415 T1 = T1ObjCPtrType->getPointeeType(); 416 T2 = T2PtrType->getPointeeType(); 417 return true; 418 } 419 } 420 else if (T2ObjCPtrType) { 421 if (T1PtrType) { 422 T2 = T2ObjCPtrType->getPointeeType(); 423 T1 = T1PtrType->getPointeeType(); 424 return true; 425 } 426 } 427 428 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 429 *T2MPType = T2->getAs<MemberPointerType>(); 430 if (T1MPType && T2MPType) { 431 T1 = T1MPType->getPointeeType(); 432 T2 = T2MPType->getPointeeType(); 433 return true; 434 } 435 436 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(), 437 *T2BPType = T2->getAs<BlockPointerType>(); 438 if (T1BPType && T2BPType) { 439 T1 = T1BPType->getPointeeType(); 440 T2 = T2BPType->getPointeeType(); 441 return true; 442 } 443 444 return false; 445} 446 447/// CastsAwayConstness - Check if the pointer conversion from SrcType to 448/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by 449/// the cast checkers. Both arguments must denote pointer (possibly to member) 450/// types. 451/// 452/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 453/// 454/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 455static bool 456CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 457 bool CheckCVR, bool CheckObjCLifetime) { 458 // If the only checking we care about is for Objective-C lifetime qualifiers, 459 // and we're not in ARC mode, there's nothing to check. 460 if (!CheckCVR && CheckObjCLifetime && 461 !Self.Context.getLangOptions().ObjCAutoRefCount) 462 return false; 463 464 // Casting away constness is defined in C++ 5.2.11p8 with reference to 465 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since 466 // the rules are non-trivial. So first we construct Tcv *...cv* as described 467 // in C++ 5.2.11p8. 468 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 469 SrcType->isBlockPointerType()) && 470 "Source type is not pointer or pointer to member."); 471 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 472 DestType->isBlockPointerType()) && 473 "Destination type is not pointer or pointer to member."); 474 475 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 476 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 477 SmallVector<Qualifiers, 8> cv1, cv2; 478 479 // Find the qualifiers. We only care about cvr-qualifiers for the 480 // purpose of this check, because other qualifiers (address spaces, 481 // Objective-C GC, etc.) are part of the type's identity. 482 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 483 // Determine the relevant qualifiers at this level. 484 Qualifiers SrcQuals, DestQuals; 485 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 486 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 487 488 Qualifiers RetainedSrcQuals, RetainedDestQuals; 489 if (CheckCVR) { 490 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers()); 491 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers()); 492 } 493 494 if (CheckObjCLifetime && 495 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 496 return true; 497 498 cv1.push_back(RetainedSrcQuals); 499 cv2.push_back(RetainedDestQuals); 500 } 501 if (cv1.empty()) 502 return false; 503 504 // Construct void pointers with those qualifiers (in reverse order of 505 // unwrapping, of course). 506 QualType SrcConstruct = Self.Context.VoidTy; 507 QualType DestConstruct = Self.Context.VoidTy; 508 ASTContext &Context = Self.Context; 509 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(), 510 i2 = cv2.rbegin(); 511 i1 != cv1.rend(); ++i1, ++i2) { 512 SrcConstruct 513 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1)); 514 DestConstruct 515 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2)); 516 } 517 518 // Test if they're compatible. 519 bool ObjCLifetimeConversion; 520 return SrcConstruct != DestConstruct && 521 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false, 522 ObjCLifetimeConversion); 523} 524 525/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 526/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 527/// checked downcasts in class hierarchies. 528void CastOperation::CheckDynamicCast() { 529 if (ValueKind == VK_RValue) 530 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 531 else if (isPlaceholder()) 532 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 533 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 534 return; 535 536 QualType OrigSrcType = SrcExpr.get()->getType(); 537 QualType DestType = Self.Context.getCanonicalType(this->DestType); 538 539 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 540 // or "pointer to cv void". 541 542 QualType DestPointee; 543 const PointerType *DestPointer = DestType->getAs<PointerType>(); 544 const ReferenceType *DestReference = 0; 545 if (DestPointer) { 546 DestPointee = DestPointer->getPointeeType(); 547 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 548 DestPointee = DestReference->getPointeeType(); 549 } else { 550 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 551 << this->DestType << DestRange; 552 return; 553 } 554 555 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 556 if (DestPointee->isVoidType()) { 557 assert(DestPointer && "Reference to void is not possible"); 558 } else if (DestRecord) { 559 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 560 Self.PDiag(diag::err_bad_dynamic_cast_incomplete) 561 << DestRange)) 562 return; 563 } else { 564 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 565 << DestPointee.getUnqualifiedType() << DestRange; 566 return; 567 } 568 569 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 570 // complete class type, [...]. If T is an lvalue reference type, v shall be 571 // an lvalue of a complete class type, [...]. If T is an rvalue reference 572 // type, v shall be an expression having a complete class type, [...] 573 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 574 QualType SrcPointee; 575 if (DestPointer) { 576 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 577 SrcPointee = SrcPointer->getPointeeType(); 578 } else { 579 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 580 << OrigSrcType << SrcExpr.get()->getSourceRange(); 581 return; 582 } 583 } else if (DestReference->isLValueReferenceType()) { 584 if (!SrcExpr.get()->isLValue()) { 585 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 586 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 587 } 588 SrcPointee = SrcType; 589 } else { 590 SrcPointee = SrcType; 591 } 592 593 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 594 if (SrcRecord) { 595 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 596 Self.PDiag(diag::err_bad_dynamic_cast_incomplete) 597 << SrcExpr.get()->getSourceRange())) 598 return; 599 } else { 600 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 601 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 602 return; 603 } 604 605 assert((DestPointer || DestReference) && 606 "Bad destination non-ptr/ref slipped through."); 607 assert((DestRecord || DestPointee->isVoidType()) && 608 "Bad destination pointee slipped through."); 609 assert(SrcRecord && "Bad source pointee slipped through."); 610 611 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 612 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 613 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 614 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 615 return; 616 } 617 618 // C++ 5.2.7p3: If the type of v is the same as the required result type, 619 // [except for cv]. 620 if (DestRecord == SrcRecord) { 621 Kind = CK_NoOp; 622 return; 623 } 624 625 // C++ 5.2.7p5 626 // Upcasts are resolved statically. 627 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) { 628 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 629 OpRange.getBegin(), OpRange, 630 &BasePath)) 631 return; 632 633 Kind = CK_DerivedToBase; 634 635 // If we are casting to or through a virtual base class, we need a 636 // vtable. 637 if (Self.BasePathInvolvesVirtualBase(BasePath)) 638 Self.MarkVTableUsed(OpRange.getBegin(), 639 cast<CXXRecordDecl>(SrcRecord->getDecl())); 640 return; 641 } 642 643 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 644 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 645 assert(SrcDecl && "Definition missing"); 646 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 647 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 648 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 649 } 650 Self.MarkVTableUsed(OpRange.getBegin(), 651 cast<CXXRecordDecl>(SrcRecord->getDecl())); 652 653 // Done. Everything else is run-time checks. 654 Kind = CK_Dynamic; 655} 656 657/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 658/// Refer to C++ 5.2.11 for details. const_cast is typically used in code 659/// like this: 660/// const char *str = "literal"; 661/// legacy_function(const_cast\<char*\>(str)); 662void CastOperation::CheckConstCast() { 663 if (ValueKind == VK_RValue) 664 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 665 else if (isPlaceholder()) 666 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 667 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 668 return; 669 670 unsigned msg = diag::err_bad_cxx_cast_generic; 671 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success 672 && msg != 0) 673 Self.Diag(OpRange.getBegin(), msg) << CT_Const 674 << SrcExpr.get()->getType() << DestType << OpRange; 675} 676 677/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 678/// valid. 679/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 680/// like this: 681/// char *bytes = reinterpret_cast\<char*\>(int_ptr); 682void CastOperation::CheckReinterpretCast() { 683 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) 684 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 685 else 686 checkNonOverloadPlaceholders(); 687 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 688 return; 689 690 unsigned msg = diag::err_bad_cxx_cast_generic; 691 TryCastResult tcr = 692 TryReinterpretCast(Self, SrcExpr, DestType, 693 /*CStyle*/false, OpRange, msg, Kind); 694 if (tcr != TC_Success && msg != 0) 695 { 696 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 697 return; 698 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 699 //FIXME: &f<int>; is overloaded and resolvable 700 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 701 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 702 << DestType << OpRange; 703 Self.NoteAllOverloadCandidates(SrcExpr.get()); 704 705 } else { 706 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType); 707 } 708 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) { 709 checkObjCARCConversion(Sema::CCK_OtherCast); 710 } 711} 712 713 714/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 715/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 716/// implicit conversions explicit and getting rid of data loss warnings. 717void CastOperation::CheckStaticCast() { 718 if (isPlaceholder()) { 719 checkNonOverloadPlaceholders(); 720 if (SrcExpr.isInvalid()) 721 return; 722 } 723 724 // This test is outside everything else because it's the only case where 725 // a non-lvalue-reference target type does not lead to decay. 726 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 727 if (DestType->isVoidType()) { 728 Kind = CK_ToVoid; 729 730 if (claimPlaceholder(BuiltinType::Overload)) { 731 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 732 false, // Decay Function to ptr 733 true, // Complain 734 OpRange, DestType, diag::err_bad_static_cast_overload); 735 if (SrcExpr.isInvalid()) 736 return; 737 } 738 739 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 740 return; 741 } 742 743 if (ValueKind == VK_RValue && !DestType->isRecordType() && 744 !isPlaceholder(BuiltinType::Overload)) { 745 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 746 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 747 return; 748 } 749 750 unsigned msg = diag::err_bad_cxx_cast_generic; 751 TryCastResult tcr 752 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 753 Kind, BasePath); 754 if (tcr != TC_Success && msg != 0) { 755 if (SrcExpr.isInvalid()) 756 return; 757 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 758 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 759 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 760 << oe->getName() << DestType << OpRange 761 << oe->getQualifierLoc().getSourceRange(); 762 Self.NoteAllOverloadCandidates(SrcExpr.get()); 763 } else { 764 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType); 765 } 766 } else if (tcr == TC_Success) { 767 if (Kind == CK_BitCast) 768 checkCastAlign(); 769 if (Self.getLangOptions().ObjCAutoRefCount) 770 checkObjCARCConversion(Sema::CCK_OtherCast); 771 } else if (Kind == CK_BitCast) { 772 checkCastAlign(); 773 } 774} 775 776/// TryStaticCast - Check if a static cast can be performed, and do so if 777/// possible. If @p CStyle, ignore access restrictions on hierarchy casting 778/// and casting away constness. 779static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 780 QualType DestType, 781 Sema::CheckedConversionKind CCK, 782 const SourceRange &OpRange, unsigned &msg, 783 CastKind &Kind, 784 CXXCastPath &BasePath) { 785 // Determine whether we have the semantics of a C-style cast. 786 bool CStyle 787 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 788 789 // The order the tests is not entirely arbitrary. There is one conversion 790 // that can be handled in two different ways. Given: 791 // struct A {}; 792 // struct B : public A { 793 // B(); B(const A&); 794 // }; 795 // const A &a = B(); 796 // the cast static_cast<const B&>(a) could be seen as either a static 797 // reference downcast, or an explicit invocation of the user-defined 798 // conversion using B's conversion constructor. 799 // DR 427 specifies that the downcast is to be applied here. 800 801 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 802 // Done outside this function. 803 804 TryCastResult tcr; 805 806 // C++ 5.2.9p5, reference downcast. 807 // See the function for details. 808 // DR 427 specifies that this is to be applied before paragraph 2. 809 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange, 810 msg, Kind, BasePath); 811 if (tcr != TC_NotApplicable) 812 return tcr; 813 814 // C++0x [expr.static.cast]p3: 815 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 816 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 817 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath, 818 msg); 819 if (tcr != TC_NotApplicable) 820 return tcr; 821 822 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 823 // [...] if the declaration "T t(e);" is well-formed, [...]. 824 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 825 Kind); 826 if (SrcExpr.isInvalid()) 827 return TC_Failed; 828 if (tcr != TC_NotApplicable) 829 return tcr; 830 831 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 832 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 833 // conversions, subject to further restrictions. 834 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 835 // of qualification conversions impossible. 836 // In the CStyle case, the earlier attempt to const_cast should have taken 837 // care of reverse qualification conversions. 838 839 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 840 841 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 842 // converted to an integral type. [...] A value of a scoped enumeration type 843 // can also be explicitly converted to a floating-point type [...]. 844 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 845 if (Enum->getDecl()->isScoped()) { 846 if (DestType->isBooleanType()) { 847 Kind = CK_IntegralToBoolean; 848 return TC_Success; 849 } else if (DestType->isIntegralType(Self.Context)) { 850 Kind = CK_IntegralCast; 851 return TC_Success; 852 } else if (DestType->isRealFloatingType()) { 853 Kind = CK_IntegralToFloating; 854 return TC_Success; 855 } 856 } 857 } 858 859 // Reverse integral promotion/conversion. All such conversions are themselves 860 // again integral promotions or conversions and are thus already handled by 861 // p2 (TryDirectInitialization above). 862 // (Note: any data loss warnings should be suppressed.) 863 // The exception is the reverse of enum->integer, i.e. integer->enum (and 864 // enum->enum). See also C++ 5.2.9p7. 865 // The same goes for reverse floating point promotion/conversion and 866 // floating-integral conversions. Again, only floating->enum is relevant. 867 if (DestType->isEnumeralType()) { 868 if (SrcType->isIntegralOrEnumerationType()) { 869 Kind = CK_IntegralCast; 870 return TC_Success; 871 } else if (SrcType->isRealFloatingType()) { 872 Kind = CK_FloatingToIntegral; 873 return TC_Success; 874 } 875 } 876 877 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 878 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 879 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 880 Kind, BasePath); 881 if (tcr != TC_NotApplicable) 882 return tcr; 883 884 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 885 // conversion. C++ 5.2.9p9 has additional information. 886 // DR54's access restrictions apply here also. 887 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 888 OpRange, msg, Kind, BasePath); 889 if (tcr != TC_NotApplicable) 890 return tcr; 891 892 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 893 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 894 // just the usual constness stuff. 895 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 896 QualType SrcPointee = SrcPointer->getPointeeType(); 897 if (SrcPointee->isVoidType()) { 898 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 899 QualType DestPointee = DestPointer->getPointeeType(); 900 if (DestPointee->isIncompleteOrObjectType()) { 901 // This is definitely the intended conversion, but it might fail due 902 // to a qualifier violation. Note that we permit Objective-C lifetime 903 // and GC qualifier mismatches here. 904 if (!CStyle) { 905 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 906 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 907 DestPointeeQuals.removeObjCGCAttr(); 908 DestPointeeQuals.removeObjCLifetime(); 909 SrcPointeeQuals.removeObjCGCAttr(); 910 SrcPointeeQuals.removeObjCLifetime(); 911 if (DestPointeeQuals != SrcPointeeQuals && 912 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 913 msg = diag::err_bad_cxx_cast_qualifiers_away; 914 return TC_Failed; 915 } 916 } 917 Kind = CK_BitCast; 918 return TC_Success; 919 } 920 } 921 else if (DestType->isObjCObjectPointerType()) { 922 // allow both c-style cast and static_cast of objective-c pointers as 923 // they are pervasive. 924 Kind = CK_CPointerToObjCPointerCast; 925 return TC_Success; 926 } 927 else if (CStyle && DestType->isBlockPointerType()) { 928 // allow c-style cast of void * to block pointers. 929 Kind = CK_AnyPointerToBlockPointerCast; 930 return TC_Success; 931 } 932 } 933 } 934 // Allow arbitray objective-c pointer conversion with static casts. 935 if (SrcType->isObjCObjectPointerType() && 936 DestType->isObjCObjectPointerType()) { 937 Kind = CK_BitCast; 938 return TC_Success; 939 } 940 941 // We tried everything. Everything! Nothing works! :-( 942 return TC_NotApplicable; 943} 944 945/// Tests whether a conversion according to N2844 is valid. 946TryCastResult 947TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, 948 bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 949 unsigned &msg) { 950 // C++0x [expr.static.cast]p3: 951 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 952 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 953 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 954 if (!R) 955 return TC_NotApplicable; 956 957 if (!SrcExpr->isGLValue()) 958 return TC_NotApplicable; 959 960 // Because we try the reference downcast before this function, from now on 961 // this is the only cast possibility, so we issue an error if we fail now. 962 // FIXME: Should allow casting away constness if CStyle. 963 bool DerivedToBase; 964 bool ObjCConversion; 965 bool ObjCLifetimeConversion; 966 QualType FromType = SrcExpr->getType(); 967 QualType ToType = R->getPointeeType(); 968 if (CStyle) { 969 FromType = FromType.getUnqualifiedType(); 970 ToType = ToType.getUnqualifiedType(); 971 } 972 973 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(), 974 ToType, FromType, 975 DerivedToBase, ObjCConversion, 976 ObjCLifetimeConversion) 977 < Sema::Ref_Compatible_With_Added_Qualification) { 978 msg = diag::err_bad_lvalue_to_rvalue_cast; 979 return TC_Failed; 980 } 981 982 if (DerivedToBase) { 983 Kind = CK_DerivedToBase; 984 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 985 /*DetectVirtual=*/true); 986 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths)) 987 return TC_NotApplicable; 988 989 Self.BuildBasePathArray(Paths, BasePath); 990 } else 991 Kind = CK_NoOp; 992 993 return TC_Success; 994} 995 996/// Tests whether a conversion according to C++ 5.2.9p5 is valid. 997TryCastResult 998TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 999 bool CStyle, const SourceRange &OpRange, 1000 unsigned &msg, CastKind &Kind, 1001 CXXCastPath &BasePath) { 1002 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 1003 // cast to type "reference to cv2 D", where D is a class derived from B, 1004 // if a valid standard conversion from "pointer to D" to "pointer to B" 1005 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1006 // In addition, DR54 clarifies that the base must be accessible in the 1007 // current context. Although the wording of DR54 only applies to the pointer 1008 // variant of this rule, the intent is clearly for it to apply to the this 1009 // conversion as well. 1010 1011 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1012 if (!DestReference) { 1013 return TC_NotApplicable; 1014 } 1015 bool RValueRef = DestReference->isRValueReferenceType(); 1016 if (!RValueRef && !SrcExpr->isLValue()) { 1017 // We know the left side is an lvalue reference, so we can suggest a reason. 1018 msg = diag::err_bad_cxx_cast_rvalue; 1019 return TC_NotApplicable; 1020 } 1021 1022 QualType DestPointee = DestReference->getPointeeType(); 1023 1024 return TryStaticDowncast(Self, 1025 Self.Context.getCanonicalType(SrcExpr->getType()), 1026 Self.Context.getCanonicalType(DestPointee), CStyle, 1027 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1028 BasePath); 1029} 1030 1031/// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1032TryCastResult 1033TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1034 bool CStyle, const SourceRange &OpRange, 1035 unsigned &msg, CastKind &Kind, 1036 CXXCastPath &BasePath) { 1037 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1038 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1039 // is a class derived from B, if a valid standard conversion from "pointer 1040 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1041 // class of D. 1042 // In addition, DR54 clarifies that the base must be accessible in the 1043 // current context. 1044 1045 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1046 if (!DestPointer) { 1047 return TC_NotApplicable; 1048 } 1049 1050 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1051 if (!SrcPointer) { 1052 msg = diag::err_bad_static_cast_pointer_nonpointer; 1053 return TC_NotApplicable; 1054 } 1055 1056 return TryStaticDowncast(Self, 1057 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1058 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1059 CStyle, OpRange, SrcType, DestType, msg, Kind, 1060 BasePath); 1061} 1062 1063/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1064/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1065/// DestType is possible and allowed. 1066TryCastResult 1067TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1068 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType, 1069 QualType OrigDestType, unsigned &msg, 1070 CastKind &Kind, CXXCastPath &BasePath) { 1071 // We can only work with complete types. But don't complain if it doesn't work 1072 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) || 1073 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0))) 1074 return TC_NotApplicable; 1075 1076 // Downcast can only happen in class hierarchies, so we need classes. 1077 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1078 return TC_NotApplicable; 1079 } 1080 1081 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1082 /*DetectVirtual=*/true); 1083 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) { 1084 return TC_NotApplicable; 1085 } 1086 1087 // Target type does derive from source type. Now we're serious. If an error 1088 // appears now, it's not ignored. 1089 // This may not be entirely in line with the standard. Take for example: 1090 // struct A {}; 1091 // struct B : virtual A { 1092 // B(A&); 1093 // }; 1094 // 1095 // void f() 1096 // { 1097 // (void)static_cast<const B&>(*((A*)0)); 1098 // } 1099 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1100 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1101 // However, both GCC and Comeau reject this example, and accepting it would 1102 // mean more complex code if we're to preserve the nice error message. 1103 // FIXME: Being 100% compliant here would be nice to have. 1104 1105 // Must preserve cv, as always, unless we're in C-style mode. 1106 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1107 msg = diag::err_bad_cxx_cast_qualifiers_away; 1108 return TC_Failed; 1109 } 1110 1111 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1112 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1113 // that it builds the paths in reverse order. 1114 // To sum up: record all paths to the base and build a nice string from 1115 // them. Use it to spice up the error message. 1116 if (!Paths.isRecordingPaths()) { 1117 Paths.clear(); 1118 Paths.setRecordingPaths(true); 1119 Self.IsDerivedFrom(DestType, SrcType, Paths); 1120 } 1121 std::string PathDisplayStr; 1122 std::set<unsigned> DisplayedPaths; 1123 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end(); 1124 PI != PE; ++PI) { 1125 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) { 1126 // We haven't displayed a path to this particular base 1127 // class subobject yet. 1128 PathDisplayStr += "\n "; 1129 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(), 1130 EE = PI->rend(); 1131 EI != EE; ++EI) 1132 PathDisplayStr += EI->Base->getType().getAsString() + " -> "; 1133 PathDisplayStr += QualType(DestType).getAsString(); 1134 } 1135 } 1136 1137 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1138 << QualType(SrcType).getUnqualifiedType() 1139 << QualType(DestType).getUnqualifiedType() 1140 << PathDisplayStr << OpRange; 1141 msg = 0; 1142 return TC_Failed; 1143 } 1144 1145 if (Paths.getDetectedVirtual() != 0) { 1146 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1147 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1148 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1149 msg = 0; 1150 return TC_Failed; 1151 } 1152 1153 if (!CStyle) { 1154 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1155 SrcType, DestType, 1156 Paths.front(), 1157 diag::err_downcast_from_inaccessible_base)) { 1158 case Sema::AR_accessible: 1159 case Sema::AR_delayed: // be optimistic 1160 case Sema::AR_dependent: // be optimistic 1161 break; 1162 1163 case Sema::AR_inaccessible: 1164 msg = 0; 1165 return TC_Failed; 1166 } 1167 } 1168 1169 Self.BuildBasePathArray(Paths, BasePath); 1170 Kind = CK_BaseToDerived; 1171 return TC_Success; 1172} 1173 1174/// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1175/// C++ 5.2.9p9 is valid: 1176/// 1177/// An rvalue of type "pointer to member of D of type cv1 T" can be 1178/// converted to an rvalue of type "pointer to member of B of type cv2 T", 1179/// where B is a base class of D [...]. 1180/// 1181TryCastResult 1182TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1183 QualType DestType, bool CStyle, 1184 const SourceRange &OpRange, 1185 unsigned &msg, CastKind &Kind, 1186 CXXCastPath &BasePath) { 1187 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1188 if (!DestMemPtr) 1189 return TC_NotApplicable; 1190 1191 bool WasOverloadedFunction = false; 1192 DeclAccessPair FoundOverload; 1193 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1194 if (FunctionDecl *Fn 1195 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1196 FoundOverload)) { 1197 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1198 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1199 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1200 WasOverloadedFunction = true; 1201 } 1202 } 1203 1204 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1205 if (!SrcMemPtr) { 1206 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1207 return TC_NotApplicable; 1208 } 1209 1210 // T == T, modulo cv 1211 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1212 DestMemPtr->getPointeeType())) 1213 return TC_NotApplicable; 1214 1215 // B base of D 1216 QualType SrcClass(SrcMemPtr->getClass(), 0); 1217 QualType DestClass(DestMemPtr->getClass(), 0); 1218 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1219 /*DetectVirtual=*/true); 1220 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) { 1221 return TC_NotApplicable; 1222 } 1223 1224 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1225 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1226 Paths.clear(); 1227 Paths.setRecordingPaths(true); 1228 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths); 1229 assert(StillOkay); 1230 (void)StillOkay; 1231 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1232 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1233 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1234 msg = 0; 1235 return TC_Failed; 1236 } 1237 1238 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1239 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1240 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1241 msg = 0; 1242 return TC_Failed; 1243 } 1244 1245 if (!CStyle) { 1246 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1247 DestClass, SrcClass, 1248 Paths.front(), 1249 diag::err_upcast_to_inaccessible_base)) { 1250 case Sema::AR_accessible: 1251 case Sema::AR_delayed: 1252 case Sema::AR_dependent: 1253 // Optimistically assume that the delayed and dependent cases 1254 // will work out. 1255 break; 1256 1257 case Sema::AR_inaccessible: 1258 msg = 0; 1259 return TC_Failed; 1260 } 1261 } 1262 1263 if (WasOverloadedFunction) { 1264 // Resolve the address of the overloaded function again, this time 1265 // allowing complaints if something goes wrong. 1266 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1267 DestType, 1268 true, 1269 FoundOverload); 1270 if (!Fn) { 1271 msg = 0; 1272 return TC_Failed; 1273 } 1274 1275 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1276 if (!SrcExpr.isUsable()) { 1277 msg = 0; 1278 return TC_Failed; 1279 } 1280 } 1281 1282 Self.BuildBasePathArray(Paths, BasePath); 1283 Kind = CK_DerivedToBaseMemberPointer; 1284 return TC_Success; 1285} 1286 1287/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1288/// is valid: 1289/// 1290/// An expression e can be explicitly converted to a type T using a 1291/// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1292TryCastResult 1293TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1294 Sema::CheckedConversionKind CCK, 1295 const SourceRange &OpRange, unsigned &msg, 1296 CastKind &Kind) { 1297 if (DestType->isRecordType()) { 1298 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1299 diag::err_bad_dynamic_cast_incomplete)) { 1300 msg = 0; 1301 return TC_Failed; 1302 } 1303 } 1304 1305 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1306 InitializationKind InitKind 1307 = (CCK == Sema::CCK_CStyleCast) 1308 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange) 1309 : (CCK == Sema::CCK_FunctionalCast) 1310 ? InitializationKind::CreateFunctionalCast(OpRange) 1311 : InitializationKind::CreateCast(OpRange); 1312 Expr *SrcExprRaw = SrcExpr.get(); 1313 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1); 1314 1315 // At this point of CheckStaticCast, if the destination is a reference, 1316 // or the expression is an overload expression this has to work. 1317 // There is no other way that works. 1318 // On the other hand, if we're checking a C-style cast, we've still got 1319 // the reinterpret_cast way. 1320 bool CStyle 1321 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1322 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1323 return TC_NotApplicable; 1324 1325 ExprResult Result 1326 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1)); 1327 if (Result.isInvalid()) { 1328 msg = 0; 1329 return TC_Failed; 1330 } 1331 1332 if (InitSeq.isConstructorInitialization()) 1333 Kind = CK_ConstructorConversion; 1334 else 1335 Kind = CK_NoOp; 1336 1337 SrcExpr = move(Result); 1338 return TC_Success; 1339} 1340 1341/// TryConstCast - See if a const_cast from source to destination is allowed, 1342/// and perform it if it is. 1343static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 1344 bool CStyle, unsigned &msg) { 1345 DestType = Self.Context.getCanonicalType(DestType); 1346 QualType SrcType = SrcExpr->getType(); 1347 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1348 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) { 1349 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1350 // is C-style, static_cast might find a way, so we simply suggest a 1351 // message and tell the parent to keep searching. 1352 msg = diag::err_bad_cxx_cast_rvalue; 1353 return TC_NotApplicable; 1354 } 1355 1356 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2 1357 // [...] if a pointer to T1 can be [cast] to the type pointer to T2. 1358 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1359 SrcType = Self.Context.getPointerType(SrcType); 1360 } 1361 1362 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1363 // the rules for const_cast are the same as those used for pointers. 1364 1365 if (!DestType->isPointerType() && 1366 !DestType->isMemberPointerType() && 1367 !DestType->isObjCObjectPointerType()) { 1368 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1369 // was a reference type, we converted it to a pointer above. 1370 // The status of rvalue references isn't entirely clear, but it looks like 1371 // conversion to them is simply invalid. 1372 // C++ 5.2.11p3: For two pointer types [...] 1373 if (!CStyle) 1374 msg = diag::err_bad_const_cast_dest; 1375 return TC_NotApplicable; 1376 } 1377 if (DestType->isFunctionPointerType() || 1378 DestType->isMemberFunctionPointerType()) { 1379 // Cannot cast direct function pointers. 1380 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1381 // T is the ultimate pointee of source and target type. 1382 if (!CStyle) 1383 msg = diag::err_bad_const_cast_dest; 1384 return TC_NotApplicable; 1385 } 1386 SrcType = Self.Context.getCanonicalType(SrcType); 1387 1388 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 1389 // completely equal. 1390 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 1391 // in multi-level pointers may change, but the level count must be the same, 1392 // as must be the final pointee type. 1393 while (SrcType != DestType && 1394 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 1395 Qualifiers SrcQuals, DestQuals; 1396 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 1397 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 1398 1399 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 1400 // the other qualifiers (e.g., address spaces) are identical. 1401 SrcQuals.removeCVRQualifiers(); 1402 DestQuals.removeCVRQualifiers(); 1403 if (SrcQuals != DestQuals) 1404 return TC_NotApplicable; 1405 } 1406 1407 // Since we're dealing in canonical types, the remainder must be the same. 1408 if (SrcType != DestType) 1409 return TC_NotApplicable; 1410 1411 return TC_Success; 1412} 1413 1414// Checks for undefined behavior in reinterpret_cast. 1415// The cases that is checked for is: 1416// *reinterpret_cast<T*>(&a) 1417// reinterpret_cast<T&>(a) 1418// where accessing 'a' as type 'T' will result in undefined behavior. 1419void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 1420 bool IsDereference, 1421 SourceRange Range) { 1422 unsigned DiagID = IsDereference ? 1423 diag::warn_pointer_indirection_from_incompatible_type : 1424 diag::warn_undefined_reinterpret_cast; 1425 1426 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) == 1427 DiagnosticsEngine::Ignored) { 1428 return; 1429 } 1430 1431 QualType SrcTy, DestTy; 1432 if (IsDereference) { 1433 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 1434 return; 1435 } 1436 SrcTy = SrcType->getPointeeType(); 1437 DestTy = DestType->getPointeeType(); 1438 } else { 1439 if (!DestType->getAs<ReferenceType>()) { 1440 return; 1441 } 1442 SrcTy = SrcType; 1443 DestTy = DestType->getPointeeType(); 1444 } 1445 1446 // Cast is compatible if the types are the same. 1447 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 1448 return; 1449 } 1450 // or one of the types is a char or void type 1451 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 1452 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 1453 return; 1454 } 1455 // or one of the types is a tag type. 1456 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 1457 return; 1458 } 1459 1460 // FIXME: Scoped enums? 1461 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 1462 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 1463 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 1464 return; 1465 } 1466 } 1467 1468 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 1469} 1470 1471static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 1472 QualType DestType, bool CStyle, 1473 const SourceRange &OpRange, 1474 unsigned &msg, 1475 CastKind &Kind) { 1476 bool IsLValueCast = false; 1477 1478 DestType = Self.Context.getCanonicalType(DestType); 1479 QualType SrcType = SrcExpr.get()->getType(); 1480 1481 // Is the source an overloaded name? (i.e. &foo) 1482 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ... 1483 if (SrcType == Self.Context.OverloadTy) { 1484 // ... unless foo<int> resolves to an lvalue unambiguously. 1485 // TODO: what if this fails because of DiagnoseUseOfDecl or something 1486 // like it? 1487 ExprResult SingleFunctionExpr = SrcExpr; 1488 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1489 SingleFunctionExpr, 1490 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 1491 ) && SingleFunctionExpr.isUsable()) { 1492 SrcExpr = move(SingleFunctionExpr); 1493 SrcType = SrcExpr.get()->getType(); 1494 } else { 1495 return TC_NotApplicable; 1496 } 1497 } 1498 1499 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 1500 bool LValue = DestTypeTmp->isLValueReferenceType(); 1501 if (LValue && !SrcExpr.get()->isLValue()) { 1502 // Cannot cast non-lvalue to lvalue reference type. See the similar 1503 // comment in const_cast. 1504 msg = diag::err_bad_cxx_cast_rvalue; 1505 return TC_NotApplicable; 1506 } 1507 1508 if (!CStyle) { 1509 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 1510 /*isDereference=*/false, OpRange); 1511 } 1512 1513 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 1514 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 1515 // built-in & and * operators. 1516 1517 const char *inappropriate = 0; 1518 switch (SrcExpr.get()->getObjectKind()) { 1519 case OK_Ordinary: 1520 break; 1521 case OK_BitField: inappropriate = "bit-field"; break; 1522 case OK_VectorComponent: inappropriate = "vector element"; break; 1523 case OK_ObjCProperty: inappropriate = "property expression"; break; 1524 } 1525 if (inappropriate) { 1526 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 1527 << inappropriate << DestType 1528 << OpRange << SrcExpr.get()->getSourceRange(); 1529 msg = 0; SrcExpr = ExprError(); 1530 return TC_NotApplicable; 1531 } 1532 1533 // This code does this transformation for the checked types. 1534 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1535 SrcType = Self.Context.getPointerType(SrcType); 1536 1537 IsLValueCast = true; 1538 } 1539 1540 // Canonicalize source for comparison. 1541 SrcType = Self.Context.getCanonicalType(SrcType); 1542 1543 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 1544 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1545 if (DestMemPtr && SrcMemPtr) { 1546 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 1547 // can be explicitly converted to an rvalue of type "pointer to member 1548 // of Y of type T2" if T1 and T2 are both function types or both object 1549 // types. 1550 if (DestMemPtr->getPointeeType()->isFunctionType() != 1551 SrcMemPtr->getPointeeType()->isFunctionType()) 1552 return TC_NotApplicable; 1553 1554 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 1555 // constness. 1556 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 1557 // we accept it. 1558 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1559 /*CheckObjCLifetime=*/CStyle)) { 1560 msg = diag::err_bad_cxx_cast_qualifiers_away; 1561 return TC_Failed; 1562 } 1563 1564 // Don't allow casting between member pointers of different sizes. 1565 if (Self.Context.getTypeSize(DestMemPtr) != 1566 Self.Context.getTypeSize(SrcMemPtr)) { 1567 msg = diag::err_bad_cxx_cast_member_pointer_size; 1568 return TC_Failed; 1569 } 1570 1571 // A valid member pointer cast. 1572 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast; 1573 return TC_Success; 1574 } 1575 1576 // See below for the enumeral issue. 1577 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 1578 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 1579 // type large enough to hold it. A value of std::nullptr_t can be 1580 // converted to an integral type; the conversion has the same meaning 1581 // and validity as a conversion of (void*)0 to the integral type. 1582 if (Self.Context.getTypeSize(SrcType) > 1583 Self.Context.getTypeSize(DestType)) { 1584 msg = diag::err_bad_reinterpret_cast_small_int; 1585 return TC_Failed; 1586 } 1587 Kind = CK_PointerToIntegral; 1588 return TC_Success; 1589 } 1590 1591 bool destIsVector = DestType->isVectorType(); 1592 bool srcIsVector = SrcType->isVectorType(); 1593 if (srcIsVector || destIsVector) { 1594 // FIXME: Should this also apply to floating point types? 1595 bool srcIsScalar = SrcType->isIntegralType(Self.Context); 1596 bool destIsScalar = DestType->isIntegralType(Self.Context); 1597 1598 // Check if this is a cast between a vector and something else. 1599 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) && 1600 !(srcIsVector && destIsVector)) 1601 return TC_NotApplicable; 1602 1603 // If both types have the same size, we can successfully cast. 1604 if (Self.Context.getTypeSize(SrcType) 1605 == Self.Context.getTypeSize(DestType)) { 1606 Kind = CK_BitCast; 1607 return TC_Success; 1608 } 1609 1610 if (destIsScalar) 1611 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 1612 else if (srcIsScalar) 1613 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 1614 else 1615 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 1616 1617 return TC_Failed; 1618 } 1619 1620 if (SrcType == DestType) { 1621 // C++ 5.2.10p2 has a note that mentions that, subject to all other 1622 // restrictions, a cast to the same type is allowed so long as it does not 1623 // cast away constness. In C++98, the intent was not entirely clear here, 1624 // since all other paragraphs explicitly forbid casts to the same type. 1625 // C++11 clarifies this case with p2. 1626 // 1627 // The only allowed types are: integral, enumeration, pointer, or 1628 // pointer-to-member types. We also won't restrict Obj-C pointers either. 1629 Kind = CK_NoOp; 1630 TryCastResult Result = TC_NotApplicable; 1631 if (SrcType->isIntegralOrEnumerationType() || 1632 SrcType->isAnyPointerType() || 1633 SrcType->isMemberPointerType() || 1634 SrcType->isBlockPointerType()) { 1635 Result = TC_Success; 1636 } 1637 return Result; 1638 } 1639 1640 bool destIsPtr = DestType->isAnyPointerType() || 1641 DestType->isBlockPointerType(); 1642 bool srcIsPtr = SrcType->isAnyPointerType() || 1643 SrcType->isBlockPointerType(); 1644 if (!destIsPtr && !srcIsPtr) { 1645 // Except for std::nullptr_t->integer and lvalue->reference, which are 1646 // handled above, at least one of the two arguments must be a pointer. 1647 return TC_NotApplicable; 1648 } 1649 1650 if (DestType->isIntegralType(Self.Context)) { 1651 assert(srcIsPtr && "One type must be a pointer"); 1652 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 1653 // type large enough to hold it; except in Microsoft mode, where the 1654 // integral type size doesn't matter. 1655 if ((Self.Context.getTypeSize(SrcType) > 1656 Self.Context.getTypeSize(DestType)) && 1657 !Self.getLangOptions().MicrosoftExt) { 1658 msg = diag::err_bad_reinterpret_cast_small_int; 1659 return TC_Failed; 1660 } 1661 Kind = CK_PointerToIntegral; 1662 return TC_Success; 1663 } 1664 1665 if (SrcType->isIntegralOrEnumerationType()) { 1666 assert(destIsPtr && "One type must be a pointer"); 1667 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 1668 // converted to a pointer. 1669 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 1670 // necessarily converted to a null pointer value.] 1671 Kind = CK_IntegralToPointer; 1672 return TC_Success; 1673 } 1674 1675 if (!destIsPtr || !srcIsPtr) { 1676 // With the valid non-pointer conversions out of the way, we can be even 1677 // more stringent. 1678 return TC_NotApplicable; 1679 } 1680 1681 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 1682 // The C-style cast operator can. 1683 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1684 /*CheckObjCLifetime=*/CStyle)) { 1685 msg = diag::err_bad_cxx_cast_qualifiers_away; 1686 return TC_Failed; 1687 } 1688 1689 // Cannot convert between block pointers and Objective-C object pointers. 1690 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 1691 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 1692 return TC_NotApplicable; 1693 1694 if (IsLValueCast) { 1695 Kind = CK_LValueBitCast; 1696 } else if (DestType->isObjCObjectPointerType()) { 1697 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 1698 } else if (DestType->isBlockPointerType()) { 1699 if (!SrcType->isBlockPointerType()) { 1700 Kind = CK_AnyPointerToBlockPointerCast; 1701 } else { 1702 Kind = CK_BitCast; 1703 } 1704 } else { 1705 Kind = CK_BitCast; 1706 } 1707 1708 // Any pointer can be cast to an Objective-C pointer type with a C-style 1709 // cast. 1710 if (CStyle && DestType->isObjCObjectPointerType()) { 1711 return TC_Success; 1712 } 1713 1714 // Not casting away constness, so the only remaining check is for compatible 1715 // pointer categories. 1716 1717 if (SrcType->isFunctionPointerType()) { 1718 if (DestType->isFunctionPointerType()) { 1719 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 1720 // a pointer to a function of a different type. 1721 return TC_Success; 1722 } 1723 1724 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 1725 // an object type or vice versa is conditionally-supported. 1726 // Compilers support it in C++03 too, though, because it's necessary for 1727 // casting the return value of dlsym() and GetProcAddress(). 1728 // FIXME: Conditionally-supported behavior should be configurable in the 1729 // TargetInfo or similar. 1730 Self.Diag(OpRange.getBegin(), 1731 Self.getLangOptions().CPlusPlus0x ? 1732 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 1733 << OpRange; 1734 return TC_Success; 1735 } 1736 1737 if (DestType->isFunctionPointerType()) { 1738 // See above. 1739 Self.Diag(OpRange.getBegin(), 1740 Self.getLangOptions().CPlusPlus0x ? 1741 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 1742 << OpRange; 1743 return TC_Success; 1744 } 1745 1746 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 1747 // a pointer to an object of different type. 1748 // Void pointers are not specified, but supported by every compiler out there. 1749 // So we finish by allowing everything that remains - it's got to be two 1750 // object pointers. 1751 return TC_Success; 1752} 1753 1754void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) { 1755 // Handle placeholders. 1756 if (isPlaceholder()) { 1757 // C-style casts can resolve __unknown_any types. 1758 if (claimPlaceholder(BuiltinType::UnknownAny)) { 1759 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 1760 SrcExpr.get(), Kind, 1761 ValueKind, BasePath); 1762 return; 1763 } 1764 1765 checkNonOverloadPlaceholders(); 1766 if (SrcExpr.isInvalid()) 1767 return; 1768 } 1769 1770 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1771 // This test is outside everything else because it's the only case where 1772 // a non-lvalue-reference target type does not lead to decay. 1773 if (DestType->isVoidType()) { 1774 Kind = CK_ToVoid; 1775 1776 if (claimPlaceholder(BuiltinType::Overload)) { 1777 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1778 SrcExpr, /* Decay Function to ptr */ false, 1779 /* Complain */ true, DestRange, DestType, 1780 diag::err_bad_cstyle_cast_overload); 1781 if (SrcExpr.isInvalid()) 1782 return; 1783 } 1784 1785 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 1786 if (SrcExpr.isInvalid()) 1787 return; 1788 1789 return; 1790 } 1791 1792 // If the type is dependent, we won't do any other semantic analysis now. 1793 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) { 1794 assert(Kind == CK_Dependent); 1795 return; 1796 } 1797 1798 if (ValueKind == VK_RValue && !DestType->isRecordType() && 1799 !isPlaceholder(BuiltinType::Overload)) { 1800 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 1801 if (SrcExpr.isInvalid()) 1802 return; 1803 } 1804 1805 // AltiVec vector initialization with a single literal. 1806 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 1807 if (vecTy->getVectorKind() == VectorType::AltiVecVector 1808 && (SrcExpr.get()->getType()->isIntegerType() 1809 || SrcExpr.get()->getType()->isFloatingType())) { 1810 Kind = CK_VectorSplat; 1811 return; 1812 } 1813 1814 // C++ [expr.cast]p5: The conversions performed by 1815 // - a const_cast, 1816 // - a static_cast, 1817 // - a static_cast followed by a const_cast, 1818 // - a reinterpret_cast, or 1819 // - a reinterpret_cast followed by a const_cast, 1820 // can be performed using the cast notation of explicit type conversion. 1821 // [...] If a conversion can be interpreted in more than one of the ways 1822 // listed above, the interpretation that appears first in the list is used, 1823 // even if a cast resulting from that interpretation is ill-formed. 1824 // In plain language, this means trying a const_cast ... 1825 unsigned msg = diag::err_bad_cxx_cast_generic; 1826 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType, 1827 /*CStyle*/true, msg); 1828 if (tcr == TC_Success) 1829 Kind = CK_NoOp; 1830 1831 Sema::CheckedConversionKind CCK 1832 = FunctionalStyle? Sema::CCK_FunctionalCast 1833 : Sema::CCK_CStyleCast; 1834 if (tcr == TC_NotApplicable) { 1835 // ... or if that is not possible, a static_cast, ignoring const, ... 1836 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 1837 msg, Kind, BasePath); 1838 if (SrcExpr.isInvalid()) 1839 return; 1840 1841 if (tcr == TC_NotApplicable) { 1842 // ... and finally a reinterpret_cast, ignoring const. 1843 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 1844 OpRange, msg, Kind); 1845 if (SrcExpr.isInvalid()) 1846 return; 1847 } 1848 } 1849 1850 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success) 1851 checkObjCARCConversion(CCK); 1852 1853 if (tcr != TC_Success && msg != 0) { 1854 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1855 DeclAccessPair Found; 1856 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1857 DestType, 1858 /*Complain*/ true, 1859 Found); 1860 1861 assert(!Fn && "cast failed but able to resolve overload expression!!"); 1862 (void)Fn; 1863 1864 } else { 1865 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 1866 OpRange, SrcExpr.get(), DestType); 1867 } 1868 } else if (Kind == CK_BitCast) { 1869 checkCastAlign(); 1870 } 1871 1872 // Clear out SrcExpr if there was a fatal error. 1873 if (tcr != TC_Success) 1874 SrcExpr = ExprError(); 1875} 1876 1877/// Check the semantics of a C-style cast operation, in C. 1878void CastOperation::CheckCStyleCast() { 1879 assert(!Self.getLangOptions().CPlusPlus); 1880 1881 // C-style casts can resolve __unknown_any types. 1882 if (claimPlaceholder(BuiltinType::UnknownAny)) { 1883 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 1884 SrcExpr.get(), Kind, 1885 ValueKind, BasePath); 1886 return; 1887 } 1888 1889 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 1890 // type needs to be scalar. 1891 if (DestType->isVoidType()) { 1892 // We don't necessarily do lvalue-to-rvalue conversions on this. 1893 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 1894 if (SrcExpr.isInvalid()) 1895 return; 1896 1897 // Cast to void allows any expr type. 1898 Kind = CK_ToVoid; 1899 return; 1900 } 1901 1902 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 1903 if (SrcExpr.isInvalid()) 1904 return; 1905 QualType SrcType = SrcExpr.get()->getType(); 1906 1907 // You can cast an _Atomic(T) to anything you can cast a T to. 1908 if (const AtomicType *AtomicSrcType = SrcType->getAs<AtomicType>()) 1909 SrcType = AtomicSrcType->getValueType(); 1910 1911 assert(!SrcType->isPlaceholderType()); 1912 1913 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1914 diag::err_typecheck_cast_to_incomplete)) { 1915 SrcExpr = ExprError(); 1916 return; 1917 } 1918 1919 if (!DestType->isScalarType() && !DestType->isVectorType()) { 1920 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 1921 1922 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 1923 // GCC struct/union extension: allow cast to self. 1924 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 1925 << DestType << SrcExpr.get()->getSourceRange(); 1926 Kind = CK_NoOp; 1927 return; 1928 } 1929 1930 // GCC's cast to union extension. 1931 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 1932 RecordDecl *RD = DestRecordTy->getDecl(); 1933 RecordDecl::field_iterator Field, FieldEnd; 1934 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 1935 Field != FieldEnd; ++Field) { 1936 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 1937 !Field->isUnnamedBitfield()) { 1938 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 1939 << SrcExpr.get()->getSourceRange(); 1940 break; 1941 } 1942 } 1943 if (Field == FieldEnd) { 1944 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 1945 << SrcType << SrcExpr.get()->getSourceRange(); 1946 SrcExpr = ExprError(); 1947 return; 1948 } 1949 Kind = CK_ToUnion; 1950 return; 1951 } 1952 1953 // Reject any other conversions to non-scalar types. 1954 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 1955 << DestType << SrcExpr.get()->getSourceRange(); 1956 SrcExpr = ExprError(); 1957 return; 1958 } 1959 1960 // The type we're casting to is known to be a scalar or vector. 1961 1962 // Require the operand to be a scalar or vector. 1963 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 1964 Self.Diag(SrcExpr.get()->getExprLoc(), 1965 diag::err_typecheck_expect_scalar_operand) 1966 << SrcType << SrcExpr.get()->getSourceRange(); 1967 SrcExpr = ExprError(); 1968 return; 1969 } 1970 1971 if (DestType->isExtVectorType()) { 1972 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind); 1973 return; 1974 } 1975 1976 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 1977 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 1978 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 1979 Kind = CK_VectorSplat; 1980 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 1981 SrcExpr = ExprError(); 1982 } 1983 return; 1984 } 1985 1986 if (SrcType->isVectorType()) { 1987 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 1988 SrcExpr = ExprError(); 1989 return; 1990 } 1991 1992 // The source and target types are both scalars, i.e. 1993 // - arithmetic types (fundamental, enum, and complex) 1994 // - all kinds of pointers 1995 // Note that member pointers were filtered out with C++, above. 1996 1997 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 1998 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 1999 SrcExpr = ExprError(); 2000 return; 2001 } 2002 2003 // If either type is a pointer, the other type has to be either an 2004 // integer or a pointer. 2005 if (!DestType->isArithmeticType()) { 2006 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 2007 Self.Diag(SrcExpr.get()->getExprLoc(), 2008 diag::err_cast_pointer_from_non_pointer_int) 2009 << SrcType << SrcExpr.get()->getSourceRange(); 2010 SrcExpr = ExprError(); 2011 return; 2012 } 2013 } else if (!SrcType->isArithmeticType()) { 2014 if (!DestType->isIntegralType(Self.Context) && 2015 DestType->isArithmeticType()) { 2016 Self.Diag(SrcExpr.get()->getLocStart(), 2017 diag::err_cast_pointer_to_non_pointer_int) 2018 << DestType << SrcExpr.get()->getSourceRange(); 2019 SrcExpr = ExprError(); 2020 return; 2021 } 2022 } 2023 2024 // ARC imposes extra restrictions on casts. 2025 if (Self.getLangOptions().ObjCAutoRefCount) { 2026 checkObjCARCConversion(Sema::CCK_CStyleCast); 2027 if (SrcExpr.isInvalid()) 2028 return; 2029 2030 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) { 2031 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 2032 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 2033 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 2034 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 2035 ExprPtr->getPointeeType()->isObjCLifetimeType() && 2036 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 2037 Self.Diag(SrcExpr.get()->getLocStart(), 2038 diag::err_typecheck_incompatible_ownership) 2039 << SrcType << DestType << Sema::AA_Casting 2040 << SrcExpr.get()->getSourceRange(); 2041 return; 2042 } 2043 } 2044 } 2045 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 2046 Self.Diag(SrcExpr.get()->getLocStart(), 2047 diag::err_arc_convesion_of_weak_unavailable) 2048 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2049 SrcExpr = ExprError(); 2050 return; 2051 } 2052 } 2053 2054 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 2055 if (SrcExpr.isInvalid()) 2056 return; 2057 2058 if (Kind == CK_BitCast) 2059 checkCastAlign(); 2060} 2061 2062ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 2063 TypeSourceInfo *CastTypeInfo, 2064 SourceLocation RPLoc, 2065 Expr *CastExpr) { 2066 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2067 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2068 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 2069 2070 if (getLangOptions().CPlusPlus) { 2071 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false); 2072 } else { 2073 Op.CheckCStyleCast(); 2074 } 2075 2076 if (Op.SrcExpr.isInvalid()) 2077 return ExprError(); 2078 2079 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 2080 Op.ValueKind, Op.Kind, Op.SrcExpr.take(), 2081 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 2082} 2083 2084ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 2085 SourceLocation LPLoc, 2086 Expr *CastExpr, 2087 SourceLocation RPLoc) { 2088 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2089 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2090 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 2091 2092 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true); 2093 if (Op.SrcExpr.isInvalid()) 2094 return ExprError(); 2095 2096 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 2097 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(), 2098 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc)); 2099} 2100