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