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> 28 using namespace clang; 29 30 31 32 enum 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 39 enum 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 48 namespace { 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 156 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 157 QualType DestType, bool CStyle, 158 CastKind &Kind, 159 CXXCastPath &BasePath, 160 unsigned &msg); 161 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 162 QualType DestType, bool CStyle, 163 SourceRange OpRange, 164 unsigned &msg, 165 CastKind &Kind, 166 CXXCastPath &BasePath); 167 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 168 QualType DestType, bool CStyle, 169 SourceRange OpRange, 170 unsigned &msg, 171 CastKind &Kind, 172 CXXCastPath &BasePath); 173 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 174 CanQualType DestType, bool CStyle, 175 SourceRange OpRange, 176 QualType OrigSrcType, 177 QualType OrigDestType, unsigned &msg, 178 CastKind &Kind, 179 CXXCastPath &BasePath); 180 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 181 QualType SrcType, 182 QualType DestType,bool CStyle, 183 SourceRange OpRange, 184 unsigned &msg, 185 CastKind &Kind, 186 CXXCastPath &BasePath); 187 188 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 189 QualType DestType, 190 Sema::CheckedConversionKind CCK, 191 SourceRange OpRange, 192 unsigned &msg, CastKind &Kind, 193 bool ListInitialization); 194 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 195 QualType DestType, 196 Sema::CheckedConversionKind CCK, 197 SourceRange OpRange, 198 unsigned &msg, CastKind &Kind, 199 CXXCastPath &BasePath, 200 bool ListInitialization); 201 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 202 QualType DestType, bool CStyle, 203 unsigned &msg); 204 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 205 QualType DestType, bool CStyle, 206 SourceRange OpRange, 207 unsigned &msg, 208 CastKind &Kind); 209 210 211 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 212 ExprResult 213 Sema::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 235 ExprResult 236 Sema::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. 306 static 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. 382 static 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. 426 static 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. 485 static bool 486 CastsAwayConstness(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 ObjC mode, there's nothing to check. 493 if (!CheckCVR && CheckObjCLifetime && 494 !Self.Context.getLangOpts().ObjC1) 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. 573 void 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 && 687 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { 688 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 689 OpRange.getBegin(), OpRange, 690 &BasePath)) { 691 SrcExpr = ExprError(); 692 return; 693 } 694 695 Kind = CK_DerivedToBase; 696 return; 697 } 698 699 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 700 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 701 assert(SrcDecl && "Definition missing"); 702 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 703 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 704 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 705 SrcExpr = ExprError(); 706 } 707 708 // dynamic_cast is not available with -fno-rtti. 709 // As an exception, dynamic_cast to void* is available because it doesn't 710 // use RTTI. 711 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { 712 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); 713 SrcExpr = ExprError(); 714 return; 715 } 716 717 // Done. Everything else is run-time checks. 718 Kind = CK_Dynamic; 719 } 720 721 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 722 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code 723 /// like this: 724 /// const char *str = "literal"; 725 /// legacy_function(const_cast\<char*\>(str)); 726 void CastOperation::CheckConstCast() { 727 if (ValueKind == VK_RValue) 728 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 729 else if (isPlaceholder()) 730 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 731 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 732 return; 733 734 unsigned msg = diag::err_bad_cxx_cast_generic; 735 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success 736 && msg != 0) { 737 Self.Diag(OpRange.getBegin(), msg) << CT_Const 738 << SrcExpr.get()->getType() << DestType << OpRange; 739 SrcExpr = ExprError(); 740 } 741 } 742 743 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast 744 /// or downcast between respective pointers or references. 745 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, 746 QualType DestType, 747 SourceRange OpRange) { 748 QualType SrcType = SrcExpr->getType(); 749 // When casting from pointer or reference, get pointee type; use original 750 // type otherwise. 751 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); 752 const CXXRecordDecl *SrcRD = 753 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); 754 755 // Examining subobjects for records is only possible if the complete and 756 // valid definition is available. Also, template instantiation is not 757 // allowed here. 758 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) 759 return; 760 761 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); 762 763 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) 764 return; 765 766 enum { 767 ReinterpretUpcast, 768 ReinterpretDowncast 769 } ReinterpretKind; 770 771 CXXBasePaths BasePaths; 772 773 if (SrcRD->isDerivedFrom(DestRD, BasePaths)) 774 ReinterpretKind = ReinterpretUpcast; 775 else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) 776 ReinterpretKind = ReinterpretDowncast; 777 else 778 return; 779 780 bool VirtualBase = true; 781 bool NonZeroOffset = false; 782 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), 783 E = BasePaths.end(); 784 I != E; ++I) { 785 const CXXBasePath &Path = *I; 786 CharUnits Offset = CharUnits::Zero(); 787 bool IsVirtual = false; 788 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); 789 IElem != EElem; ++IElem) { 790 IsVirtual = IElem->Base->isVirtual(); 791 if (IsVirtual) 792 break; 793 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); 794 assert(BaseRD && "Base type should be a valid unqualified class type"); 795 // Don't check if any base has invalid declaration or has no definition 796 // since it has no layout info. 797 const CXXRecordDecl *Class = IElem->Class, 798 *ClassDefinition = Class->getDefinition(); 799 if (Class->isInvalidDecl() || !ClassDefinition || 800 !ClassDefinition->isCompleteDefinition()) 801 return; 802 803 const ASTRecordLayout &DerivedLayout = 804 Self.Context.getASTRecordLayout(Class); 805 Offset += DerivedLayout.getBaseClassOffset(BaseRD); 806 } 807 if (!IsVirtual) { 808 // Don't warn if any path is a non-virtually derived base at offset zero. 809 if (Offset.isZero()) 810 return; 811 // Offset makes sense only for non-virtual bases. 812 else 813 NonZeroOffset = true; 814 } 815 VirtualBase = VirtualBase && IsVirtual; 816 } 817 818 (void) NonZeroOffset; // Silence set but not used warning. 819 assert((VirtualBase || NonZeroOffset) && 820 "Should have returned if has non-virtual base with zero offset"); 821 822 QualType BaseType = 823 ReinterpretKind == ReinterpretUpcast? DestType : SrcType; 824 QualType DerivedType = 825 ReinterpretKind == ReinterpretUpcast? SrcType : DestType; 826 827 SourceLocation BeginLoc = OpRange.getBegin(); 828 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) 829 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) 830 << OpRange; 831 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) 832 << int(ReinterpretKind) 833 << FixItHint::CreateReplacement(BeginLoc, "static_cast"); 834 } 835 836 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 837 /// valid. 838 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 839 /// like this: 840 /// char *bytes = reinterpret_cast\<char*\>(int_ptr); 841 void CastOperation::CheckReinterpretCast() { 842 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) 843 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 844 else 845 checkNonOverloadPlaceholders(); 846 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 847 return; 848 849 unsigned msg = diag::err_bad_cxx_cast_generic; 850 TryCastResult tcr = 851 TryReinterpretCast(Self, SrcExpr, DestType, 852 /*CStyle*/false, OpRange, msg, Kind); 853 if (tcr != TC_Success && msg != 0) 854 { 855 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 856 return; 857 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 858 //FIXME: &f<int>; is overloaded and resolvable 859 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 860 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 861 << DestType << OpRange; 862 Self.NoteAllOverloadCandidates(SrcExpr.get()); 863 864 } else { 865 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), 866 DestType, /*listInitialization=*/false); 867 } 868 SrcExpr = ExprError(); 869 } else if (tcr == TC_Success) { 870 if (Self.getLangOpts().ObjCAutoRefCount) 871 checkObjCARCConversion(Sema::CCK_OtherCast); 872 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); 873 } 874 } 875 876 877 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 878 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 879 /// implicit conversions explicit and getting rid of data loss warnings. 880 void CastOperation::CheckStaticCast() { 881 if (isPlaceholder()) { 882 checkNonOverloadPlaceholders(); 883 if (SrcExpr.isInvalid()) 884 return; 885 } 886 887 // This test is outside everything else because it's the only case where 888 // a non-lvalue-reference target type does not lead to decay. 889 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 890 if (DestType->isVoidType()) { 891 Kind = CK_ToVoid; 892 893 if (claimPlaceholder(BuiltinType::Overload)) { 894 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 895 false, // Decay Function to ptr 896 true, // Complain 897 OpRange, DestType, diag::err_bad_static_cast_overload); 898 if (SrcExpr.isInvalid()) 899 return; 900 } 901 902 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 903 return; 904 } 905 906 if (ValueKind == VK_RValue && !DestType->isRecordType() && 907 !isPlaceholder(BuiltinType::Overload)) { 908 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 909 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 910 return; 911 } 912 913 unsigned msg = diag::err_bad_cxx_cast_generic; 914 TryCastResult tcr 915 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 916 Kind, BasePath, /*ListInitialization=*/false); 917 if (tcr != TC_Success && msg != 0) { 918 if (SrcExpr.isInvalid()) 919 return; 920 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 921 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 922 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 923 << oe->getName() << DestType << OpRange 924 << oe->getQualifierLoc().getSourceRange(); 925 Self.NoteAllOverloadCandidates(SrcExpr.get()); 926 } else { 927 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, 928 /*listInitialization=*/false); 929 } 930 SrcExpr = ExprError(); 931 } else if (tcr == TC_Success) { 932 if (Kind == CK_BitCast) 933 checkCastAlign(); 934 if (Self.getLangOpts().ObjCAutoRefCount) 935 checkObjCARCConversion(Sema::CCK_OtherCast); 936 } else if (Kind == CK_BitCast) { 937 checkCastAlign(); 938 } 939 } 940 941 /// TryStaticCast - Check if a static cast can be performed, and do so if 942 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting 943 /// and casting away constness. 944 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 945 QualType DestType, 946 Sema::CheckedConversionKind CCK, 947 SourceRange OpRange, unsigned &msg, 948 CastKind &Kind, CXXCastPath &BasePath, 949 bool ListInitialization) { 950 // Determine whether we have the semantics of a C-style cast. 951 bool CStyle 952 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 953 954 // The order the tests is not entirely arbitrary. There is one conversion 955 // that can be handled in two different ways. Given: 956 // struct A {}; 957 // struct B : public A { 958 // B(); B(const A&); 959 // }; 960 // const A &a = B(); 961 // the cast static_cast<const B&>(a) could be seen as either a static 962 // reference downcast, or an explicit invocation of the user-defined 963 // conversion using B's conversion constructor. 964 // DR 427 specifies that the downcast is to be applied here. 965 966 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 967 // Done outside this function. 968 969 TryCastResult tcr; 970 971 // C++ 5.2.9p5, reference downcast. 972 // See the function for details. 973 // DR 427 specifies that this is to be applied before paragraph 2. 974 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, 975 OpRange, msg, Kind, BasePath); 976 if (tcr != TC_NotApplicable) 977 return tcr; 978 979 // C++11 [expr.static.cast]p3: 980 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 981 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 982 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 983 BasePath, msg); 984 if (tcr != TC_NotApplicable) 985 return tcr; 986 987 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 988 // [...] if the declaration "T t(e);" is well-formed, [...]. 989 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 990 Kind, ListInitialization); 991 if (SrcExpr.isInvalid()) 992 return TC_Failed; 993 if (tcr != TC_NotApplicable) 994 return tcr; 995 996 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 997 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 998 // conversions, subject to further restrictions. 999 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 1000 // of qualification conversions impossible. 1001 // In the CStyle case, the earlier attempt to const_cast should have taken 1002 // care of reverse qualification conversions. 1003 1004 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 1005 1006 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 1007 // converted to an integral type. [...] A value of a scoped enumeration type 1008 // can also be explicitly converted to a floating-point type [...]. 1009 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 1010 if (Enum->getDecl()->isScoped()) { 1011 if (DestType->isBooleanType()) { 1012 Kind = CK_IntegralToBoolean; 1013 return TC_Success; 1014 } else if (DestType->isIntegralType(Self.Context)) { 1015 Kind = CK_IntegralCast; 1016 return TC_Success; 1017 } else if (DestType->isRealFloatingType()) { 1018 Kind = CK_IntegralToFloating; 1019 return TC_Success; 1020 } 1021 } 1022 } 1023 1024 // Reverse integral promotion/conversion. All such conversions are themselves 1025 // again integral promotions or conversions and are thus already handled by 1026 // p2 (TryDirectInitialization above). 1027 // (Note: any data loss warnings should be suppressed.) 1028 // The exception is the reverse of enum->integer, i.e. integer->enum (and 1029 // enum->enum). See also C++ 5.2.9p7. 1030 // The same goes for reverse floating point promotion/conversion and 1031 // floating-integral conversions. Again, only floating->enum is relevant. 1032 if (DestType->isEnumeralType()) { 1033 if (SrcType->isIntegralOrEnumerationType()) { 1034 Kind = CK_IntegralCast; 1035 return TC_Success; 1036 } else if (SrcType->isRealFloatingType()) { 1037 Kind = CK_FloatingToIntegral; 1038 return TC_Success; 1039 } 1040 } 1041 1042 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 1043 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 1044 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 1045 Kind, BasePath); 1046 if (tcr != TC_NotApplicable) 1047 return tcr; 1048 1049 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 1050 // conversion. C++ 5.2.9p9 has additional information. 1051 // DR54's access restrictions apply here also. 1052 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 1053 OpRange, msg, Kind, BasePath); 1054 if (tcr != TC_NotApplicable) 1055 return tcr; 1056 1057 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 1058 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 1059 // just the usual constness stuff. 1060 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 1061 QualType SrcPointee = SrcPointer->getPointeeType(); 1062 if (SrcPointee->isVoidType()) { 1063 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 1064 QualType DestPointee = DestPointer->getPointeeType(); 1065 if (DestPointee->isIncompleteOrObjectType()) { 1066 // This is definitely the intended conversion, but it might fail due 1067 // to a qualifier violation. Note that we permit Objective-C lifetime 1068 // and GC qualifier mismatches here. 1069 if (!CStyle) { 1070 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 1071 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 1072 DestPointeeQuals.removeObjCGCAttr(); 1073 DestPointeeQuals.removeObjCLifetime(); 1074 SrcPointeeQuals.removeObjCGCAttr(); 1075 SrcPointeeQuals.removeObjCLifetime(); 1076 if (DestPointeeQuals != SrcPointeeQuals && 1077 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 1078 msg = diag::err_bad_cxx_cast_qualifiers_away; 1079 return TC_Failed; 1080 } 1081 } 1082 Kind = CK_BitCast; 1083 return TC_Success; 1084 } 1085 1086 // Microsoft permits static_cast from 'pointer-to-void' to 1087 // 'pointer-to-function'. 1088 if (!CStyle && Self.getLangOpts().MSVCCompat && 1089 DestPointee->isFunctionType()) { 1090 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; 1091 Kind = CK_BitCast; 1092 return TC_Success; 1093 } 1094 } 1095 else if (DestType->isObjCObjectPointerType()) { 1096 // allow both c-style cast and static_cast of objective-c pointers as 1097 // they are pervasive. 1098 Kind = CK_CPointerToObjCPointerCast; 1099 return TC_Success; 1100 } 1101 else if (CStyle && DestType->isBlockPointerType()) { 1102 // allow c-style cast of void * to block pointers. 1103 Kind = CK_AnyPointerToBlockPointerCast; 1104 return TC_Success; 1105 } 1106 } 1107 } 1108 // Allow arbitray objective-c pointer conversion with static casts. 1109 if (SrcType->isObjCObjectPointerType() && 1110 DestType->isObjCObjectPointerType()) { 1111 Kind = CK_BitCast; 1112 return TC_Success; 1113 } 1114 // Allow ns-pointer to cf-pointer conversion in either direction 1115 // with static casts. 1116 if (!CStyle && 1117 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) 1118 return TC_Success; 1119 1120 // See if it looks like the user is trying to convert between 1121 // related record types, and select a better diagnostic if so. 1122 if (auto SrcPointer = SrcType->getAs<PointerType>()) 1123 if (auto DestPointer = DestType->getAs<PointerType>()) 1124 if (SrcPointer->getPointeeType()->getAs<RecordType>() && 1125 DestPointer->getPointeeType()->getAs<RecordType>()) 1126 msg = diag::err_bad_cxx_cast_unrelated_class; 1127 1128 // We tried everything. Everything! Nothing works! :-( 1129 return TC_NotApplicable; 1130 } 1131 1132 /// Tests whether a conversion according to N2844 is valid. 1133 TryCastResult 1134 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, 1135 bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 1136 unsigned &msg) { 1137 // C++11 [expr.static.cast]p3: 1138 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 1139 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1140 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 1141 if (!R) 1142 return TC_NotApplicable; 1143 1144 if (!SrcExpr->isGLValue()) 1145 return TC_NotApplicable; 1146 1147 // Because we try the reference downcast before this function, from now on 1148 // this is the only cast possibility, so we issue an error if we fail now. 1149 // FIXME: Should allow casting away constness if CStyle. 1150 bool DerivedToBase; 1151 bool ObjCConversion; 1152 bool ObjCLifetimeConversion; 1153 QualType FromType = SrcExpr->getType(); 1154 QualType ToType = R->getPointeeType(); 1155 if (CStyle) { 1156 FromType = FromType.getUnqualifiedType(); 1157 ToType = ToType.getUnqualifiedType(); 1158 } 1159 1160 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(), 1161 ToType, FromType, 1162 DerivedToBase, ObjCConversion, 1163 ObjCLifetimeConversion) 1164 < Sema::Ref_Compatible_With_Added_Qualification) { 1165 if (CStyle) 1166 return TC_NotApplicable; 1167 msg = diag::err_bad_lvalue_to_rvalue_cast; 1168 return TC_Failed; 1169 } 1170 1171 if (DerivedToBase) { 1172 Kind = CK_DerivedToBase; 1173 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1174 /*DetectVirtual=*/true); 1175 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(), 1176 R->getPointeeType(), Paths)) 1177 return TC_NotApplicable; 1178 1179 Self.BuildBasePathArray(Paths, BasePath); 1180 } else 1181 Kind = CK_NoOp; 1182 1183 return TC_Success; 1184 } 1185 1186 /// Tests whether a conversion according to C++ 5.2.9p5 is valid. 1187 TryCastResult 1188 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 1189 bool CStyle, SourceRange OpRange, 1190 unsigned &msg, CastKind &Kind, 1191 CXXCastPath &BasePath) { 1192 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 1193 // cast to type "reference to cv2 D", where D is a class derived from B, 1194 // if a valid standard conversion from "pointer to D" to "pointer to B" 1195 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1196 // In addition, DR54 clarifies that the base must be accessible in the 1197 // current context. Although the wording of DR54 only applies to the pointer 1198 // variant of this rule, the intent is clearly for it to apply to the this 1199 // conversion as well. 1200 1201 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1202 if (!DestReference) { 1203 return TC_NotApplicable; 1204 } 1205 bool RValueRef = DestReference->isRValueReferenceType(); 1206 if (!RValueRef && !SrcExpr->isLValue()) { 1207 // We know the left side is an lvalue reference, so we can suggest a reason. 1208 msg = diag::err_bad_cxx_cast_rvalue; 1209 return TC_NotApplicable; 1210 } 1211 1212 QualType DestPointee = DestReference->getPointeeType(); 1213 1214 // FIXME: If the source is a prvalue, we should issue a warning (because the 1215 // cast always has undefined behavior), and for AST consistency, we should 1216 // materialize a temporary. 1217 return TryStaticDowncast(Self, 1218 Self.Context.getCanonicalType(SrcExpr->getType()), 1219 Self.Context.getCanonicalType(DestPointee), CStyle, 1220 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1221 BasePath); 1222 } 1223 1224 /// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1225 TryCastResult 1226 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1227 bool CStyle, SourceRange OpRange, 1228 unsigned &msg, CastKind &Kind, 1229 CXXCastPath &BasePath) { 1230 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1231 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1232 // is a class derived from B, if a valid standard conversion from "pointer 1233 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1234 // class of D. 1235 // In addition, DR54 clarifies that the base must be accessible in the 1236 // current context. 1237 1238 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1239 if (!DestPointer) { 1240 return TC_NotApplicable; 1241 } 1242 1243 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1244 if (!SrcPointer) { 1245 msg = diag::err_bad_static_cast_pointer_nonpointer; 1246 return TC_NotApplicable; 1247 } 1248 1249 return TryStaticDowncast(Self, 1250 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1251 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1252 CStyle, OpRange, SrcType, DestType, msg, Kind, 1253 BasePath); 1254 } 1255 1256 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1257 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1258 /// DestType is possible and allowed. 1259 TryCastResult 1260 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1261 bool CStyle, SourceRange OpRange, QualType OrigSrcType, 1262 QualType OrigDestType, unsigned &msg, 1263 CastKind &Kind, CXXCastPath &BasePath) { 1264 // We can only work with complete types. But don't complain if it doesn't work 1265 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || 1266 !Self.isCompleteType(OpRange.getBegin(), DestType)) 1267 return TC_NotApplicable; 1268 1269 // Downcast can only happen in class hierarchies, so we need classes. 1270 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1271 return TC_NotApplicable; 1272 } 1273 1274 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1275 /*DetectVirtual=*/true); 1276 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { 1277 return TC_NotApplicable; 1278 } 1279 1280 // Target type does derive from source type. Now we're serious. If an error 1281 // appears now, it's not ignored. 1282 // This may not be entirely in line with the standard. Take for example: 1283 // struct A {}; 1284 // struct B : virtual A { 1285 // B(A&); 1286 // }; 1287 // 1288 // void f() 1289 // { 1290 // (void)static_cast<const B&>(*((A*)0)); 1291 // } 1292 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1293 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1294 // However, both GCC and Comeau reject this example, and accepting it would 1295 // mean more complex code if we're to preserve the nice error message. 1296 // FIXME: Being 100% compliant here would be nice to have. 1297 1298 // Must preserve cv, as always, unless we're in C-style mode. 1299 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1300 msg = diag::err_bad_cxx_cast_qualifiers_away; 1301 return TC_Failed; 1302 } 1303 1304 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1305 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1306 // that it builds the paths in reverse order. 1307 // To sum up: record all paths to the base and build a nice string from 1308 // them. Use it to spice up the error message. 1309 if (!Paths.isRecordingPaths()) { 1310 Paths.clear(); 1311 Paths.setRecordingPaths(true); 1312 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); 1313 } 1314 std::string PathDisplayStr; 1315 std::set<unsigned> DisplayedPaths; 1316 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end(); 1317 PI != PE; ++PI) { 1318 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) { 1319 // We haven't displayed a path to this particular base 1320 // class subobject yet. 1321 PathDisplayStr += "\n "; 1322 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(), 1323 EE = PI->rend(); 1324 EI != EE; ++EI) 1325 PathDisplayStr += EI->Base->getType().getAsString() + " -> "; 1326 PathDisplayStr += QualType(DestType).getAsString(); 1327 } 1328 } 1329 1330 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1331 << QualType(SrcType).getUnqualifiedType() 1332 << QualType(DestType).getUnqualifiedType() 1333 << PathDisplayStr << OpRange; 1334 msg = 0; 1335 return TC_Failed; 1336 } 1337 1338 if (Paths.getDetectedVirtual() != nullptr) { 1339 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1340 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1341 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1342 msg = 0; 1343 return TC_Failed; 1344 } 1345 1346 if (!CStyle) { 1347 unsigned Diag = Self.getLangOpts().MSVCCompat 1348 ? diag::ext_ms_downcast_from_inaccessible_base 1349 : diag::err_downcast_from_inaccessible_base; 1350 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), SrcType, DestType, 1351 Paths.front(), Diag)) { 1352 case Sema::AR_accessible: 1353 case Sema::AR_delayed: // be optimistic 1354 case Sema::AR_dependent: // be optimistic 1355 break; 1356 1357 case Sema::AR_inaccessible: 1358 msg = 0; 1359 return TC_Failed; 1360 } 1361 } 1362 1363 Self.BuildBasePathArray(Paths, BasePath); 1364 Kind = CK_BaseToDerived; 1365 return TC_Success; 1366 } 1367 1368 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1369 /// C++ 5.2.9p9 is valid: 1370 /// 1371 /// An rvalue of type "pointer to member of D of type cv1 T" can be 1372 /// converted to an rvalue of type "pointer to member of B of type cv2 T", 1373 /// where B is a base class of D [...]. 1374 /// 1375 TryCastResult 1376 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1377 QualType DestType, bool CStyle, 1378 SourceRange OpRange, 1379 unsigned &msg, CastKind &Kind, 1380 CXXCastPath &BasePath) { 1381 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1382 if (!DestMemPtr) 1383 return TC_NotApplicable; 1384 1385 bool WasOverloadedFunction = false; 1386 DeclAccessPair FoundOverload; 1387 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1388 if (FunctionDecl *Fn 1389 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1390 FoundOverload)) { 1391 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1392 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1393 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1394 WasOverloadedFunction = true; 1395 } 1396 } 1397 1398 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1399 if (!SrcMemPtr) { 1400 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1401 return TC_NotApplicable; 1402 } 1403 1404 // Lock down the inheritance model right now in MS ABI, whether or not the 1405 // pointee types are the same. 1406 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1407 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 1408 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 1409 } 1410 1411 // T == T, modulo cv 1412 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1413 DestMemPtr->getPointeeType())) 1414 return TC_NotApplicable; 1415 1416 // B base of D 1417 QualType SrcClass(SrcMemPtr->getClass(), 0); 1418 QualType DestClass(DestMemPtr->getClass(), 0); 1419 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1420 /*DetectVirtual=*/true); 1421 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) 1422 return TC_NotApplicable; 1423 1424 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1425 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1426 Paths.clear(); 1427 Paths.setRecordingPaths(true); 1428 bool StillOkay = 1429 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); 1430 assert(StillOkay); 1431 (void)StillOkay; 1432 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1433 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1434 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1435 msg = 0; 1436 return TC_Failed; 1437 } 1438 1439 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1440 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1441 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1442 msg = 0; 1443 return TC_Failed; 1444 } 1445 1446 if (!CStyle) { 1447 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1448 DestClass, SrcClass, 1449 Paths.front(), 1450 diag::err_upcast_to_inaccessible_base)) { 1451 case Sema::AR_accessible: 1452 case Sema::AR_delayed: 1453 case Sema::AR_dependent: 1454 // Optimistically assume that the delayed and dependent cases 1455 // will work out. 1456 break; 1457 1458 case Sema::AR_inaccessible: 1459 msg = 0; 1460 return TC_Failed; 1461 } 1462 } 1463 1464 if (WasOverloadedFunction) { 1465 // Resolve the address of the overloaded function again, this time 1466 // allowing complaints if something goes wrong. 1467 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1468 DestType, 1469 true, 1470 FoundOverload); 1471 if (!Fn) { 1472 msg = 0; 1473 return TC_Failed; 1474 } 1475 1476 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1477 if (!SrcExpr.isUsable()) { 1478 msg = 0; 1479 return TC_Failed; 1480 } 1481 } 1482 1483 Self.BuildBasePathArray(Paths, BasePath); 1484 Kind = CK_DerivedToBaseMemberPointer; 1485 return TC_Success; 1486 } 1487 1488 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1489 /// is valid: 1490 /// 1491 /// An expression e can be explicitly converted to a type T using a 1492 /// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1493 TryCastResult 1494 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1495 Sema::CheckedConversionKind CCK, 1496 SourceRange OpRange, unsigned &msg, 1497 CastKind &Kind, bool ListInitialization) { 1498 if (DestType->isRecordType()) { 1499 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1500 diag::err_bad_dynamic_cast_incomplete) || 1501 Self.RequireNonAbstractType(OpRange.getBegin(), DestType, 1502 diag::err_allocation_of_abstract_type)) { 1503 msg = 0; 1504 return TC_Failed; 1505 } 1506 } 1507 1508 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1509 InitializationKind InitKind 1510 = (CCK == Sema::CCK_CStyleCast) 1511 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, 1512 ListInitialization) 1513 : (CCK == Sema::CCK_FunctionalCast) 1514 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) 1515 : InitializationKind::CreateCast(OpRange); 1516 Expr *SrcExprRaw = SrcExpr.get(); 1517 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); 1518 1519 // At this point of CheckStaticCast, if the destination is a reference, 1520 // or the expression is an overload expression this has to work. 1521 // There is no other way that works. 1522 // On the other hand, if we're checking a C-style cast, we've still got 1523 // the reinterpret_cast way. 1524 bool CStyle 1525 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1526 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1527 return TC_NotApplicable; 1528 1529 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); 1530 if (Result.isInvalid()) { 1531 msg = 0; 1532 return TC_Failed; 1533 } 1534 1535 if (InitSeq.isConstructorInitialization()) 1536 Kind = CK_ConstructorConversion; 1537 else 1538 Kind = CK_NoOp; 1539 1540 SrcExpr = Result; 1541 return TC_Success; 1542 } 1543 1544 /// TryConstCast - See if a const_cast from source to destination is allowed, 1545 /// and perform it if it is. 1546 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 1547 QualType DestType, bool CStyle, 1548 unsigned &msg) { 1549 DestType = Self.Context.getCanonicalType(DestType); 1550 QualType SrcType = SrcExpr.get()->getType(); 1551 bool NeedToMaterializeTemporary = false; 1552 1553 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1554 // C++11 5.2.11p4: 1555 // if a pointer to T1 can be explicitly converted to the type "pointer to 1556 // T2" using a const_cast, then the following conversions can also be 1557 // made: 1558 // -- an lvalue of type T1 can be explicitly converted to an lvalue of 1559 // type T2 using the cast const_cast<T2&>; 1560 // -- a glvalue of type T1 can be explicitly converted to an xvalue of 1561 // type T2 using the cast const_cast<T2&&>; and 1562 // -- if T1 is a class type, a prvalue of type T1 can be explicitly 1563 // converted to an xvalue of type T2 using the cast const_cast<T2&&>. 1564 1565 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { 1566 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1567 // is C-style, static_cast might find a way, so we simply suggest a 1568 // message and tell the parent to keep searching. 1569 msg = diag::err_bad_cxx_cast_rvalue; 1570 return TC_NotApplicable; 1571 } 1572 1573 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) { 1574 if (!SrcType->isRecordType()) { 1575 // Cannot const_cast non-class prvalue to rvalue reference type. But if 1576 // this is C-style, static_cast can do this. 1577 msg = diag::err_bad_cxx_cast_rvalue; 1578 return TC_NotApplicable; 1579 } 1580 1581 // Materialize the class prvalue so that the const_cast can bind a 1582 // reference to it. 1583 NeedToMaterializeTemporary = true; 1584 } 1585 1586 // It's not completely clear under the standard whether we can 1587 // const_cast bit-field gl-values. Doing so would not be 1588 // intrinsically complicated, but for now, we say no for 1589 // consistency with other compilers and await the word of the 1590 // committee. 1591 if (SrcExpr.get()->refersToBitField()) { 1592 msg = diag::err_bad_cxx_cast_bitfield; 1593 return TC_NotApplicable; 1594 } 1595 1596 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1597 SrcType = Self.Context.getPointerType(SrcType); 1598 } 1599 1600 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1601 // the rules for const_cast are the same as those used for pointers. 1602 1603 if (!DestType->isPointerType() && 1604 !DestType->isMemberPointerType() && 1605 !DestType->isObjCObjectPointerType()) { 1606 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1607 // was a reference type, we converted it to a pointer above. 1608 // The status of rvalue references isn't entirely clear, but it looks like 1609 // conversion to them is simply invalid. 1610 // C++ 5.2.11p3: For two pointer types [...] 1611 if (!CStyle) 1612 msg = diag::err_bad_const_cast_dest; 1613 return TC_NotApplicable; 1614 } 1615 if (DestType->isFunctionPointerType() || 1616 DestType->isMemberFunctionPointerType()) { 1617 // Cannot cast direct function pointers. 1618 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1619 // T is the ultimate pointee of source and target type. 1620 if (!CStyle) 1621 msg = diag::err_bad_const_cast_dest; 1622 return TC_NotApplicable; 1623 } 1624 SrcType = Self.Context.getCanonicalType(SrcType); 1625 1626 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 1627 // completely equal. 1628 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 1629 // in multi-level pointers may change, but the level count must be the same, 1630 // as must be the final pointee type. 1631 while (SrcType != DestType && 1632 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 1633 Qualifiers SrcQuals, DestQuals; 1634 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 1635 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 1636 1637 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 1638 // the other qualifiers (e.g., address spaces) are identical. 1639 SrcQuals.removeCVRQualifiers(); 1640 DestQuals.removeCVRQualifiers(); 1641 if (SrcQuals != DestQuals) 1642 return TC_NotApplicable; 1643 } 1644 1645 // Since we're dealing in canonical types, the remainder must be the same. 1646 if (SrcType != DestType) 1647 return TC_NotApplicable; 1648 1649 if (NeedToMaterializeTemporary) 1650 // This is a const_cast from a class prvalue to an rvalue reference type. 1651 // Materialize a temporary to store the result of the conversion. 1652 SrcExpr = new (Self.Context) MaterializeTemporaryExpr( 1653 SrcType, SrcExpr.get(), /*IsLValueReference*/ false); 1654 1655 return TC_Success; 1656 } 1657 1658 // Checks for undefined behavior in reinterpret_cast. 1659 // The cases that is checked for is: 1660 // *reinterpret_cast<T*>(&a) 1661 // reinterpret_cast<T&>(a) 1662 // where accessing 'a' as type 'T' will result in undefined behavior. 1663 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 1664 bool IsDereference, 1665 SourceRange Range) { 1666 unsigned DiagID = IsDereference ? 1667 diag::warn_pointer_indirection_from_incompatible_type : 1668 diag::warn_undefined_reinterpret_cast; 1669 1670 if (Diags.isIgnored(DiagID, Range.getBegin())) 1671 return; 1672 1673 QualType SrcTy, DestTy; 1674 if (IsDereference) { 1675 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 1676 return; 1677 } 1678 SrcTy = SrcType->getPointeeType(); 1679 DestTy = DestType->getPointeeType(); 1680 } else { 1681 if (!DestType->getAs<ReferenceType>()) { 1682 return; 1683 } 1684 SrcTy = SrcType; 1685 DestTy = DestType->getPointeeType(); 1686 } 1687 1688 // Cast is compatible if the types are the same. 1689 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 1690 return; 1691 } 1692 // or one of the types is a char or void type 1693 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 1694 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 1695 return; 1696 } 1697 // or one of the types is a tag type. 1698 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 1699 return; 1700 } 1701 1702 // FIXME: Scoped enums? 1703 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 1704 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 1705 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 1706 return; 1707 } 1708 } 1709 1710 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 1711 } 1712 1713 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, 1714 QualType DestType) { 1715 QualType SrcType = SrcExpr.get()->getType(); 1716 if (Self.Context.hasSameType(SrcType, DestType)) 1717 return; 1718 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) 1719 if (SrcPtrTy->isObjCSelType()) { 1720 QualType DT = DestType; 1721 if (isa<PointerType>(DestType)) 1722 DT = DestType->getPointeeType(); 1723 if (!DT.getUnqualifiedType()->isVoidType()) 1724 Self.Diag(SrcExpr.get()->getExprLoc(), 1725 diag::warn_cast_pointer_from_sel) 1726 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 1727 } 1728 } 1729 1730 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc, 1731 const Expr *SrcExpr, QualType DestType, 1732 Sema &Self) { 1733 QualType SrcType = SrcExpr->getType(); 1734 1735 // Not warning on reinterpret_cast, boolean, constant expressions, etc 1736 // are not explicit design choices, but consistent with GCC's behavior. 1737 // Feel free to modify them if you've reason/evidence for an alternative. 1738 if (CStyle && SrcType->isIntegralType(Self.Context) 1739 && !SrcType->isBooleanType() 1740 && !SrcType->isEnumeralType() 1741 && !SrcExpr->isIntegerConstantExpr(Self.Context) 1742 && Self.Context.getTypeSize(DestType) > 1743 Self.Context.getTypeSize(SrcType)) { 1744 // Separate between casts to void* and non-void* pointers. 1745 // Some APIs use (abuse) void* for something like a user context, 1746 // and often that value is an integer even if it isn't a pointer itself. 1747 // Having a separate warning flag allows users to control the warning 1748 // for their workflow. 1749 unsigned Diag = DestType->isVoidPointerType() ? 1750 diag::warn_int_to_void_pointer_cast 1751 : diag::warn_int_to_pointer_cast; 1752 Self.Diag(Loc, Diag) << SrcType << DestType; 1753 } 1754 } 1755 1756 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, 1757 ExprResult &Result) { 1758 // We can only fix an overloaded reinterpret_cast if 1759 // - it is a template with explicit arguments that resolves to an lvalue 1760 // unambiguously, or 1761 // - it is the only function in an overload set that may have its address 1762 // taken. 1763 1764 Expr *E = Result.get(); 1765 // TODO: what if this fails because of DiagnoseUseOfDecl or something 1766 // like it? 1767 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 1768 Result, 1769 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 1770 ) && 1771 Result.isUsable()) 1772 return true; 1773 1774 DeclAccessPair DAP; 1775 FunctionDecl *Found = Self.resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 1776 if (!Found) 1777 return false; 1778 1779 // It seems that if we encounter a call to a function that is both unavailable 1780 // and inaccessible, we'll emit multiple diags for said call. Hence, we run 1781 // both checks below unconditionally. 1782 Self.DiagnoseUseOfDecl(Found, E->getExprLoc()); 1783 Self.CheckAddressOfMemberAccess(E, DAP); 1784 1785 Expr *Fixed = Self.FixOverloadedFunctionReference(E, DAP, Found); 1786 if (Fixed->getType()->isFunctionType()) 1787 Result = Self.DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 1788 else 1789 Result = Fixed; 1790 1791 return !Result.isInvalid(); 1792 } 1793 1794 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 1795 QualType DestType, bool CStyle, 1796 SourceRange OpRange, 1797 unsigned &msg, 1798 CastKind &Kind) { 1799 bool IsLValueCast = false; 1800 1801 DestType = Self.Context.getCanonicalType(DestType); 1802 QualType SrcType = SrcExpr.get()->getType(); 1803 1804 // Is the source an overloaded name? (i.e. &foo) 1805 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) 1806 if (SrcType == Self.Context.OverloadTy) { 1807 ExprResult FixedExpr = SrcExpr; 1808 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) 1809 return TC_NotApplicable; 1810 1811 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr"); 1812 SrcExpr = FixedExpr; 1813 SrcType = SrcExpr.get()->getType(); 1814 } 1815 1816 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 1817 if (!SrcExpr.get()->isGLValue()) { 1818 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the 1819 // similar comment in const_cast. 1820 msg = diag::err_bad_cxx_cast_rvalue; 1821 return TC_NotApplicable; 1822 } 1823 1824 if (!CStyle) { 1825 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 1826 /*isDereference=*/false, OpRange); 1827 } 1828 1829 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 1830 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 1831 // built-in & and * operators. 1832 1833 const char *inappropriate = nullptr; 1834 switch (SrcExpr.get()->getObjectKind()) { 1835 case OK_Ordinary: 1836 break; 1837 case OK_BitField: inappropriate = "bit-field"; break; 1838 case OK_VectorComponent: inappropriate = "vector element"; break; 1839 case OK_ObjCProperty: inappropriate = "property expression"; break; 1840 case OK_ObjCSubscript: inappropriate = "container subscripting expression"; 1841 break; 1842 } 1843 if (inappropriate) { 1844 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 1845 << inappropriate << DestType 1846 << OpRange << SrcExpr.get()->getSourceRange(); 1847 msg = 0; SrcExpr = ExprError(); 1848 return TC_NotApplicable; 1849 } 1850 1851 // This code does this transformation for the checked types. 1852 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1853 SrcType = Self.Context.getPointerType(SrcType); 1854 1855 IsLValueCast = true; 1856 } 1857 1858 // Canonicalize source for comparison. 1859 SrcType = Self.Context.getCanonicalType(SrcType); 1860 1861 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 1862 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1863 if (DestMemPtr && SrcMemPtr) { 1864 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 1865 // can be explicitly converted to an rvalue of type "pointer to member 1866 // of Y of type T2" if T1 and T2 are both function types or both object 1867 // types. 1868 if (DestMemPtr->isMemberFunctionPointer() != 1869 SrcMemPtr->isMemberFunctionPointer()) 1870 return TC_NotApplicable; 1871 1872 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 1873 // constness. 1874 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 1875 // we accept it. 1876 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 1877 /*CheckObjCLifetime=*/CStyle)) { 1878 msg = diag::err_bad_cxx_cast_qualifiers_away; 1879 return TC_Failed; 1880 } 1881 1882 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1883 // We need to determine the inheritance model that the class will use if 1884 // haven't yet. 1885 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 1886 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 1887 } 1888 1889 // Don't allow casting between member pointers of different sizes. 1890 if (Self.Context.getTypeSize(DestMemPtr) != 1891 Self.Context.getTypeSize(SrcMemPtr)) { 1892 msg = diag::err_bad_cxx_cast_member_pointer_size; 1893 return TC_Failed; 1894 } 1895 1896 // A valid member pointer cast. 1897 assert(!IsLValueCast); 1898 Kind = CK_ReinterpretMemberPointer; 1899 return TC_Success; 1900 } 1901 1902 // See below for the enumeral issue. 1903 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 1904 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 1905 // type large enough to hold it. A value of std::nullptr_t can be 1906 // converted to an integral type; the conversion has the same meaning 1907 // and validity as a conversion of (void*)0 to the integral type. 1908 if (Self.Context.getTypeSize(SrcType) > 1909 Self.Context.getTypeSize(DestType)) { 1910 msg = diag::err_bad_reinterpret_cast_small_int; 1911 return TC_Failed; 1912 } 1913 Kind = CK_PointerToIntegral; 1914 return TC_Success; 1915 } 1916 1917 // Allow reinterpret_casts between vectors of the same size and 1918 // between vectors and integers of the same size. 1919 bool destIsVector = DestType->isVectorType(); 1920 bool srcIsVector = SrcType->isVectorType(); 1921 if (srcIsVector || destIsVector) { 1922 // The non-vector type, if any, must have integral type. This is 1923 // the same rule that C vector casts use; note, however, that enum 1924 // types are not integral in C++. 1925 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) || 1926 (!srcIsVector && !SrcType->isIntegralType(Self.Context))) 1927 return TC_NotApplicable; 1928 1929 // The size we want to consider is eltCount * eltSize. 1930 // That's exactly what the lax-conversion rules will check. 1931 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { 1932 Kind = CK_BitCast; 1933 return TC_Success; 1934 } 1935 1936 // Otherwise, pick a reasonable diagnostic. 1937 if (!destIsVector) 1938 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 1939 else if (!srcIsVector) 1940 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 1941 else 1942 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 1943 1944 return TC_Failed; 1945 } 1946 1947 if (SrcType == DestType) { 1948 // C++ 5.2.10p2 has a note that mentions that, subject to all other 1949 // restrictions, a cast to the same type is allowed so long as it does not 1950 // cast away constness. In C++98, the intent was not entirely clear here, 1951 // since all other paragraphs explicitly forbid casts to the same type. 1952 // C++11 clarifies this case with p2. 1953 // 1954 // The only allowed types are: integral, enumeration, pointer, or 1955 // pointer-to-member types. We also won't restrict Obj-C pointers either. 1956 Kind = CK_NoOp; 1957 TryCastResult Result = TC_NotApplicable; 1958 if (SrcType->isIntegralOrEnumerationType() || 1959 SrcType->isAnyPointerType() || 1960 SrcType->isMemberPointerType() || 1961 SrcType->isBlockPointerType()) { 1962 Result = TC_Success; 1963 } 1964 return Result; 1965 } 1966 1967 bool destIsPtr = DestType->isAnyPointerType() || 1968 DestType->isBlockPointerType(); 1969 bool srcIsPtr = SrcType->isAnyPointerType() || 1970 SrcType->isBlockPointerType(); 1971 if (!destIsPtr && !srcIsPtr) { 1972 // Except for std::nullptr_t->integer and lvalue->reference, which are 1973 // handled above, at least one of the two arguments must be a pointer. 1974 return TC_NotApplicable; 1975 } 1976 1977 if (DestType->isIntegralType(Self.Context)) { 1978 assert(srcIsPtr && "One type must be a pointer"); 1979 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 1980 // type large enough to hold it; except in Microsoft mode, where the 1981 // integral type size doesn't matter (except we don't allow bool). 1982 bool MicrosoftException = Self.getLangOpts().MicrosoftExt && 1983 !DestType->isBooleanType(); 1984 if ((Self.Context.getTypeSize(SrcType) > 1985 Self.Context.getTypeSize(DestType)) && 1986 !MicrosoftException) { 1987 msg = diag::err_bad_reinterpret_cast_small_int; 1988 return TC_Failed; 1989 } 1990 Kind = CK_PointerToIntegral; 1991 return TC_Success; 1992 } 1993 1994 if (SrcType->isIntegralOrEnumerationType()) { 1995 assert(destIsPtr && "One type must be a pointer"); 1996 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType, 1997 Self); 1998 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 1999 // converted to a pointer. 2000 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 2001 // necessarily converted to a null pointer value.] 2002 Kind = CK_IntegralToPointer; 2003 return TC_Success; 2004 } 2005 2006 if (!destIsPtr || !srcIsPtr) { 2007 // With the valid non-pointer conversions out of the way, we can be even 2008 // more stringent. 2009 return TC_NotApplicable; 2010 } 2011 2012 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 2013 // The C-style cast operator can. 2014 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 2015 /*CheckObjCLifetime=*/CStyle)) { 2016 msg = diag::err_bad_cxx_cast_qualifiers_away; 2017 return TC_Failed; 2018 } 2019 2020 // Cannot convert between block pointers and Objective-C object pointers. 2021 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 2022 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 2023 return TC_NotApplicable; 2024 2025 if (IsLValueCast) { 2026 Kind = CK_LValueBitCast; 2027 } else if (DestType->isObjCObjectPointerType()) { 2028 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 2029 } else if (DestType->isBlockPointerType()) { 2030 if (!SrcType->isBlockPointerType()) { 2031 Kind = CK_AnyPointerToBlockPointerCast; 2032 } else { 2033 Kind = CK_BitCast; 2034 } 2035 } else { 2036 Kind = CK_BitCast; 2037 } 2038 2039 // Any pointer can be cast to an Objective-C pointer type with a C-style 2040 // cast. 2041 if (CStyle && DestType->isObjCObjectPointerType()) { 2042 return TC_Success; 2043 } 2044 if (CStyle) 2045 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2046 2047 // Not casting away constness, so the only remaining check is for compatible 2048 // pointer categories. 2049 2050 if (SrcType->isFunctionPointerType()) { 2051 if (DestType->isFunctionPointerType()) { 2052 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 2053 // a pointer to a function of a different type. 2054 return TC_Success; 2055 } 2056 2057 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 2058 // an object type or vice versa is conditionally-supported. 2059 // Compilers support it in C++03 too, though, because it's necessary for 2060 // casting the return value of dlsym() and GetProcAddress(). 2061 // FIXME: Conditionally-supported behavior should be configurable in the 2062 // TargetInfo or similar. 2063 Self.Diag(OpRange.getBegin(), 2064 Self.getLangOpts().CPlusPlus11 ? 2065 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2066 << OpRange; 2067 return TC_Success; 2068 } 2069 2070 if (DestType->isFunctionPointerType()) { 2071 // See above. 2072 Self.Diag(OpRange.getBegin(), 2073 Self.getLangOpts().CPlusPlus11 ? 2074 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2075 << OpRange; 2076 return TC_Success; 2077 } 2078 2079 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 2080 // a pointer to an object of different type. 2081 // Void pointers are not specified, but supported by every compiler out there. 2082 // So we finish by allowing everything that remains - it's got to be two 2083 // object pointers. 2084 return TC_Success; 2085 } 2086 2087 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, 2088 bool ListInitialization) { 2089 // Handle placeholders. 2090 if (isPlaceholder()) { 2091 // C-style casts can resolve __unknown_any types. 2092 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2093 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2094 SrcExpr.get(), Kind, 2095 ValueKind, BasePath); 2096 return; 2097 } 2098 2099 checkNonOverloadPlaceholders(); 2100 if (SrcExpr.isInvalid()) 2101 return; 2102 } 2103 2104 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 2105 // This test is outside everything else because it's the only case where 2106 // a non-lvalue-reference target type does not lead to decay. 2107 if (DestType->isVoidType()) { 2108 Kind = CK_ToVoid; 2109 2110 if (claimPlaceholder(BuiltinType::Overload)) { 2111 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2112 SrcExpr, /* Decay Function to ptr */ false, 2113 /* Complain */ true, DestRange, DestType, 2114 diag::err_bad_cstyle_cast_overload); 2115 if (SrcExpr.isInvalid()) 2116 return; 2117 } 2118 2119 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2120 return; 2121 } 2122 2123 // If the type is dependent, we won't do any other semantic analysis now. 2124 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || 2125 SrcExpr.get()->isValueDependent()) { 2126 assert(Kind == CK_Dependent); 2127 return; 2128 } 2129 2130 if (ValueKind == VK_RValue && !DestType->isRecordType() && 2131 !isPlaceholder(BuiltinType::Overload)) { 2132 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2133 if (SrcExpr.isInvalid()) 2134 return; 2135 } 2136 2137 // AltiVec vector initialization with a single literal. 2138 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 2139 if (vecTy->getVectorKind() == VectorType::AltiVecVector 2140 && (SrcExpr.get()->getType()->isIntegerType() 2141 || SrcExpr.get()->getType()->isFloatingType())) { 2142 Kind = CK_VectorSplat; 2143 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2144 return; 2145 } 2146 2147 // C++ [expr.cast]p5: The conversions performed by 2148 // - a const_cast, 2149 // - a static_cast, 2150 // - a static_cast followed by a const_cast, 2151 // - a reinterpret_cast, or 2152 // - a reinterpret_cast followed by a const_cast, 2153 // can be performed using the cast notation of explicit type conversion. 2154 // [...] If a conversion can be interpreted in more than one of the ways 2155 // listed above, the interpretation that appears first in the list is used, 2156 // even if a cast resulting from that interpretation is ill-formed. 2157 // In plain language, this means trying a const_cast ... 2158 unsigned msg = diag::err_bad_cxx_cast_generic; 2159 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, 2160 /*CStyle*/true, msg); 2161 if (SrcExpr.isInvalid()) 2162 return; 2163 if (tcr == TC_Success) 2164 Kind = CK_NoOp; 2165 2166 Sema::CheckedConversionKind CCK 2167 = FunctionalStyle? Sema::CCK_FunctionalCast 2168 : Sema::CCK_CStyleCast; 2169 if (tcr == TC_NotApplicable) { 2170 // ... or if that is not possible, a static_cast, ignoring const, ... 2171 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 2172 msg, Kind, BasePath, ListInitialization); 2173 if (SrcExpr.isInvalid()) 2174 return; 2175 2176 if (tcr == TC_NotApplicable) { 2177 // ... and finally a reinterpret_cast, ignoring const. 2178 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 2179 OpRange, msg, Kind); 2180 if (SrcExpr.isInvalid()) 2181 return; 2182 } 2183 } 2184 2185 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success) 2186 checkObjCARCConversion(CCK); 2187 2188 if (tcr != TC_Success && msg != 0) { 2189 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2190 DeclAccessPair Found; 2191 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 2192 DestType, 2193 /*Complain*/ true, 2194 Found); 2195 if (Fn) { 2196 // If DestType is a function type (not to be confused with the function 2197 // pointer type), it will be possible to resolve the function address, 2198 // but the type cast should be considered as failure. 2199 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; 2200 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) 2201 << OE->getName() << DestType << OpRange 2202 << OE->getQualifierLoc().getSourceRange(); 2203 Self.NoteAllOverloadCandidates(SrcExpr.get()); 2204 } 2205 } else { 2206 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 2207 OpRange, SrcExpr.get(), DestType, ListInitialization); 2208 } 2209 } else if (Kind == CK_BitCast) { 2210 checkCastAlign(); 2211 } 2212 2213 // Clear out SrcExpr if there was a fatal error. 2214 if (tcr != TC_Success) 2215 SrcExpr = ExprError(); 2216 } 2217 2218 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a 2219 /// non-matching type. Such as enum function call to int, int call to 2220 /// pointer; etc. Cast to 'void' is an exception. 2221 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, 2222 QualType DestType) { 2223 if (Self.Diags.isIgnored(diag::warn_bad_function_cast, 2224 SrcExpr.get()->getExprLoc())) 2225 return; 2226 2227 if (!isa<CallExpr>(SrcExpr.get())) 2228 return; 2229 2230 QualType SrcType = SrcExpr.get()->getType(); 2231 if (DestType.getUnqualifiedType()->isVoidType()) 2232 return; 2233 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) 2234 && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) 2235 return; 2236 if (SrcType->isIntegerType() && DestType->isIntegerType() && 2237 (SrcType->isBooleanType() == DestType->isBooleanType()) && 2238 (SrcType->isEnumeralType() == DestType->isEnumeralType())) 2239 return; 2240 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) 2241 return; 2242 if (SrcType->isEnumeralType() && DestType->isEnumeralType()) 2243 return; 2244 if (SrcType->isComplexType() && DestType->isComplexType()) 2245 return; 2246 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) 2247 return; 2248 2249 Self.Diag(SrcExpr.get()->getExprLoc(), 2250 diag::warn_bad_function_cast) 2251 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2252 } 2253 2254 /// Check the semantics of a C-style cast operation, in C. 2255 void CastOperation::CheckCStyleCast() { 2256 assert(!Self.getLangOpts().CPlusPlus); 2257 2258 // C-style casts can resolve __unknown_any types. 2259 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2260 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2261 SrcExpr.get(), Kind, 2262 ValueKind, BasePath); 2263 return; 2264 } 2265 2266 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2267 // type needs to be scalar. 2268 if (DestType->isVoidType()) { 2269 // We don't necessarily do lvalue-to-rvalue conversions on this. 2270 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2271 if (SrcExpr.isInvalid()) 2272 return; 2273 2274 // Cast to void allows any expr type. 2275 Kind = CK_ToVoid; 2276 return; 2277 } 2278 2279 // Overloads are allowed with C extensions, so we need to support them. 2280 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2281 DeclAccessPair DAP; 2282 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( 2283 SrcExpr.get(), DestType, /*Complain=*/true, DAP)) 2284 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); 2285 else 2286 return; 2287 assert(SrcExpr.isUsable()); 2288 } 2289 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2290 if (SrcExpr.isInvalid()) 2291 return; 2292 QualType SrcType = SrcExpr.get()->getType(); 2293 2294 assert(!SrcType->isPlaceholderType()); 2295 2296 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to 2297 // address space B is illegal. 2298 if (Self.getLangOpts().OpenCL && DestType->isPointerType() && 2299 SrcType->isPointerType()) { 2300 const PointerType *DestPtr = DestType->getAs<PointerType>(); 2301 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) { 2302 Self.Diag(OpRange.getBegin(), 2303 diag::err_typecheck_incompatible_address_space) 2304 << SrcType << DestType << Sema::AA_Casting 2305 << SrcExpr.get()->getSourceRange(); 2306 SrcExpr = ExprError(); 2307 return; 2308 } 2309 } 2310 2311 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 2312 diag::err_typecheck_cast_to_incomplete)) { 2313 SrcExpr = ExprError(); 2314 return; 2315 } 2316 2317 if (!DestType->isScalarType() && !DestType->isVectorType()) { 2318 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 2319 2320 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 2321 // GCC struct/union extension: allow cast to self. 2322 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 2323 << DestType << SrcExpr.get()->getSourceRange(); 2324 Kind = CK_NoOp; 2325 return; 2326 } 2327 2328 // GCC's cast to union extension. 2329 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 2330 RecordDecl *RD = DestRecordTy->getDecl(); 2331 RecordDecl::field_iterator Field, FieldEnd; 2332 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 2333 Field != FieldEnd; ++Field) { 2334 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 2335 !Field->isUnnamedBitfield()) { 2336 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 2337 << SrcExpr.get()->getSourceRange(); 2338 break; 2339 } 2340 } 2341 if (Field == FieldEnd) { 2342 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2343 << SrcType << SrcExpr.get()->getSourceRange(); 2344 SrcExpr = ExprError(); 2345 return; 2346 } 2347 Kind = CK_ToUnion; 2348 return; 2349 } 2350 2351 // Reject any other conversions to non-scalar types. 2352 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 2353 << DestType << SrcExpr.get()->getSourceRange(); 2354 SrcExpr = ExprError(); 2355 return; 2356 } 2357 2358 // The type we're casting to is known to be a scalar or vector. 2359 2360 // Require the operand to be a scalar or vector. 2361 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 2362 Self.Diag(SrcExpr.get()->getExprLoc(), 2363 diag::err_typecheck_expect_scalar_operand) 2364 << SrcType << SrcExpr.get()->getSourceRange(); 2365 SrcExpr = ExprError(); 2366 return; 2367 } 2368 2369 if (DestType->isExtVectorType()) { 2370 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); 2371 return; 2372 } 2373 2374 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 2375 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 2376 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 2377 Kind = CK_VectorSplat; 2378 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2379 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 2380 SrcExpr = ExprError(); 2381 } 2382 return; 2383 } 2384 2385 if (SrcType->isVectorType()) { 2386 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 2387 SrcExpr = ExprError(); 2388 return; 2389 } 2390 2391 // The source and target types are both scalars, i.e. 2392 // - arithmetic types (fundamental, enum, and complex) 2393 // - all kinds of pointers 2394 // Note that member pointers were filtered out with C++, above. 2395 2396 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 2397 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 2398 SrcExpr = ExprError(); 2399 return; 2400 } 2401 2402 // If either type is a pointer, the other type has to be either an 2403 // integer or a pointer. 2404 if (!DestType->isArithmeticType()) { 2405 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 2406 Self.Diag(SrcExpr.get()->getExprLoc(), 2407 diag::err_cast_pointer_from_non_pointer_int) 2408 << SrcType << SrcExpr.get()->getSourceRange(); 2409 SrcExpr = ExprError(); 2410 return; 2411 } 2412 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(), 2413 DestType, Self); 2414 } else if (!SrcType->isArithmeticType()) { 2415 if (!DestType->isIntegralType(Self.Context) && 2416 DestType->isArithmeticType()) { 2417 Self.Diag(SrcExpr.get()->getLocStart(), 2418 diag::err_cast_pointer_to_non_pointer_int) 2419 << DestType << SrcExpr.get()->getSourceRange(); 2420 SrcExpr = ExprError(); 2421 return; 2422 } 2423 } 2424 2425 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) { 2426 if (DestType->isHalfType()) { 2427 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half) 2428 << DestType << SrcExpr.get()->getSourceRange(); 2429 SrcExpr = ExprError(); 2430 return; 2431 } 2432 } 2433 2434 // ARC imposes extra restrictions on casts. 2435 if (Self.getLangOpts().ObjCAutoRefCount) { 2436 checkObjCARCConversion(Sema::CCK_CStyleCast); 2437 if (SrcExpr.isInvalid()) 2438 return; 2439 2440 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) { 2441 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 2442 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 2443 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 2444 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 2445 ExprPtr->getPointeeType()->isObjCLifetimeType() && 2446 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 2447 Self.Diag(SrcExpr.get()->getLocStart(), 2448 diag::err_typecheck_incompatible_ownership) 2449 << SrcType << DestType << Sema::AA_Casting 2450 << SrcExpr.get()->getSourceRange(); 2451 return; 2452 } 2453 } 2454 } 2455 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 2456 Self.Diag(SrcExpr.get()->getLocStart(), 2457 diag::err_arc_convesion_of_weak_unavailable) 2458 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2459 SrcExpr = ExprError(); 2460 return; 2461 } 2462 } 2463 2464 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2465 DiagnoseBadFunctionCast(Self, SrcExpr, DestType); 2466 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 2467 if (SrcExpr.isInvalid()) 2468 return; 2469 2470 if (Kind == CK_BitCast) 2471 checkCastAlign(); 2472 2473 // -Wcast-qual 2474 QualType TheOffendingSrcType, TheOffendingDestType; 2475 Qualifiers CastAwayQualifiers; 2476 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() && 2477 CastsAwayConstness(Self, SrcType, DestType, true, false, 2478 &TheOffendingSrcType, &TheOffendingDestType, 2479 &CastAwayQualifiers)) { 2480 int qualifiers = -1; 2481 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { 2482 qualifiers = 0; 2483 } else if (CastAwayQualifiers.hasConst()) { 2484 qualifiers = 1; 2485 } else if (CastAwayQualifiers.hasVolatile()) { 2486 qualifiers = 2; 2487 } 2488 // This is a variant of int **x; const int **y = (const int **)x; 2489 if (qualifiers == -1) 2490 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) << 2491 SrcType << DestType; 2492 else 2493 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) << 2494 TheOffendingSrcType << TheOffendingDestType << qualifiers; 2495 } 2496 } 2497 2498 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 2499 TypeSourceInfo *CastTypeInfo, 2500 SourceLocation RPLoc, 2501 Expr *CastExpr) { 2502 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2503 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2504 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 2505 2506 if (getLangOpts().CPlusPlus) { 2507 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false, 2508 isa<InitListExpr>(CastExpr)); 2509 } else { 2510 Op.CheckCStyleCast(); 2511 } 2512 2513 if (Op.SrcExpr.isInvalid()) 2514 return ExprError(); 2515 2516 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 2517 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 2518 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 2519 } 2520 2521 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 2522 SourceLocation LPLoc, 2523 Expr *CastExpr, 2524 SourceLocation RPLoc) { 2525 assert(LPLoc.isValid() && "List-initialization shouldn't get here."); 2526 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 2527 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 2528 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 2529 2530 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false); 2531 if (Op.SrcExpr.isInvalid()) 2532 return ExprError(); 2533 2534 auto *SubExpr = Op.SrcExpr.get(); 2535 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 2536 SubExpr = BindExpr->getSubExpr(); 2537 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) 2538 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); 2539 2540 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 2541 Op.ValueKind, CastTypeInfo, Op.Kind, 2542 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc)); 2543 } 2544