SemaCast.cpp revision 288943
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/AST/ASTContext.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/ExprObjC.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Basic/TargetInfo.h" 25#include "clang/Sema/Initialization.h" 26#include "llvm/ADT/SmallVector.h" 27#include <set> 28using namespace clang; 29 30 31 32enum TryCastResult { 33 TC_NotApplicable, ///< The cast method is not applicable. 34 TC_Success, ///< The cast method is appropriate and successful. 35 TC_Failed ///< The cast method is appropriate, but failed. A 36 ///< diagnostic has been emitted. 37}; 38 39enum CastType { 40 CT_Const, ///< const_cast 41 CT_Static, ///< static_cast 42 CT_Reinterpret, ///< reinterpret_cast 43 CT_Dynamic, ///< dynamic_cast 44 CT_CStyle, ///< (Type)expr 45 CT_Functional ///< Type(expr) 46}; 47 48namespace { 49 struct CastOperation { 50 CastOperation(Sema &S, QualType destType, ExprResult src) 51 : Self(S), SrcExpr(src), DestType(destType), 52 ResultType(destType.getNonLValueExprType(S.Context)), 53 ValueKind(Expr::getValueKindForType(destType)), 54 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 55 56 if (const BuiltinType *placeholder = 57 src.get()->getType()->getAsPlaceholderType()) { 58 PlaceholderKind = placeholder->getKind(); 59 } else { 60 PlaceholderKind = (BuiltinType::Kind) 0; 61 } 62 } 63 64 Sema &Self; 65 ExprResult SrcExpr; 66 QualType DestType; 67 QualType ResultType; 68 ExprValueKind ValueKind; 69 CastKind Kind; 70 BuiltinType::Kind PlaceholderKind; 71 CXXCastPath BasePath; 72 bool IsARCUnbridgedCast; 73 74 SourceRange OpRange; 75 SourceRange DestRange; 76 77 // Top-level semantics-checking routines. 78 void CheckConstCast(); 79 void CheckReinterpretCast(); 80 void CheckStaticCast(); 81 void CheckDynamicCast(); 82 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); 83 void CheckCStyleCast(); 84 85 /// Complete an apparently-successful cast operation that yields 86 /// the given expression. 87 ExprResult complete(CastExpr *castExpr) { 88 // If this is an unbridged cast, wrap the result in an implicit 89 // cast that yields the unbridged-cast placeholder type. 90 if (IsARCUnbridgedCast) { 91 castExpr = ImplicitCastExpr::Create(Self.Context, 92 Self.Context.ARCUnbridgedCastTy, 93 CK_Dependent, castExpr, nullptr, 94 castExpr->getValueKind()); 95 } 96 return castExpr; 97 } 98 99 // Internal convenience methods. 100 101 /// Try to handle the given placeholder expression kind. Return 102 /// true if the source expression has the appropriate placeholder 103 /// kind. A placeholder can only be claimed once. 104 bool claimPlaceholder(BuiltinType::Kind K) { 105 if (PlaceholderKind != K) return false; 106 107 PlaceholderKind = (BuiltinType::Kind) 0; 108 return true; 109 } 110 111 bool isPlaceholder() const { 112 return PlaceholderKind != 0; 113 } 114 bool isPlaceholder(BuiltinType::Kind K) const { 115 return PlaceholderKind == K; 116 } 117 118 void checkCastAlign() { 119 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 120 } 121 122 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) { 123 assert(Self.getLangOpts().ObjCAutoRefCount); 124 125 Expr *src = SrcExpr.get(); 126 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) == 127 Sema::ACR_unbridged) 128 IsARCUnbridgedCast = true; 129 SrcExpr = src; 130 } 131 132 /// Check for and handle non-overload placeholder expressions. 133 void checkNonOverloadPlaceholders() { 134 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 135 return; 136 137 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 138 if (SrcExpr.isInvalid()) 139 return; 140 PlaceholderKind = (BuiltinType::Kind) 0; 141 } 142 }; 143} 144 145// The Try functions attempt a specific way of casting. If they succeed, they 146// return TC_Success. If their way of casting is not appropriate for the given 147// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 148// to emit if no other way succeeds. If their way of casting is appropriate but 149// fails, they return TC_Failed and *must* set diag; they can set it to 0 if 150// they emit a specialized diagnostic. 151// All diagnostics returned by these functions must expect the same three 152// arguments: 153// %0: Cast Type (a value from the CastType enumeration) 154// %1: Source Type 155// %2: Destination Type 156static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 157 QualType DestType, bool CStyle, 158 CastKind &Kind, 159 CXXCastPath &BasePath, 160 unsigned &msg); 161static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 162 QualType DestType, bool CStyle, 163 const SourceRange &OpRange, 164 unsigned &msg, 165 CastKind &Kind, 166 CXXCastPath &BasePath); 167static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 168 QualType DestType, bool CStyle, 169 const SourceRange &OpRange, 170 unsigned &msg, 171 CastKind &Kind, 172 CXXCastPath &BasePath); 173static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 174 CanQualType DestType, bool CStyle, 175 const SourceRange &OpRange, 176 QualType OrigSrcType, 177 QualType OrigDestType, unsigned &msg, 178 CastKind &Kind, 179 CXXCastPath &BasePath); 180static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 181 QualType SrcType, 182 QualType DestType,bool CStyle, 183 const SourceRange &OpRange, 184 unsigned &msg, 185 CastKind &Kind, 186 CXXCastPath &BasePath); 187 188static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 189 QualType DestType, 190 Sema::CheckedConversionKind CCK, 191 const SourceRange &OpRange, 192 unsigned &msg, CastKind &Kind, 193 bool ListInitialization); 194static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 195 QualType DestType, 196 Sema::CheckedConversionKind CCK, 197 const SourceRange &OpRange, 198 unsigned &msg, CastKind &Kind, 199 CXXCastPath &BasePath, 200 bool ListInitialization); 201static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 202 QualType DestType, bool CStyle, 203 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 (getLangOpts().CPlusPlus) { 226 // Check that there are no default arguments (C++ only). 227 CheckExtraCXXDefaultArguments(D); 228 } 229 230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, 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 = E; 240 QualType DestType = DestTInfo->getType(); 241 242 // If the type is dependent, we won't do the semantic analysis now. 243 bool TypeDependent = 244 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.get(), DestTInfo, 261 OpLoc, Parens.getEnd(), 262 AngleBrackets)); 263 264 case tok::kw_dynamic_cast: { 265 if (!TypeDependent) { 266 Op.CheckDynamicCast(); 267 if (Op.SrcExpr.isInvalid()) 268 return ExprError(); 269 } 270 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 271 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 272 &Op.BasePath, DestTInfo, 273 OpLoc, Parens.getEnd(), 274 AngleBrackets)); 275 } 276 case tok::kw_reinterpret_cast: { 277 if (!TypeDependent) { 278 Op.CheckReinterpretCast(); 279 if (Op.SrcExpr.isInvalid()) 280 return ExprError(); 281 } 282 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 283 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 284 nullptr, DestTInfo, OpLoc, 285 Parens.getEnd(), 286 AngleBrackets)); 287 } 288 case tok::kw_static_cast: { 289 if (!TypeDependent) { 290 Op.CheckStaticCast(); 291 if (Op.SrcExpr.isInvalid()) 292 return ExprError(); 293 } 294 295 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, 296 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 297 &Op.BasePath, DestTInfo, 298 OpLoc, Parens.getEnd(), 299 AngleBrackets)); 300 } 301 } 302} 303 304/// Try to diagnose a failed overloaded cast. Returns true if 305/// diagnostics were emitted. 306static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 307 SourceRange range, Expr *src, 308 QualType destType, 309 bool listInitialization) { 310 switch (CT) { 311 // These cast kinds don't consider user-defined conversions. 312 case CT_Const: 313 case CT_Reinterpret: 314 case CT_Dynamic: 315 return false; 316 317 // These do. 318 case CT_Static: 319 case CT_CStyle: 320 case CT_Functional: 321 break; 322 } 323 324 QualType srcType = src->getType(); 325 if (!destType->isRecordType() && !srcType->isRecordType()) 326 return false; 327 328 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 329 InitializationKind initKind 330 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 331 range, listInitialization) 332 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, 333 listInitialization) 334 : InitializationKind::CreateCast(/*type range?*/ range); 335 InitializationSequence sequence(S, entity, initKind, src); 336 337 assert(sequence.Failed() && "initialization succeeded on second try?"); 338 switch (sequence.getFailureKind()) { 339 default: return false; 340 341 case InitializationSequence::FK_ConstructorOverloadFailed: 342 case InitializationSequence::FK_UserConversionOverloadFailed: 343 break; 344 } 345 346 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 347 348 unsigned msg = 0; 349 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 350 351 switch (sequence.getFailedOverloadResult()) { 352 case OR_Success: llvm_unreachable("successful failed overload"); 353 case OR_No_Viable_Function: 354 if (candidates.empty()) 355 msg = diag::err_ovl_no_conversion_in_cast; 356 else 357 msg = diag::err_ovl_no_viable_conversion_in_cast; 358 howManyCandidates = OCD_AllCandidates; 359 break; 360 361 case OR_Ambiguous: 362 msg = diag::err_ovl_ambiguous_conversion_in_cast; 363 howManyCandidates = OCD_ViableCandidates; 364 break; 365 366 case OR_Deleted: 367 msg = diag::err_ovl_deleted_conversion_in_cast; 368 howManyCandidates = OCD_ViableCandidates; 369 break; 370 } 371 372 S.Diag(range.getBegin(), msg) 373 << CT << srcType << destType 374 << range << src->getSourceRange(); 375 376 candidates.NoteCandidates(S, howManyCandidates, src); 377 378 return true; 379} 380 381/// Diagnose a failed cast. 382static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 383 SourceRange opRange, Expr *src, QualType destType, 384 bool listInitialization) { 385 if (msg == diag::err_bad_cxx_cast_generic && 386 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, 387 listInitialization)) 388 return; 389 390 S.Diag(opRange.getBegin(), msg) << castType 391 << src->getType() << destType << opRange << src->getSourceRange(); 392 393 // Detect if both types are (ptr to) class, and note any incompleteness. 394 int DifferentPtrness = 0; 395 QualType From = destType; 396 if (auto Ptr = From->getAs<PointerType>()) { 397 From = Ptr->getPointeeType(); 398 DifferentPtrness++; 399 } 400 QualType To = src->getType(); 401 if (auto Ptr = To->getAs<PointerType>()) { 402 To = Ptr->getPointeeType(); 403 DifferentPtrness--; 404 } 405 if (!DifferentPtrness) { 406 auto RecFrom = From->getAs<RecordType>(); 407 auto RecTo = To->getAs<RecordType>(); 408 if (RecFrom && RecTo) { 409 auto DeclFrom = RecFrom->getAsCXXRecordDecl(); 410 if (!DeclFrom->isCompleteDefinition()) 411 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) 412 << DeclFrom->getDeclName(); 413 auto DeclTo = RecTo->getAsCXXRecordDecl(); 414 if (!DeclTo->isCompleteDefinition()) 415 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) 416 << DeclTo->getDeclName(); 417 } 418 } 419} 420 421/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes, 422/// this removes one level of indirection from both types, provided that they're 423/// the same kind of pointer (plain or to-member). Unlike the Sema function, 424/// this one doesn't care if the two pointers-to-member don't point into the 425/// same class. This is because CastsAwayConstness doesn't care. 426static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) { 427 const PointerType *T1PtrType = T1->getAs<PointerType>(), 428 *T2PtrType = T2->getAs<PointerType>(); 429 if (T1PtrType && T2PtrType) { 430 T1 = T1PtrType->getPointeeType(); 431 T2 = T2PtrType->getPointeeType(); 432 return true; 433 } 434 const ObjCObjectPointerType *T1ObjCPtrType = 435 T1->getAs<ObjCObjectPointerType>(), 436 *T2ObjCPtrType = 437 T2->getAs<ObjCObjectPointerType>(); 438 if (T1ObjCPtrType) { 439 if (T2ObjCPtrType) { 440 T1 = T1ObjCPtrType->getPointeeType(); 441 T2 = T2ObjCPtrType->getPointeeType(); 442 return true; 443 } 444 else if (T2PtrType) { 445 T1 = T1ObjCPtrType->getPointeeType(); 446 T2 = T2PtrType->getPointeeType(); 447 return true; 448 } 449 } 450 else if (T2ObjCPtrType) { 451 if (T1PtrType) { 452 T2 = T2ObjCPtrType->getPointeeType(); 453 T1 = T1PtrType->getPointeeType(); 454 return true; 455 } 456 } 457 458 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 459 *T2MPType = T2->getAs<MemberPointerType>(); 460 if (T1MPType && T2MPType) { 461 T1 = T1MPType->getPointeeType(); 462 T2 = T2MPType->getPointeeType(); 463 return true; 464 } 465 466 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(), 467 *T2BPType = T2->getAs<BlockPointerType>(); 468 if (T1BPType && T2BPType) { 469 T1 = T1BPType->getPointeeType(); 470 T2 = T2BPType->getPointeeType(); 471 return true; 472 } 473 474 return false; 475} 476 477/// CastsAwayConstness - Check if the pointer conversion from SrcType to 478/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by 479/// the cast checkers. Both arguments must denote pointer (possibly to member) 480/// types. 481/// 482/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 483/// 484/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 485static bool 486CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 487 bool CheckCVR, bool CheckObjCLifetime, 488 QualType *TheOffendingSrcType = nullptr, 489 QualType *TheOffendingDestType = nullptr, 490 Qualifiers *CastAwayQualifiers = nullptr) { 491 // If the only checking we care about is for Objective-C lifetime qualifiers, 492 // and we're not in ARC mode, there's nothing to check. 493 if (!CheckCVR && CheckObjCLifetime && 494 !Self.Context.getLangOpts().ObjCAutoRefCount) 495 return false; 496 497 // Casting away constness is defined in C++ 5.2.11p8 with reference to 498 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since 499 // the rules are non-trivial. So first we construct Tcv *...cv* as described 500 // in C++ 5.2.11p8. 501 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 502 SrcType->isBlockPointerType()) && 503 "Source type is not pointer or pointer to member."); 504 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 505 DestType->isBlockPointerType()) && 506 "Destination type is not pointer or pointer to member."); 507 508 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 509 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 510 SmallVector<Qualifiers, 8> cv1, cv2; 511 512 // Find the qualifiers. We only care about cvr-qualifiers for the 513 // purpose of this check, because other qualifiers (address spaces, 514 // Objective-C GC, etc.) are part of the type's identity. 515 QualType PrevUnwrappedSrcType = UnwrappedSrcType; 516 QualType PrevUnwrappedDestType = UnwrappedDestType; 517 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 518 // Determine the relevant qualifiers at this level. 519 Qualifiers SrcQuals, DestQuals; 520 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 521 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 522 523 Qualifiers RetainedSrcQuals, RetainedDestQuals; 524 if (CheckCVR) { 525 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers()); 526 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers()); 527 528 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType && 529 TheOffendingDestType && CastAwayQualifiers) { 530 *TheOffendingSrcType = PrevUnwrappedSrcType; 531 *TheOffendingDestType = PrevUnwrappedDestType; 532 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals; 533 } 534 } 535 536 if (CheckObjCLifetime && 537 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 538 return true; 539 540 cv1.push_back(RetainedSrcQuals); 541 cv2.push_back(RetainedDestQuals); 542 543 PrevUnwrappedSrcType = UnwrappedSrcType; 544 PrevUnwrappedDestType = UnwrappedDestType; 545 } 546 if (cv1.empty()) 547 return false; 548 549 // Construct void pointers with those qualifiers (in reverse order of 550 // unwrapping, of course). 551 QualType SrcConstruct = Self.Context.VoidTy; 552 QualType DestConstruct = Self.Context.VoidTy; 553 ASTContext &Context = Self.Context; 554 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(), 555 i2 = cv2.rbegin(); 556 i1 != cv1.rend(); ++i1, ++i2) { 557 SrcConstruct 558 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1)); 559 DestConstruct 560 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2)); 561 } 562 563 // Test if they're compatible. 564 bool ObjCLifetimeConversion; 565 return SrcConstruct != DestConstruct && 566 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false, 567 ObjCLifetimeConversion); 568} 569 570/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 571/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 572/// checked downcasts in class hierarchies. 573void CastOperation::CheckDynamicCast() { 574 if (ValueKind == VK_RValue) 575 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 576 else if (isPlaceholder()) 577 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 578 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 579 return; 580 581 QualType OrigSrcType = SrcExpr.get()->getType(); 582 QualType DestType = Self.Context.getCanonicalType(this->DestType); 583 584 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 585 // or "pointer to cv void". 586 587 QualType DestPointee; 588 const PointerType *DestPointer = DestType->getAs<PointerType>(); 589 const ReferenceType *DestReference = nullptr; 590 if (DestPointer) { 591 DestPointee = DestPointer->getPointeeType(); 592 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 593 DestPointee = DestReference->getPointeeType(); 594 } else { 595 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 596 << this->DestType << DestRange; 597 SrcExpr = ExprError(); 598 return; 599 } 600 601 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 602 if (DestPointee->isVoidType()) { 603 assert(DestPointer && "Reference to void is not possible"); 604 } else if (DestRecord) { 605 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 606 diag::err_bad_dynamic_cast_incomplete, 607 DestRange)) { 608 SrcExpr = ExprError(); 609 return; 610 } 611 } else { 612 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 613 << DestPointee.getUnqualifiedType() << DestRange; 614 SrcExpr = ExprError(); 615 return; 616 } 617 618 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 619 // complete class type, [...]. If T is an lvalue reference type, v shall be 620 // an lvalue of a complete class type, [...]. If T is an rvalue reference 621 // type, v shall be an expression having a complete class type, [...] 622 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 623 QualType SrcPointee; 624 if (DestPointer) { 625 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 626 SrcPointee = SrcPointer->getPointeeType(); 627 } else { 628 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 629 << OrigSrcType << SrcExpr.get()->getSourceRange(); 630 SrcExpr = ExprError(); 631 return; 632 } 633 } else if (DestReference->isLValueReferenceType()) { 634 if (!SrcExpr.get()->isLValue()) { 635 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 636 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 637 } 638 SrcPointee = SrcType; 639 } else { 640 // If we're dynamic_casting from a prvalue to an rvalue reference, we need 641 // to materialize the prvalue before we bind the reference to it. 642 if (SrcExpr.get()->isRValue()) 643 SrcExpr = new (Self.Context) MaterializeTemporaryExpr( 644 SrcType, SrcExpr.get(), /*IsLValueReference*/false); 645 SrcPointee = SrcType; 646 } 647 648 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 649 if (SrcRecord) { 650 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 651 diag::err_bad_dynamic_cast_incomplete, 652 SrcExpr.get())) { 653 SrcExpr = ExprError(); 654 return; 655 } 656 } else { 657 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 658 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 659 SrcExpr = ExprError(); 660 return; 661 } 662 663 assert((DestPointer || DestReference) && 664 "Bad destination non-ptr/ref slipped through."); 665 assert((DestRecord || DestPointee->isVoidType()) && 666 "Bad destination pointee slipped through."); 667 assert(SrcRecord && "Bad source pointee slipped through."); 668 669 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 670 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 671 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 672 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 673 SrcExpr = ExprError(); 674 return; 675 } 676 677 // C++ 5.2.7p3: If the type of v is the same as the required result type, 678 // [except for cv]. 679 if (DestRecord == SrcRecord) { 680 Kind = CK_NoOp; 681 return; 682 } 683 684 // C++ 5.2.7p5 685 // Upcasts are resolved statically. 686 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) { 687 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 688 OpRange.getBegin(), OpRange, 689 &BasePath)) { 690 SrcExpr = ExprError(); 691 return; 692 } 693 694 Kind = CK_DerivedToBase; 695 return; 696 } 697 698 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 699 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 700 assert(SrcDecl && "Definition missing"); 701 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 702 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 703 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 704 SrcExpr = ExprError(); 705 } 706 707 // dynamic_cast is not available with -fno-rtti. 708 // As an exception, dynamic_cast to void* is available because it doesn't 709 // use RTTI. 710 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { 711 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); 712 SrcExpr = ExprError(); 713 return; 714 } 715 716 // Done. Everything else is run-time checks. 717 Kind = CK_Dynamic; 718} 719 720/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 721/// Refer to C++ 5.2.11 for details. const_cast is typically used in code 722/// like this: 723/// const char *str = "literal"; 724/// legacy_function(const_cast\<char*\>(str)); 725void CastOperation::CheckConstCast() { 726 if (ValueKind == VK_RValue) 727 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 728 else if (isPlaceholder()) 729 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 730 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 731 return; 732 733 unsigned msg = diag::err_bad_cxx_cast_generic; 734 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success 735 && msg != 0) { 736 Self.Diag(OpRange.getBegin(), msg) << CT_Const 737 << SrcExpr.get()->getType() << DestType << OpRange; 738 SrcExpr = ExprError(); 739 } 740} 741 742/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast 743/// or downcast between respective pointers or references. 744static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, 745 QualType DestType, 746 SourceRange OpRange) { 747 QualType SrcType = SrcExpr->getType(); 748 // When casting from pointer or reference, get pointee type; use original 749 // type otherwise. 750 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); 751 const CXXRecordDecl *SrcRD = 752 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); 753 754 // Examining subobjects for records is only possible if the complete and 755 // valid definition is available. Also, template instantiation is not 756 // allowed here. 757 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) 758 return; 759 760 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); 761 762 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) 763 return; 764 765 enum { 766 ReinterpretUpcast, 767 ReinterpretDowncast 768 } ReinterpretKind; 769 770 CXXBasePaths BasePaths; 771 772 if (SrcRD->isDerivedFrom(DestRD, BasePaths)) 773 ReinterpretKind = ReinterpretUpcast; 774 else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) 775 ReinterpretKind = ReinterpretDowncast; 776 else 777 return; 778 779 bool VirtualBase = true; 780 bool NonZeroOffset = false; 781 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), 782 E = BasePaths.end(); 783 I != E; ++I) { 784 const CXXBasePath &Path = *I; 785 CharUnits Offset = CharUnits::Zero(); 786 bool IsVirtual = false; 787 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); 788 IElem != EElem; ++IElem) { 789 IsVirtual = IElem->Base->isVirtual(); 790 if (IsVirtual) 791 break; 792 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); 793 assert(BaseRD && "Base type should be a valid unqualified class type"); 794 // Don't check if any base has invalid declaration or has no definition 795 // since it has no layout info. 796 const CXXRecordDecl *Class = IElem->Class, 797 *ClassDefinition = Class->getDefinition(); 798 if (Class->isInvalidDecl() || !ClassDefinition || 799 !ClassDefinition->isCompleteDefinition()) 800 return; 801 802 const ASTRecordLayout &DerivedLayout = 803 Self.Context.getASTRecordLayout(Class); 804 Offset += DerivedLayout.getBaseClassOffset(BaseRD); 805 } 806 if (!IsVirtual) { 807 // Don't warn if any path is a non-virtually derived base at offset zero. 808 if (Offset.isZero()) 809 return; 810 // Offset makes sense only for non-virtual bases. 811 else 812 NonZeroOffset = true; 813 } 814 VirtualBase = VirtualBase && IsVirtual; 815 } 816 817 (void) NonZeroOffset; // Silence set but not used warning. 818 assert((VirtualBase || NonZeroOffset) && 819 "Should have returned if has non-virtual base with zero offset"); 820 821 QualType BaseType = 822 ReinterpretKind == ReinterpretUpcast? DestType : SrcType; 823 QualType DerivedType = 824 ReinterpretKind == ReinterpretUpcast? SrcType : DestType; 825 826 SourceLocation BeginLoc = OpRange.getBegin(); 827 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) 828 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) 829 << OpRange; 830 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) 831 << int(ReinterpretKind) 832 << FixItHint::CreateReplacement(BeginLoc, "static_cast"); 833} 834 835/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 836/// valid. 837/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 838/// like this: 839/// char *bytes = reinterpret_cast\<char*\>(int_ptr); 840void CastOperation::CheckReinterpretCast() { 841 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) 842 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 843 else 844 checkNonOverloadPlaceholders(); 845 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 846 return; 847 848 unsigned msg = diag::err_bad_cxx_cast_generic; 849 TryCastResult tcr = 850 TryReinterpretCast(Self, SrcExpr, DestType, 851 /*CStyle*/false, OpRange, msg, Kind); 852 if (tcr != TC_Success && msg != 0) 853 { 854 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 855 return; 856 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 857 //FIXME: &f<int>; is overloaded and resolvable 858 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 859 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 860 << DestType << OpRange; 861 Self.NoteAllOverloadCandidates(SrcExpr.get()); 862 863 } else { 864 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), 865 DestType, /*listInitialization=*/false); 866 } 867 SrcExpr = ExprError(); 868 } else if (tcr == TC_Success) { 869 if (Self.getLangOpts().ObjCAutoRefCount) 870 checkObjCARCConversion(Sema::CCK_OtherCast); 871 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); 872 } 873} 874 875 876/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 877/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 878/// implicit conversions explicit and getting rid of data loss warnings. 879void CastOperation::CheckStaticCast() { 880 if (isPlaceholder()) { 881 checkNonOverloadPlaceholders(); 882 if (SrcExpr.isInvalid()) 883 return; 884 } 885 886 // This test is outside everything else because it's the only case where 887 // a non-lvalue-reference target type does not lead to decay. 888 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 889 if (DestType->isVoidType()) { 890 Kind = CK_ToVoid; 891 892 if (claimPlaceholder(BuiltinType::Overload)) { 893 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 894 false, // Decay Function to ptr 895 true, // Complain 896 OpRange, DestType, diag::err_bad_static_cast_overload); 897 if (SrcExpr.isInvalid()) 898 return; 899 } 900 901 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 902 return; 903 } 904 905 if (ValueKind == VK_RValue && !DestType->isRecordType() && 906 !isPlaceholder(BuiltinType::Overload)) { 907 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 908 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 909 return; 910 } 911 912 unsigned msg = diag::err_bad_cxx_cast_generic; 913 TryCastResult tcr 914 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 915 Kind, BasePath, /*ListInitialization=*/false); 916 if (tcr != TC_Success && msg != 0) { 917 if (SrcExpr.isInvalid()) 918 return; 919 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 920 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 921 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 922 << oe->getName() << DestType << OpRange 923 << oe->getQualifierLoc().getSourceRange(); 924 Self.NoteAllOverloadCandidates(SrcExpr.get()); 925 } else { 926 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, 927 /*listInitialization=*/false); 928 } 929 SrcExpr = ExprError(); 930 } else if (tcr == TC_Success) { 931 if (Kind == CK_BitCast) 932 checkCastAlign(); 933 if (Self.getLangOpts().ObjCAutoRefCount) 934 checkObjCARCConversion(Sema::CCK_OtherCast); 935 } else if (Kind == CK_BitCast) { 936 checkCastAlign(); 937 } 938} 939 940/// TryStaticCast - Check if a static cast can be performed, and do so if 941/// possible. If @p CStyle, ignore access restrictions on hierarchy casting 942/// and casting away constness. 943static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 944 QualType DestType, 945 Sema::CheckedConversionKind CCK, 946 const SourceRange &OpRange, unsigned &msg, 947 CastKind &Kind, CXXCastPath &BasePath, 948 bool ListInitialization) { 949 // Determine whether we have the semantics of a C-style cast. 950 bool CStyle 951 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 952 953 // The order the tests is not entirely arbitrary. There is one conversion 954 // that can be handled in two different ways. Given: 955 // struct A {}; 956 // struct B : public A { 957 // B(); B(const A&); 958 // }; 959 // const A &a = B(); 960 // the cast static_cast<const B&>(a) could be seen as either a static 961 // reference downcast, or an explicit invocation of the user-defined 962 // conversion using B's conversion constructor. 963 // DR 427 specifies that the downcast is to be applied here. 964 965 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 966 // Done outside this function. 967 968 TryCastResult tcr; 969 970 // C++ 5.2.9p5, reference downcast. 971 // See the function for details. 972 // DR 427 specifies that this is to be applied before paragraph 2. 973 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, 974 OpRange, msg, Kind, BasePath); 975 if (tcr != TC_NotApplicable) 976 return tcr; 977 978 // C++11 [expr.static.cast]p3: 979 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 980 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 981 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 982 BasePath, msg); 983 if (tcr != TC_NotApplicable) 984 return tcr; 985 986 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 987 // [...] if the declaration "T t(e);" is well-formed, [...]. 988 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 989 Kind, ListInitialization); 990 if (SrcExpr.isInvalid()) 991 return TC_Failed; 992 if (tcr != TC_NotApplicable) 993 return tcr; 994 995 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 996 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 997 // conversions, subject to further restrictions. 998 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 999 // of qualification conversions impossible. 1000 // In the CStyle case, the earlier attempt to const_cast should have taken 1001 // care of reverse qualification conversions. 1002 1003 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 1004 1005 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 1006 // converted to an integral type. [...] A value of a scoped enumeration type 1007 // can also be explicitly converted to a floating-point type [...]. 1008 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 1009 if (Enum->getDecl()->isScoped()) { 1010 if (DestType->isBooleanType()) { 1011 Kind = CK_IntegralToBoolean; 1012 return TC_Success; 1013 } else if (DestType->isIntegralType(Self.Context)) { 1014 Kind = CK_IntegralCast; 1015 return TC_Success; 1016 } else if (DestType->isRealFloatingType()) { 1017 Kind = CK_IntegralToFloating; 1018 return TC_Success; 1019 } 1020 } 1021 } 1022 1023 // Reverse integral promotion/conversion. All such conversions are themselves 1024 // again integral promotions or conversions and are thus already handled by 1025 // p2 (TryDirectInitialization above). 1026 // (Note: any data loss warnings should be suppressed.) 1027 // The exception is the reverse of enum->integer, i.e. integer->enum (and 1028 // enum->enum). See also C++ 5.2.9p7. 1029 // The same goes for reverse floating point promotion/conversion and 1030 // floating-integral conversions. Again, only floating->enum is relevant. 1031 if (DestType->isEnumeralType()) { 1032 if (SrcType->isIntegralOrEnumerationType()) { 1033 Kind = CK_IntegralCast; 1034 return TC_Success; 1035 } else if (SrcType->isRealFloatingType()) { 1036 Kind = CK_FloatingToIntegral; 1037 return TC_Success; 1038 } 1039 } 1040 1041 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 1042 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 1043 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 1044 Kind, BasePath); 1045 if (tcr != TC_NotApplicable) 1046 return tcr; 1047 1048 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 1049 // conversion. C++ 5.2.9p9 has additional information. 1050 // DR54's access restrictions apply here also. 1051 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 1052 OpRange, msg, Kind, BasePath); 1053 if (tcr != TC_NotApplicable) 1054 return tcr; 1055 1056 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 1057 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 1058 // just the usual constness stuff. 1059 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 1060 QualType SrcPointee = SrcPointer->getPointeeType(); 1061 if (SrcPointee->isVoidType()) { 1062 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 1063 QualType DestPointee = DestPointer->getPointeeType(); 1064 if (DestPointee->isIncompleteOrObjectType()) { 1065 // This is definitely the intended conversion, but it might fail due 1066 // to a qualifier violation. Note that we permit Objective-C lifetime 1067 // and GC qualifier mismatches here. 1068 if (!CStyle) { 1069 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 1070 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 1071 DestPointeeQuals.removeObjCGCAttr(); 1072 DestPointeeQuals.removeObjCLifetime(); 1073 SrcPointeeQuals.removeObjCGCAttr(); 1074 SrcPointeeQuals.removeObjCLifetime(); 1075 if (DestPointeeQuals != SrcPointeeQuals && 1076 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 1077 msg = diag::err_bad_cxx_cast_qualifiers_away; 1078 return TC_Failed; 1079 } 1080 } 1081 Kind = CK_BitCast; 1082 return TC_Success; 1083 } 1084 1085 // Microsoft permits static_cast from 'pointer-to-void' to 1086 // 'pointer-to-function'. 1087 if (!CStyle && Self.getLangOpts().MSVCCompat && 1088 DestPointee->isFunctionType()) { 1089 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; 1090 Kind = CK_BitCast; 1091 return TC_Success; 1092 } 1093 } 1094 else if (DestType->isObjCObjectPointerType()) { 1095 // allow both c-style cast and static_cast of objective-c pointers as 1096 // they are pervasive. 1097 Kind = CK_CPointerToObjCPointerCast; 1098 return TC_Success; 1099 } 1100 else if (CStyle && DestType->isBlockPointerType()) { 1101 // allow c-style cast of void * to block pointers. 1102 Kind = CK_AnyPointerToBlockPointerCast; 1103 return TC_Success; 1104 } 1105 } 1106 } 1107 // Allow arbitray objective-c pointer conversion with static casts. 1108 if (SrcType->isObjCObjectPointerType() && 1109 DestType->isObjCObjectPointerType()) { 1110 Kind = CK_BitCast; 1111 return TC_Success; 1112 } 1113 // Allow ns-pointer to cf-pointer conversion in either direction 1114 // with static casts. 1115 if (!CStyle && 1116 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) 1117 return TC_Success; 1118 1119 // See if it looks like the user is trying to convert between 1120 // related record types, and select a better diagnostic if so. 1121 if (auto SrcPointer = SrcType->getAs<PointerType>()) 1122 if (auto DestPointer = DestType->getAs<PointerType>()) 1123 if (SrcPointer->getPointeeType()->getAs<RecordType>() && 1124 DestPointer->getPointeeType()->getAs<RecordType>()) 1125 msg = diag::err_bad_cxx_cast_unrelated_class; 1126 1127 // We tried everything. Everything! Nothing works! :-( 1128 return TC_NotApplicable; 1129} 1130 1131/// Tests whether a conversion according to N2844 is valid. 1132TryCastResult 1133TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, 1134 bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 1135 unsigned &msg) { 1136 // C++11 [expr.static.cast]p3: 1137 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 1138 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1139 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 1140 if (!R) 1141 return TC_NotApplicable; 1142 1143 if (!SrcExpr->isGLValue()) 1144 return TC_NotApplicable; 1145 1146 // Because we try the reference downcast before this function, from now on 1147 // this is the only cast possibility, so we issue an error if we fail now. 1148 // FIXME: Should allow casting away constness if CStyle. 1149 bool DerivedToBase; 1150 bool ObjCConversion; 1151 bool ObjCLifetimeConversion; 1152 QualType FromType = SrcExpr->getType(); 1153 QualType ToType = R->getPointeeType(); 1154 if (CStyle) { 1155 FromType = FromType.getUnqualifiedType(); 1156 ToType = ToType.getUnqualifiedType(); 1157 } 1158 1159 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(), 1160 ToType, FromType, 1161 DerivedToBase, ObjCConversion, 1162 ObjCLifetimeConversion) 1163 < Sema::Ref_Compatible_With_Added_Qualification) { 1164 if (CStyle) 1165 return TC_NotApplicable; 1166 msg = diag::err_bad_lvalue_to_rvalue_cast; 1167 return TC_Failed; 1168 } 1169 1170 if (DerivedToBase) { 1171 Kind = CK_DerivedToBase; 1172 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1173 /*DetectVirtual=*/true); 1174 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths)) 1175 return TC_NotApplicable; 1176 1177 Self.BuildBasePathArray(Paths, BasePath); 1178 } else 1179 Kind = CK_NoOp; 1180 1181 return TC_Success; 1182} 1183 1184/// Tests whether a conversion according to C++ 5.2.9p5 is valid. 1185TryCastResult 1186TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 1187 bool CStyle, const SourceRange &OpRange, 1188 unsigned &msg, CastKind &Kind, 1189 CXXCastPath &BasePath) { 1190 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 1191 // cast to type "reference to cv2 D", where D is a class derived from B, 1192 // if a valid standard conversion from "pointer to D" to "pointer to B" 1193 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1194 // In addition, DR54 clarifies that the base must be accessible in the 1195 // current context. Although the wording of DR54 only applies to the pointer 1196 // variant of this rule, the intent is clearly for it to apply to the this 1197 // conversion as well. 1198 1199 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1200 if (!DestReference) { 1201 return TC_NotApplicable; 1202 } 1203 bool RValueRef = DestReference->isRValueReferenceType(); 1204 if (!RValueRef && !SrcExpr->isLValue()) { 1205 // We know the left side is an lvalue reference, so we can suggest a reason. 1206 msg = diag::err_bad_cxx_cast_rvalue; 1207 return TC_NotApplicable; 1208 } 1209 1210 QualType DestPointee = DestReference->getPointeeType(); 1211 1212 // FIXME: If the source is a prvalue, we should issue a warning (because the 1213 // cast always has undefined behavior), and for AST consistency, we should 1214 // materialize a temporary. 1215 return TryStaticDowncast(Self, 1216 Self.Context.getCanonicalType(SrcExpr->getType()), 1217 Self.Context.getCanonicalType(DestPointee), CStyle, 1218 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1219 BasePath); 1220} 1221 1222/// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1223TryCastResult 1224TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1225 bool CStyle, const SourceRange &OpRange, 1226 unsigned &msg, CastKind &Kind, 1227 CXXCastPath &BasePath) { 1228 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1229 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1230 // is a class derived from B, if a valid standard conversion from "pointer 1231 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1232 // class of D. 1233 // In addition, DR54 clarifies that the base must be accessible in the 1234 // current context. 1235 1236 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1237 if (!DestPointer) { 1238 return TC_NotApplicable; 1239 } 1240 1241 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1242 if (!SrcPointer) { 1243 msg = diag::err_bad_static_cast_pointer_nonpointer; 1244 return TC_NotApplicable; 1245 } 1246 1247 return TryStaticDowncast(Self, 1248 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1249 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1250 CStyle, OpRange, SrcType, DestType, msg, Kind, 1251 BasePath); 1252} 1253 1254/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1255/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1256/// DestType is possible and allowed. 1257TryCastResult 1258TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1259 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType, 1260 QualType OrigDestType, unsigned &msg, 1261 CastKind &Kind, CXXCastPath &BasePath) { 1262 // We can only work with complete types. But don't complain if it doesn't work 1263 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) || 1264 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0)) 1265 return TC_NotApplicable; 1266 1267 // Downcast can only happen in class hierarchies, so we need classes. 1268 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1269 return TC_NotApplicable; 1270 } 1271 1272 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1273 /*DetectVirtual=*/true); 1274 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) { 1275 return TC_NotApplicable; 1276 } 1277 1278 // Target type does derive from source type. Now we're serious. If an error 1279 // appears now, it's not ignored. 1280 // This may not be entirely in line with the standard. Take for example: 1281 // struct A {}; 1282 // struct B : virtual A { 1283 // B(A&); 1284 // }; 1285 // 1286 // void f() 1287 // { 1288 // (void)static_cast<const B&>(*((A*)0)); 1289 // } 1290 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1291 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1292 // However, both GCC and Comeau reject this example, and accepting it would 1293 // mean more complex code if we're to preserve the nice error message. 1294 // FIXME: Being 100% compliant here would be nice to have. 1295 1296 // Must preserve cv, as always, unless we're in C-style mode. 1297 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1298 msg = diag::err_bad_cxx_cast_qualifiers_away; 1299 return TC_Failed; 1300 } 1301 1302 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1303 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1304 // that it builds the paths in reverse order. 1305 // To sum up: record all paths to the base and build a nice string from 1306 // them. Use it to spice up the error message. 1307 if (!Paths.isRecordingPaths()) { 1308 Paths.clear(); 1309 Paths.setRecordingPaths(true); 1310 Self.IsDerivedFrom(DestType, SrcType, Paths); 1311 } 1312 std::string PathDisplayStr; 1313 std::set<unsigned> DisplayedPaths; 1314 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end(); 1315 PI != PE; ++PI) { 1316 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) { 1317 // We haven't displayed a path to this particular base 1318 // class subobject yet. 1319 PathDisplayStr += "\n "; 1320 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(), 1321 EE = PI->rend(); 1322 EI != EE; ++EI) 1323 PathDisplayStr += EI->Base->getType().getAsString() + " -> "; 1324 PathDisplayStr += QualType(DestType).getAsString(); 1325 } 1326 } 1327 1328 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1329 << QualType(SrcType).getUnqualifiedType() 1330 << QualType(DestType).getUnqualifiedType() 1331 << PathDisplayStr << OpRange; 1332 msg = 0; 1333 return TC_Failed; 1334 } 1335 1336 if (Paths.getDetectedVirtual() != nullptr) { 1337 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1338 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1339 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1340 msg = 0; 1341 return TC_Failed; 1342 } 1343 1344 if (!CStyle) { 1345 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1346 SrcType, DestType, 1347 Paths.front(), 1348 diag::err_downcast_from_inaccessible_base)) { 1349 case Sema::AR_accessible: 1350 case Sema::AR_delayed: // be optimistic 1351 case Sema::AR_dependent: // be optimistic 1352 break; 1353 1354 case Sema::AR_inaccessible: 1355 msg = 0; 1356 return TC_Failed; 1357 } 1358 } 1359 1360 Self.BuildBasePathArray(Paths, BasePath); 1361 Kind = CK_BaseToDerived; 1362 return TC_Success; 1363} 1364 1365/// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1366/// C++ 5.2.9p9 is valid: 1367/// 1368/// An rvalue of type "pointer to member of D of type cv1 T" can be 1369/// converted to an rvalue of type "pointer to member of B of type cv2 T", 1370/// where B is a base class of D [...]. 1371/// 1372TryCastResult 1373TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1374 QualType DestType, bool CStyle, 1375 const SourceRange &OpRange, 1376 unsigned &msg, CastKind &Kind, 1377 CXXCastPath &BasePath) { 1378 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1379 if (!DestMemPtr) 1380 return TC_NotApplicable; 1381 1382 bool WasOverloadedFunction = false; 1383 DeclAccessPair FoundOverload; 1384 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1385 if (FunctionDecl *Fn 1386 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1387 FoundOverload)) { 1388 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1389 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1390 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1391 WasOverloadedFunction = true; 1392 } 1393 } 1394 1395 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1396 if (!SrcMemPtr) { 1397 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1398 return TC_NotApplicable; 1399 } 1400 1401 // T == T, modulo cv 1402 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1403 DestMemPtr->getPointeeType())) 1404 return TC_NotApplicable; 1405 1406 // B base of D 1407 QualType SrcClass(SrcMemPtr->getClass(), 0); 1408 QualType DestClass(DestMemPtr->getClass(), 0); 1409 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1410 /*DetectVirtual=*/true); 1411 if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) || 1412 !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) { 1413 return TC_NotApplicable; 1414 } 1415 1416 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1417 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1418 Paths.clear(); 1419 Paths.setRecordingPaths(true); 1420 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths); 1421 assert(StillOkay); 1422 (void)StillOkay; 1423 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1424 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1425 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1426 msg = 0; 1427 return TC_Failed; 1428 } 1429 1430 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1431 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1432 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1433 msg = 0; 1434 return TC_Failed; 1435 } 1436 1437 if (!CStyle) { 1438 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1439 DestClass, SrcClass, 1440 Paths.front(), 1441 diag::err_upcast_to_inaccessible_base)) { 1442 case Sema::AR_accessible: 1443 case Sema::AR_delayed: 1444 case Sema::AR_dependent: 1445 // Optimistically assume that the delayed and dependent cases 1446 // will work out. 1447 break; 1448 1449 case Sema::AR_inaccessible: 1450 msg = 0; 1451 return TC_Failed; 1452 } 1453 } 1454 1455 if (WasOverloadedFunction) { 1456 // Resolve the address of the overloaded function again, this time 1457 // allowing complaints if something goes wrong. 1458 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1459 DestType, 1460 true, 1461 FoundOverload); 1462 if (!Fn) { 1463 msg = 0; 1464 return TC_Failed; 1465 } 1466 1467 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1468 if (!SrcExpr.isUsable()) { 1469 msg = 0; 1470 return TC_Failed; 1471 } 1472 } 1473 1474 Self.BuildBasePathArray(Paths, BasePath); 1475 Kind = CK_DerivedToBaseMemberPointer; 1476 return TC_Success; 1477} 1478 1479/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1480/// is valid: 1481/// 1482/// An expression e can be explicitly converted to a type T using a 1483/// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1484TryCastResult 1485TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1486 Sema::CheckedConversionKind CCK, 1487 const SourceRange &OpRange, unsigned &msg, 1488 CastKind &Kind, bool ListInitialization) { 1489 if (DestType->isRecordType()) { 1490 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1491 diag::err_bad_dynamic_cast_incomplete) || 1492 Self.RequireNonAbstractType(OpRange.getBegin(), DestType, 1493 diag::err_allocation_of_abstract_type)) { 1494 msg = 0; 1495 return TC_Failed; 1496 } 1497 } else if (DestType->isMemberPointerType()) { 1498 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1499 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0); 1500 } 1501 } 1502 1503 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1504 InitializationKind InitKind 1505 = (CCK == Sema::CCK_CStyleCast) 1506 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, 1507 ListInitialization) 1508 : (CCK == Sema::CCK_FunctionalCast) 1509 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) 1510 : InitializationKind::CreateCast(OpRange); 1511 Expr *SrcExprRaw = SrcExpr.get(); 1512 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); 1513 1514 // At this point of CheckStaticCast, if the destination is a reference, 1515 // or the expression is an overload expression this has to work. 1516 // There is no other way that works. 1517 // On the other hand, if we're checking a C-style cast, we've still got 1518 // the reinterpret_cast way. 1519 bool CStyle 1520 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1521 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1522 return TC_NotApplicable; 1523 1524 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); 1525 if (Result.isInvalid()) { 1526 msg = 0; 1527 return TC_Failed; 1528 } 1529 1530 if (InitSeq.isConstructorInitialization()) 1531 Kind = CK_ConstructorConversion; 1532 else 1533 Kind = CK_NoOp; 1534 1535 SrcExpr = Result; 1536 return TC_Success; 1537} 1538 1539/// TryConstCast - See if a const_cast from source to destination is allowed, 1540/// and perform it if it is. 1541static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 1542 QualType DestType, bool CStyle, 1543 unsigned &msg) { 1544 DestType = Self.Context.getCanonicalType(DestType); 1545 QualType SrcType = SrcExpr.get()->getType(); 1546 bool NeedToMaterializeTemporary = false; 1547 1548 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1549 // C++11 5.2.11p4: 1550 // if a pointer to T1 can be explicitly converted to the type "pointer to 1551 // T2" using a const_cast, then the following conversions can also be 1552 // made: 1553 // -- an lvalue of type T1 can be explicitly converted to an lvalue of 1554 // type T2 using the cast const_cast<T2&>; 1555 // -- a glvalue of type T1 can be explicitly converted to an xvalue of 1556 // type T2 using the cast const_cast<T2&&>; and 1557 // -- if T1 is a class type, a prvalue of type T1 can be explicitly 1558 // converted to an xvalue of type T2 using the cast const_cast<T2&&>. 1559 1560 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { 1561 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1562 // is C-style, static_cast might find a way, so we simply suggest a 1563 // message and tell the parent to keep searching. 1564 msg = diag::err_bad_cxx_cast_rvalue; 1565 return TC_NotApplicable; 1566 } 1567 1568 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) { 1569 if (!SrcType->isRecordType()) { 1570 // Cannot const_cast non-class prvalue to rvalue reference type. But if 1571 // this is C-style, static_cast can do this. 1572 msg = diag::err_bad_cxx_cast_rvalue; 1573 return TC_NotApplicable; 1574 } 1575 1576 // Materialize the class prvalue so that the const_cast can bind a 1577 // reference to it. 1578 NeedToMaterializeTemporary = true; 1579 } 1580 1581 // It's not completely clear under the standard whether we can 1582 // const_cast bit-field gl-values. Doing so would not be 1583 // intrinsically complicated, but for now, we say no for 1584 // consistency with other compilers and await the word of the 1585 // committee. 1586 if (SrcExpr.get()->refersToBitField()) { 1587 msg = diag::err_bad_cxx_cast_bitfield; 1588 return TC_NotApplicable; 1589 } 1590 1591 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1592 SrcType = Self.Context.getPointerType(SrcType); 1593 } 1594 1595 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1596 // the rules for const_cast are the same as those used for pointers. 1597 1598 if (!DestType->isPointerType() && 1599 !DestType->isMemberPointerType() && 1600 !DestType->isObjCObjectPointerType()) { 1601 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1602 // was a reference type, we converted it to a pointer above. 1603 // The status of rvalue references isn't entirely clear, but it looks like 1604 // conversion to them is simply invalid. 1605 // C++ 5.2.11p3: For two pointer types [...] 1606 if (!CStyle) 1607 msg = diag::err_bad_const_cast_dest; 1608 return TC_NotApplicable; 1609 } 1610 if (DestType->isFunctionPointerType() || 1611 DestType->isMemberFunctionPointerType()) { 1612 // Cannot cast direct function pointers. 1613 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1614 // T is the ultimate pointee of source and target type. 1615 if (!CStyle) 1616 msg = diag::err_bad_const_cast_dest; 1617 return TC_NotApplicable; 1618 } 1619 SrcType = Self.Context.getCanonicalType(SrcType); 1620 1621 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 1622 // completely equal. 1623 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 1624 // in multi-level pointers may change, but the level count must be the same, 1625 // as must be the final pointee type. 1626 while (SrcType != DestType && 1627 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 1628 Qualifiers SrcQuals, DestQuals; 1629 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 1630 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 1631 1632 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 1633 // the other qualifiers (e.g., address spaces) are identical. 1634 SrcQuals.removeCVRQualifiers(); 1635 DestQuals.removeCVRQualifiers(); 1636 if (SrcQuals != DestQuals) 1637 return TC_NotApplicable; 1638 } 1639 1640 // Since we're dealing in canonical types, the remainder must be the same. 1641 if (SrcType != DestType) 1642 return TC_NotApplicable; 1643 1644 if (NeedToMaterializeTemporary) 1645 // This is a const_cast from a class prvalue to an rvalue reference type. 1646 // Materialize a temporary to store the result of the conversion. 1647 SrcExpr = new (Self.Context) MaterializeTemporaryExpr( 1648 SrcType, SrcExpr.get(), /*IsLValueReference*/ false); 1649 1650 return TC_Success; 1651} 1652 1653// Checks for undefined behavior in reinterpret_cast. 1654// The cases that is checked for is: 1655// *reinterpret_cast<T*>(&a) 1656// reinterpret_cast<T&>(a) 1657// where accessing 'a' as type 'T' will result in undefined behavior. 1658void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 1659 bool IsDereference, 1660 SourceRange Range) { 1661 unsigned DiagID = IsDereference ? 1662 diag::warn_pointer_indirection_from_incompatible_type : 1663 diag::warn_undefined_reinterpret_cast; 1664 1665 if (Diags.isIgnored(DiagID, Range.getBegin())) 1666 return; 1667 1668 QualType SrcTy, DestTy; 1669 if (IsDereference) { 1670 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 1671 return; 1672 } 1673 SrcTy = SrcType->getPointeeType(); 1674 DestTy = DestType->getPointeeType(); 1675 } else { 1676 if (!DestType->getAs<ReferenceType>()) { 1677 return; 1678 } 1679 SrcTy = SrcType; 1680 DestTy = DestType->getPointeeType(); 1681 } 1682 1683 // Cast is compatible if the types are the same. 1684 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 1685 return; 1686 } 1687 // or one of the types is a char or void type 1688 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 1689 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 1690 return; 1691 } 1692 // or one of the types is a tag type. 1693 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 1694 return; 1695 } 1696 1697 // FIXME: Scoped enums? 1698 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 1699 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 1700 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 1701 return; 1702 } 1703 } 1704 1705 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 1706} 1707 1708static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, 1709 QualType DestType) { 1710 QualType SrcType = SrcExpr.get()->getType(); 1711 if (Self.Context.hasSameType(SrcType, DestType)) 1712 return; 1713 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) 1714 if (SrcPtrTy->isObjCSelType()) { 1715 QualType DT = DestType; 1716 if (isa<PointerType>(DestType)) 1717 DT = DestType->getPointeeType(); 1718 if (!DT.getUnqualifiedType()->isVoidType()) 1719 Self.Diag(SrcExpr.get()->getExprLoc(), 1720 diag::warn_cast_pointer_from_sel) 1721 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 1722 } 1723} 1724 1725static void checkIntToPointerCast(bool CStyle, SourceLocation Loc, 1726 const Expr *SrcExpr, QualType DestType, 1727 Sema &Self) { 1728 QualType SrcType = SrcExpr->getType(); 1729 1730 // Not warning on reinterpret_cast, boolean, constant expressions, etc 1731 // are not explicit design choices, but consistent with GCC's behavior. 1732 // Feel free to modify them if you've reason/evidence for an alternative. 1733 if (CStyle && SrcType->isIntegralType(Self.Context) 1734 && !SrcType->isBooleanType() 1735 && !SrcType->isEnumeralType() 1736 && !SrcExpr->isIntegerConstantExpr(Self.Context) 1737 && Self.Context.getTypeSize(DestType) > 1738 Self.Context.getTypeSize(SrcType)) { 1739 // Separate between casts to void* and non-void* pointers. 1740 // Some APIs use (abuse) void* for something like a user context, 1741 // and often that value is an integer even if it isn't a pointer itself. 1742 // Having a separate warning flag allows users to control the warning 1743 // for their workflow. 1744 unsigned Diag = DestType->isVoidPointerType() ? 1745 diag::warn_int_to_void_pointer_cast 1746 : diag::warn_int_to_pointer_cast; 1747 Self.Diag(Loc, Diag) << SrcType << DestType; 1748 } 1749} 1750 1751static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 1752 QualType DestType, bool CStyle, 1753 const SourceRange &OpRange, 1754 unsigned &msg, 1755 CastKind &Kind) { 1756 bool IsLValueCast = false; 1757 1758 DestType = Self.Context.getCanonicalType(DestType); 1759 QualType SrcType = SrcExpr.get()->getType(); 1760 1761 // Is the source an overloaded name? (i.e. &foo) 1762 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ... 1763 if (SrcType == Self.Context.OverloadTy) { 1764 // ... unless foo<int> resolves to an lvalue unambiguously. 1765 // TODO: what if this fails because of DiagnoseUseOfDecl or something 1766 // like it? 1767 ExprResult SingleFunctionExpr = SrcExpr; 1768 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1769 SingleFunctionExpr, 1770 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 1771 ) && SingleFunctionExpr.isUsable()) { 1772 SrcExpr = SingleFunctionExpr; 1773 SrcType = SrcExpr.get()->getType(); 1774 } else { 1775 return TC_NotApplicable; 1776 } 1777 } 1778 1779 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 1780 if (!SrcExpr.get()->isGLValue()) { 1781 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the 1782 // similar comment in const_cast. 1783 msg = diag::err_bad_cxx_cast_rvalue; 1784 return TC_NotApplicable; 1785 } 1786 1787 if (!CStyle) { 1788 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 1789 /*isDereference=*/false, OpRange); 1790 } 1791 1792 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 1793 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 1794 // built-in & and * operators. 1795 1796 const char *inappropriate = nullptr; 1797 switch (SrcExpr.get()->getObjectKind()) { 1798 case OK_Ordinary: 1799 break; 1800 case OK_BitField: inappropriate = "bit-field"; break; 1801 case OK_VectorComponent: inappropriate = "vector element"; break; 1802 case OK_ObjCProperty: inappropriate = "property expression"; break; 1803 case OK_ObjCSubscript: inappropriate = "container subscripting expression"; 1804 break; 1805 } 1806 if (inappropriate) { 1807 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 1808 << inappropriate << DestType 1809 << OpRange << SrcExpr.get()->getSourceRange(); 1810 msg = 0; SrcExpr = ExprError(); 1811 return TC_NotApplicable; 1812 } 1813 1814 // This code does this transformation for the checked types. 1815 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1816 SrcType = Self.Context.getPointerType(SrcType); 1817 1818 IsLValueCast = true; 1819 } 1820 1821 // Canonicalize source for comparison. 1822 SrcType = Self.Context.getCanonicalType(SrcType); 1823 1824 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 1825 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1826 if (DestMemPtr && SrcMemPtr) { 1827 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 1828 // can be explicitly converted to an rvalue of type "pointer to member 1829 // of Y of type T2" if T1 and T2 are both function types or both object 1830 // types. 1831 if (DestMemPtr->isMemberFunctionPointer() != 1832 SrcMemPtr->isMemberFunctionPointer()) 1833 return TC_NotApplicable; 1834 1835 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 1836 // constness. 1837 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 1838 // we accept it. 1839 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1840 /*CheckObjCLifetime=*/CStyle)) { 1841 msg = diag::err_bad_cxx_cast_qualifiers_away; 1842 return TC_Failed; 1843 } 1844 1845 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1846 // We need to determine the inheritance model that the class will use if 1847 // haven't yet. 1848 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0); 1849 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0); 1850 } 1851 1852 // Don't allow casting between member pointers of different sizes. 1853 if (Self.Context.getTypeSize(DestMemPtr) != 1854 Self.Context.getTypeSize(SrcMemPtr)) { 1855 msg = diag::err_bad_cxx_cast_member_pointer_size; 1856 return TC_Failed; 1857 } 1858 1859 // A valid member pointer cast. 1860 assert(!IsLValueCast); 1861 Kind = CK_ReinterpretMemberPointer; 1862 return TC_Success; 1863 } 1864 1865 // See below for the enumeral issue. 1866 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 1867 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 1868 // type large enough to hold it. A value of std::nullptr_t can be 1869 // converted to an integral type; the conversion has the same meaning 1870 // and validity as a conversion of (void*)0 to the integral type. 1871 if (Self.Context.getTypeSize(SrcType) > 1872 Self.Context.getTypeSize(DestType)) { 1873 msg = diag::err_bad_reinterpret_cast_small_int; 1874 return TC_Failed; 1875 } 1876 Kind = CK_PointerToIntegral; 1877 return TC_Success; 1878 } 1879 1880 bool destIsVector = DestType->isVectorType(); 1881 bool srcIsVector = SrcType->isVectorType(); 1882 if (srcIsVector || destIsVector) { 1883 // FIXME: Should this also apply to floating point types? 1884 bool srcIsScalar = SrcType->isIntegralType(Self.Context); 1885 bool destIsScalar = DestType->isIntegralType(Self.Context); 1886 1887 // Check if this is a cast between a vector and something else. 1888 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) && 1889 !(srcIsVector && destIsVector)) 1890 return TC_NotApplicable; 1891 1892 // If both types have the same size, we can successfully cast. 1893 if (Self.Context.getTypeSize(SrcType) 1894 == Self.Context.getTypeSize(DestType)) { 1895 Kind = CK_BitCast; 1896 return TC_Success; 1897 } 1898 1899 if (destIsScalar) 1900 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 1901 else if (srcIsScalar) 1902 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 1903 else 1904 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 1905 1906 return TC_Failed; 1907 } 1908 1909 if (SrcType == DestType) { 1910 // C++ 5.2.10p2 has a note that mentions that, subject to all other 1911 // restrictions, a cast to the same type is allowed so long as it does not 1912 // cast away constness. In C++98, the intent was not entirely clear here, 1913 // since all other paragraphs explicitly forbid casts to the same type. 1914 // C++11 clarifies this case with p2. 1915 // 1916 // The only allowed types are: integral, enumeration, pointer, or 1917 // pointer-to-member types. We also won't restrict Obj-C pointers either. 1918 Kind = CK_NoOp; 1919 TryCastResult Result = TC_NotApplicable; 1920 if (SrcType->isIntegralOrEnumerationType() || 1921 SrcType->isAnyPointerType() || 1922 SrcType->isMemberPointerType() || 1923 SrcType->isBlockPointerType()) { 1924 Result = TC_Success; 1925 } 1926 return Result; 1927 } 1928 1929 bool destIsPtr = DestType->isAnyPointerType() || 1930 DestType->isBlockPointerType(); 1931 bool srcIsPtr = SrcType->isAnyPointerType() || 1932 SrcType->isBlockPointerType(); 1933 if (!destIsPtr && !srcIsPtr) { 1934 // Except for std::nullptr_t->integer and lvalue->reference, which are 1935 // handled above, at least one of the two arguments must be a pointer. 1936 return TC_NotApplicable; 1937 } 1938 1939 if (DestType->isIntegralType(Self.Context)) { 1940 assert(srcIsPtr && "One type must be a pointer"); 1941 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 1942 // type large enough to hold it; except in Microsoft mode, where the 1943 // integral type size doesn't matter (except we don't allow bool). 1944 bool MicrosoftException = Self.getLangOpts().MicrosoftExt && 1945 !DestType->isBooleanType(); 1946 if ((Self.Context.getTypeSize(SrcType) > 1947 Self.Context.getTypeSize(DestType)) && 1948 !MicrosoftException) { 1949 msg = diag::err_bad_reinterpret_cast_small_int; 1950 return TC_Failed; 1951 } 1952 Kind = CK_PointerToIntegral; 1953 return TC_Success; 1954 } 1955 1956 if (SrcType->isIntegralOrEnumerationType()) { 1957 assert(destIsPtr && "One type must be a pointer"); 1958 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType, 1959 Self); 1960 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 1961 // converted to a pointer. 1962 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 1963 // necessarily converted to a null pointer value.] 1964 Kind = CK_IntegralToPointer; 1965 return TC_Success; 1966 } 1967 1968 if (!destIsPtr || !srcIsPtr) { 1969 // With the valid non-pointer conversions out of the way, we can be even 1970 // more stringent. 1971 return TC_NotApplicable; 1972 } 1973 1974 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 1975 // The C-style cast operator can. 1976 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1977 /*CheckObjCLifetime=*/CStyle)) { 1978 msg = diag::err_bad_cxx_cast_qualifiers_away; 1979 return TC_Failed; 1980 } 1981 1982 // Cannot convert between block pointers and Objective-C object pointers. 1983 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 1984 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 1985 return TC_NotApplicable; 1986 1987 if (IsLValueCast) { 1988 Kind = CK_LValueBitCast; 1989 } else if (DestType->isObjCObjectPointerType()) { 1990 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 1991 } else if (DestType->isBlockPointerType()) { 1992 if (!SrcType->isBlockPointerType()) { 1993 Kind = CK_AnyPointerToBlockPointerCast; 1994 } else { 1995 Kind = CK_BitCast; 1996 } 1997 } else { 1998 Kind = CK_BitCast; 1999 } 2000 2001 // Any pointer can be cast to an Objective-C pointer type with a C-style 2002 // cast. 2003 if (CStyle && DestType->isObjCObjectPointerType()) { 2004 return TC_Success; 2005 } 2006 if (CStyle) 2007 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2008 2009 // Not casting away constness, so the only remaining check is for compatible 2010 // pointer categories. 2011 2012 if (SrcType->isFunctionPointerType()) { 2013 if (DestType->isFunctionPointerType()) { 2014 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 2015 // a pointer to a function of a different type. 2016 return TC_Success; 2017 } 2018 2019 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 2020 // an object type or vice versa is conditionally-supported. 2021 // Compilers support it in C++03 too, though, because it's necessary for 2022 // casting the return value of dlsym() and GetProcAddress(). 2023 // FIXME: Conditionally-supported behavior should be configurable in the 2024 // TargetInfo or similar. 2025 Self.Diag(OpRange.getBegin(), 2026 Self.getLangOpts().CPlusPlus11 ? 2027 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2028 << OpRange; 2029 return TC_Success; 2030 } 2031 2032 if (DestType->isFunctionPointerType()) { 2033 // See above. 2034 Self.Diag(OpRange.getBegin(), 2035 Self.getLangOpts().CPlusPlus11 ? 2036 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2037 << OpRange; 2038 return TC_Success; 2039 } 2040 2041 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 2042 // a pointer to an object of different type. 2043 // Void pointers are not specified, but supported by every compiler out there. 2044 // So we finish by allowing everything that remains - it's got to be two 2045 // object pointers. 2046 return TC_Success; 2047} 2048 2049void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, 2050 bool ListInitialization) { 2051 // Handle placeholders. 2052 if (isPlaceholder()) { 2053 // C-style casts can resolve __unknown_any types. 2054 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2055 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2056 SrcExpr.get(), Kind, 2057 ValueKind, BasePath); 2058 return; 2059 } 2060 2061 checkNonOverloadPlaceholders(); 2062 if (SrcExpr.isInvalid()) 2063 return; 2064 } 2065 2066 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 2067 // This test is outside everything else because it's the only case where 2068 // a non-lvalue-reference target type does not lead to decay. 2069 if (DestType->isVoidType()) { 2070 Kind = CK_ToVoid; 2071 2072 if (claimPlaceholder(BuiltinType::Overload)) { 2073 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2074 SrcExpr, /* Decay Function to ptr */ false, 2075 /* Complain */ true, DestRange, DestType, 2076 diag::err_bad_cstyle_cast_overload); 2077 if (SrcExpr.isInvalid()) 2078 return; 2079 } 2080 2081 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2082 return; 2083 } 2084 2085 // If the type is dependent, we won't do any other semantic analysis now. 2086 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || 2087 SrcExpr.get()->isValueDependent()) { 2088 assert(Kind == CK_Dependent); 2089 return; 2090 } 2091 2092 if (ValueKind == VK_RValue && !DestType->isRecordType() && 2093 !isPlaceholder(BuiltinType::Overload)) { 2094 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2095 if (SrcExpr.isInvalid()) 2096 return; 2097 } 2098 2099 // AltiVec vector initialization with a single literal. 2100 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 2101 if (vecTy->getVectorKind() == VectorType::AltiVecVector 2102 && (SrcExpr.get()->getType()->isIntegerType() 2103 || SrcExpr.get()->getType()->isFloatingType())) { 2104 Kind = CK_VectorSplat; 2105 return; 2106 } 2107 2108 // C++ [expr.cast]p5: The conversions performed by 2109 // - a const_cast, 2110 // - a static_cast, 2111 // - a static_cast followed by a const_cast, 2112 // - a reinterpret_cast, or 2113 // - a reinterpret_cast followed by a const_cast, 2114 // can be performed using the cast notation of explicit type conversion. 2115 // [...] If a conversion can be interpreted in more than one of the ways 2116 // listed above, the interpretation that appears first in the list is used, 2117 // even if a cast resulting from that interpretation is ill-formed. 2118 // In plain language, this means trying a const_cast ... 2119 unsigned msg = diag::err_bad_cxx_cast_generic; 2120 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, 2121 /*CStyle*/true, msg); 2122 if (SrcExpr.isInvalid()) 2123 return; 2124 if (tcr == TC_Success) 2125 Kind = CK_NoOp; 2126 2127 Sema::CheckedConversionKind CCK 2128 = FunctionalStyle? Sema::CCK_FunctionalCast 2129 : Sema::CCK_CStyleCast; 2130 if (tcr == TC_NotApplicable) { 2131 // ... or if that is not possible, a static_cast, ignoring const, ... 2132 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 2133 msg, Kind, BasePath, ListInitialization); 2134 if (SrcExpr.isInvalid()) 2135 return; 2136 2137 if (tcr == TC_NotApplicable) { 2138 // ... and finally a reinterpret_cast, ignoring const. 2139 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 2140 OpRange, msg, Kind); 2141 if (SrcExpr.isInvalid()) 2142 return; 2143 } 2144 } 2145 2146 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success) 2147 checkObjCARCConversion(CCK); 2148 2149 if (tcr != TC_Success && msg != 0) { 2150 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2151 DeclAccessPair Found; 2152 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 2153 DestType, 2154 /*Complain*/ true, 2155 Found); 2156 if (Fn) { 2157 // If DestType is a function type (not to be confused with the function 2158 // pointer type), it will be possible to resolve the function address, 2159 // but the type cast should be considered as failure. 2160 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; 2161 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) 2162 << OE->getName() << DestType << OpRange 2163 << OE->getQualifierLoc().getSourceRange(); 2164 Self.NoteAllOverloadCandidates(SrcExpr.get()); 2165 } 2166 } else { 2167 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 2168 OpRange, SrcExpr.get(), DestType, ListInitialization); 2169 } 2170 } else if (Kind == CK_BitCast) { 2171 checkCastAlign(); 2172 } 2173 2174 // Clear out SrcExpr if there was a fatal error. 2175 if (tcr != TC_Success) 2176 SrcExpr = ExprError(); 2177} 2178 2179/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a 2180/// non-matching type. Such as enum function call to int, int call to 2181/// pointer; etc. Cast to 'void' is an exception. 2182static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, 2183 QualType DestType) { 2184 if (Self.Diags.isIgnored(diag::warn_bad_function_cast, 2185 SrcExpr.get()->getExprLoc())) 2186 return; 2187 2188 if (!isa<CallExpr>(SrcExpr.get())) 2189 return; 2190 2191 QualType SrcType = SrcExpr.get()->getType(); 2192 if (DestType.getUnqualifiedType()->isVoidType()) 2193 return; 2194 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) 2195 && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) 2196 return; 2197 if (SrcType->isIntegerType() && DestType->isIntegerType() && 2198 (SrcType->isBooleanType() == DestType->isBooleanType()) && 2199 (SrcType->isEnumeralType() == DestType->isEnumeralType())) 2200 return; 2201 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) 2202 return; 2203 if (SrcType->isEnumeralType() && DestType->isEnumeralType()) 2204 return; 2205 if (SrcType->isComplexType() && DestType->isComplexType()) 2206 return; 2207 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) 2208 return; 2209 2210 Self.Diag(SrcExpr.get()->getExprLoc(), 2211 diag::warn_bad_function_cast) 2212 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2213} 2214 2215/// Check the semantics of a C-style cast operation, in C. 2216void CastOperation::CheckCStyleCast() { 2217 assert(!Self.getLangOpts().CPlusPlus); 2218 2219 // C-style casts can resolve __unknown_any types. 2220 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2221 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2222 SrcExpr.get(), Kind, 2223 ValueKind, BasePath); 2224 return; 2225 } 2226 2227 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2228 // type needs to be scalar. 2229 if (DestType->isVoidType()) { 2230 // We don't necessarily do lvalue-to-rvalue conversions on this. 2231 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2232 if (SrcExpr.isInvalid()) 2233 return; 2234 2235 // Cast to void allows any expr type. 2236 Kind = CK_ToVoid; 2237 return; 2238 } 2239 2240 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2241 if (SrcExpr.isInvalid()) 2242 return; 2243 QualType SrcType = SrcExpr.get()->getType(); 2244 2245 assert(!SrcType->isPlaceholderType()); 2246 2247 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to 2248 // address space B is illegal. 2249 if (Self.getLangOpts().OpenCL && DestType->isPointerType() && 2250 SrcType->isPointerType()) { 2251 const PointerType *DestPtr = DestType->getAs<PointerType>(); 2252 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) { 2253 Self.Diag(OpRange.getBegin(), 2254 diag::err_typecheck_incompatible_address_space) 2255 << SrcType << DestType << Sema::AA_Casting 2256 << SrcExpr.get()->getSourceRange(); 2257 SrcExpr = ExprError(); 2258 return; 2259 } 2260 } 2261 2262 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 2263 diag::err_typecheck_cast_to_incomplete)) { 2264 SrcExpr = ExprError(); 2265 return; 2266 } 2267 2268 if (!DestType->isScalarType() && !DestType->isVectorType()) { 2269 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 2270 2271 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 2272 // GCC struct/union extension: allow cast to self. 2273 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 2274 << DestType << SrcExpr.get()->getSourceRange(); 2275 Kind = CK_NoOp; 2276 return; 2277 } 2278 2279 // GCC's cast to union extension. 2280 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 2281 RecordDecl *RD = DestRecordTy->getDecl(); 2282 RecordDecl::field_iterator Field, FieldEnd; 2283 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2284 Field != FieldEnd; ++Field) { 2285 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 2286 !Field->isUnnamedBitfield()) { 2287 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 2288 << SrcExpr.get()->getSourceRange(); 2289 break; 2290 } 2291 } 2292 if (Field == FieldEnd) { 2293 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2294 << SrcType << SrcExpr.get()->getSourceRange(); 2295 SrcExpr = ExprError(); 2296 return; 2297 } 2298 Kind = CK_ToUnion; 2299 return; 2300 } 2301 2302 // Reject any other conversions to non-scalar types. 2303 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 2304 << DestType << SrcExpr.get()->getSourceRange(); 2305 SrcExpr = ExprError(); 2306 return; 2307 } 2308 2309 // The type we're casting to is known to be a scalar or vector. 2310 2311 // Require the operand to be a scalar or vector. 2312 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 2313 Self.Diag(SrcExpr.get()->getExprLoc(), 2314 diag::err_typecheck_expect_scalar_operand) 2315 << SrcType << SrcExpr.get()->getSourceRange(); 2316 SrcExpr = ExprError(); 2317 return; 2318 } 2319 2320 if (DestType->isExtVectorType()) { 2321 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); 2322 return; 2323 } 2324 2325 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 2326 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 2327 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 2328 Kind = CK_VectorSplat; 2329 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 2330 SrcExpr = ExprError(); 2331 } 2332 return; 2333 } 2334 2335 if (SrcType->isVectorType()) { 2336 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 2337 SrcExpr = ExprError(); 2338 return; 2339 } 2340 2341 // The source and target types are both scalars, i.e. 2342 // - arithmetic types (fundamental, enum, and complex) 2343 // - all kinds of pointers 2344 // Note that member pointers were filtered out with C++, above. 2345 2346 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 2347 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 2348 SrcExpr = ExprError(); 2349 return; 2350 } 2351 2352 // If either type is a pointer, the other type has to be either an 2353 // integer or a pointer. 2354 if (!DestType->isArithmeticType()) { 2355 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 2356 Self.Diag(SrcExpr.get()->getExprLoc(), 2357 diag::err_cast_pointer_from_non_pointer_int) 2358 << SrcType << SrcExpr.get()->getSourceRange(); 2359 SrcExpr = ExprError(); 2360 return; 2361 } 2362 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(), 2363 DestType, Self); 2364 } else if (!SrcType->isArithmeticType()) { 2365 if (!DestType->isIntegralType(Self.Context) && 2366 DestType->isArithmeticType()) { 2367 Self.Diag(SrcExpr.get()->getLocStart(), 2368 diag::err_cast_pointer_to_non_pointer_int) 2369 << DestType << SrcExpr.get()->getSourceRange(); 2370 SrcExpr = ExprError(); 2371 return; 2372 } 2373 } 2374 2375 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) { 2376 if (DestType->isHalfType()) { 2377 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half) 2378 << DestType << SrcExpr.get()->getSourceRange(); 2379 SrcExpr = ExprError(); 2380 return; 2381 } 2382 } 2383 2384 // ARC imposes extra restrictions on casts. 2385 if (Self.getLangOpts().ObjCAutoRefCount) { 2386 checkObjCARCConversion(Sema::CCK_CStyleCast); 2387 if (SrcExpr.isInvalid()) 2388 return; 2389 2390 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) { 2391 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 2392 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 2393 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 2394 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 2395 ExprPtr->getPointeeType()->isObjCLifetimeType() && 2396 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 2397 Self.Diag(SrcExpr.get()->getLocStart(), 2398 diag::err_typecheck_incompatible_ownership) 2399 << SrcType << DestType << Sema::AA_Casting 2400 << SrcExpr.get()->getSourceRange(); 2401 return; 2402 } 2403 } 2404 } 2405 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 2406 Self.Diag(SrcExpr.get()->getLocStart(), 2407 diag::err_arc_convesion_of_weak_unavailable) 2408 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2409 SrcExpr = ExprError(); 2410 return; 2411 } 2412 } 2413 2414 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2415 DiagnoseBadFunctionCast(Self, SrcExpr, DestType); 2416 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 2417 if (SrcExpr.isInvalid()) 2418 return; 2419 2420 if (Kind == CK_BitCast) 2421 checkCastAlign(); 2422 2423 // -Wcast-qual 2424 QualType TheOffendingSrcType, TheOffendingDestType; 2425 Qualifiers CastAwayQualifiers; 2426 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() && 2427 CastsAwayConstness(Self, SrcType, DestType, true, false, 2428 &TheOffendingSrcType, &TheOffendingDestType, 2429 &CastAwayQualifiers)) { 2430 int qualifiers = -1; 2431 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { 2432 qualifiers = 0; 2433 } else if (CastAwayQualifiers.hasConst()) { 2434 qualifiers = 1; 2435 } else if (CastAwayQualifiers.hasVolatile()) { 2436 qualifiers = 2; 2437 } 2438 // This is a variant of int **x; const int **y = (const int **)x; 2439 if (qualifiers == -1) 2440 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) << 2441 SrcType << DestType; 2442 else 2443 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) << 2444 TheOffendingSrcType << TheOffendingDestType << qualifiers; 2445 } 2446} 2447 2448ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 2449 TypeSourceInfo *CastTypeInfo, 2450 SourceLocation RPLoc, 2451 Expr *CastExpr) { 2452 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2453 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2454 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 2455 2456 if (getLangOpts().CPlusPlus) { 2457 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false, 2458 isa<InitListExpr>(CastExpr)); 2459 } else { 2460 Op.CheckCStyleCast(); 2461 } 2462 2463 if (Op.SrcExpr.isInvalid()) 2464 return ExprError(); 2465 2466 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 2467 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 2468 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 2469} 2470 2471ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 2472 SourceLocation LPLoc, 2473 Expr *CastExpr, 2474 SourceLocation RPLoc) { 2475 assert(LPLoc.isValid() && "List-initialization shouldn't get here."); 2476 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2477 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2478 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 2479 2480 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false); 2481 if (Op.SrcExpr.isInvalid()) 2482 return ExprError(); 2483 2484 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get())) 2485 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); 2486 2487 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 2488 Op.ValueKind, CastTypeInfo, Op.Kind, 2489 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc)); 2490} 2491