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