1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for cast expressions, including 10 // 1) C-style casts like '(int) x' 11 // 2) C++ functional casts like 'int(x)' 12 // 3) C++ named casts like 'static_cast<int>(x)' 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "clang/Sema/SemaInternal.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/PartialDiagnostic.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/Lex/Preprocessor.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_Extension, ///< The cast method is appropriate and accepted as a 36 ///< language extension. 37 TC_Failed ///< The cast method is appropriate, but failed. A 38 ///< diagnostic has been emitted. 39 }; 40 41 static bool isValidCast(TryCastResult TCR) { 42 return TCR == TC_Success || TCR == TC_Extension; 43 } 44 45 enum CastType { 46 CT_Const, ///< const_cast 47 CT_Static, ///< static_cast 48 CT_Reinterpret, ///< reinterpret_cast 49 CT_Dynamic, ///< dynamic_cast 50 CT_CStyle, ///< (Type)expr 51 CT_Functional, ///< Type(expr) 52 CT_Addrspace ///< addrspace_cast 53 }; 54 55 namespace { 56 struct CastOperation { 57 CastOperation(Sema &S, QualType destType, ExprResult src) 58 : Self(S), SrcExpr(src), DestType(destType), 59 ResultType(destType.getNonLValueExprType(S.Context)), 60 ValueKind(Expr::getValueKindForType(destType)), 61 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 62 63 if (const BuiltinType *placeholder = 64 src.get()->getType()->getAsPlaceholderType()) { 65 PlaceholderKind = placeholder->getKind(); 66 } else { 67 PlaceholderKind = (BuiltinType::Kind) 0; 68 } 69 } 70 71 Sema &Self; 72 ExprResult SrcExpr; 73 QualType DestType; 74 QualType ResultType; 75 ExprValueKind ValueKind; 76 CastKind Kind; 77 BuiltinType::Kind PlaceholderKind; 78 CXXCastPath BasePath; 79 bool IsARCUnbridgedCast; 80 81 SourceRange OpRange; 82 SourceRange DestRange; 83 84 // Top-level semantics-checking routines. 85 void CheckConstCast(); 86 void CheckReinterpretCast(); 87 void CheckStaticCast(); 88 void CheckDynamicCast(); 89 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization); 90 void CheckCStyleCast(); 91 void CheckBuiltinBitCast(); 92 void CheckAddrspaceCast(); 93 94 void updatePartOfExplicitCastFlags(CastExpr *CE) { 95 // Walk down from the CE to the OrigSrcExpr, and mark all immediate 96 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE 97 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched. 98 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE) 99 ICE->setIsPartOfExplicitCast(true); 100 } 101 102 /// Complete an apparently-successful cast operation that yields 103 /// the given expression. 104 ExprResult complete(CastExpr *castExpr) { 105 // If this is an unbridged cast, wrap the result in an implicit 106 // cast that yields the unbridged-cast placeholder type. 107 if (IsARCUnbridgedCast) { 108 castExpr = ImplicitCastExpr::Create(Self.Context, 109 Self.Context.ARCUnbridgedCastTy, 110 CK_Dependent, castExpr, nullptr, 111 castExpr->getValueKind()); 112 } 113 updatePartOfExplicitCastFlags(castExpr); 114 return castExpr; 115 } 116 117 // Internal convenience methods. 118 119 /// Try to handle the given placeholder expression kind. Return 120 /// true if the source expression has the appropriate placeholder 121 /// kind. A placeholder can only be claimed once. 122 bool claimPlaceholder(BuiltinType::Kind K) { 123 if (PlaceholderKind != K) return false; 124 125 PlaceholderKind = (BuiltinType::Kind) 0; 126 return true; 127 } 128 129 bool isPlaceholder() const { 130 return PlaceholderKind != 0; 131 } 132 bool isPlaceholder(BuiltinType::Kind K) const { 133 return PlaceholderKind == K; 134 } 135 136 // Language specific cast restrictions for address spaces. 137 void checkAddressSpaceCast(QualType SrcType, QualType DestType); 138 139 void checkCastAlign() { 140 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 141 } 142 143 void checkObjCConversion(Sema::CheckedConversionKind CCK) { 144 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()); 145 146 Expr *src = SrcExpr.get(); 147 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) == 148 Sema::ACR_unbridged) 149 IsARCUnbridgedCast = true; 150 SrcExpr = src; 151 } 152 153 /// Check for and handle non-overload placeholder expressions. 154 void checkNonOverloadPlaceholders() { 155 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 156 return; 157 158 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 159 if (SrcExpr.isInvalid()) 160 return; 161 PlaceholderKind = (BuiltinType::Kind) 0; 162 } 163 }; 164 165 void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType, 166 SourceLocation OpLoc) { 167 if (const auto *PtrType = dyn_cast<PointerType>(FromType)) { 168 if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 169 if (const auto *DestType = dyn_cast<PointerType>(ToType)) { 170 if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) { 171 S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer); 172 } 173 } 174 } 175 } 176 } 177 178 struct CheckNoDerefRAII { 179 CheckNoDerefRAII(CastOperation &Op) : Op(Op) {} 180 ~CheckNoDerefRAII() { 181 if (!Op.SrcExpr.isInvalid()) 182 CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType, 183 Op.OpRange.getBegin()); 184 } 185 186 CastOperation &Op; 187 }; 188 } 189 190 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, 191 QualType DestType); 192 193 // The Try functions attempt a specific way of casting. If they succeed, they 194 // return TC_Success. If their way of casting is not appropriate for the given 195 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 196 // to emit if no other way succeeds. If their way of casting is appropriate but 197 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if 198 // they emit a specialized diagnostic. 199 // All diagnostics returned by these functions must expect the same three 200 // arguments: 201 // %0: Cast Type (a value from the CastType enumeration) 202 // %1: Source Type 203 // %2: Destination Type 204 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 205 QualType DestType, bool CStyle, 206 CastKind &Kind, 207 CXXCastPath &BasePath, 208 unsigned &msg); 209 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 210 QualType DestType, bool CStyle, 211 SourceRange OpRange, 212 unsigned &msg, 213 CastKind &Kind, 214 CXXCastPath &BasePath); 215 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 216 QualType DestType, bool CStyle, 217 SourceRange OpRange, 218 unsigned &msg, 219 CastKind &Kind, 220 CXXCastPath &BasePath); 221 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 222 CanQualType DestType, bool CStyle, 223 SourceRange OpRange, 224 QualType OrigSrcType, 225 QualType OrigDestType, unsigned &msg, 226 CastKind &Kind, 227 CXXCastPath &BasePath); 228 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 229 QualType SrcType, 230 QualType DestType,bool CStyle, 231 SourceRange OpRange, 232 unsigned &msg, 233 CastKind &Kind, 234 CXXCastPath &BasePath); 235 236 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 237 QualType DestType, 238 Sema::CheckedConversionKind CCK, 239 SourceRange OpRange, 240 unsigned &msg, CastKind &Kind, 241 bool ListInitialization); 242 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 243 QualType DestType, 244 Sema::CheckedConversionKind CCK, 245 SourceRange OpRange, 246 unsigned &msg, CastKind &Kind, 247 CXXCastPath &BasePath, 248 bool ListInitialization); 249 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 250 QualType DestType, bool CStyle, 251 unsigned &msg); 252 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 253 QualType DestType, bool CStyle, 254 SourceRange OpRange, unsigned &msg, 255 CastKind &Kind); 256 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, 257 QualType DestType, bool CStyle, 258 unsigned &msg, CastKind &Kind); 259 260 /// ActOnCXXNamedCast - Parse 261 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 262 ExprResult 263 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 264 SourceLocation LAngleBracketLoc, Declarator &D, 265 SourceLocation RAngleBracketLoc, 266 SourceLocation LParenLoc, Expr *E, 267 SourceLocation RParenLoc) { 268 269 assert(!D.isInvalidType()); 270 271 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); 272 if (D.isInvalidType()) 273 return ExprError(); 274 275 if (getLangOpts().CPlusPlus) { 276 // Check that there are no default arguments (C++ only). 277 CheckExtraCXXDefaultArguments(D); 278 } 279 280 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E, 281 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 282 SourceRange(LParenLoc, RParenLoc)); 283 } 284 285 ExprResult 286 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 287 TypeSourceInfo *DestTInfo, Expr *E, 288 SourceRange AngleBrackets, SourceRange Parens) { 289 ExprResult Ex = E; 290 QualType DestType = DestTInfo->getType(); 291 292 // If the type is dependent, we won't do the semantic analysis now. 293 bool TypeDependent = 294 DestType->isDependentType() || Ex.get()->isTypeDependent(); 295 296 CastOperation Op(*this, DestType, E); 297 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 298 Op.DestRange = AngleBrackets; 299 300 switch (Kind) { 301 default: llvm_unreachable("Unknown C++ cast!"); 302 303 case tok::kw_addrspace_cast: 304 if (!TypeDependent) { 305 Op.CheckAddrspaceCast(); 306 if (Op.SrcExpr.isInvalid()) 307 return ExprError(); 308 } 309 return Op.complete(CXXAddrspaceCastExpr::Create( 310 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 311 DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets)); 312 313 case tok::kw_const_cast: 314 if (!TypeDependent) { 315 Op.CheckConstCast(); 316 if (Op.SrcExpr.isInvalid()) 317 return ExprError(); 318 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 319 } 320 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType, 321 Op.ValueKind, Op.SrcExpr.get(), DestTInfo, 322 OpLoc, Parens.getEnd(), 323 AngleBrackets)); 324 325 case tok::kw_dynamic_cast: { 326 // dynamic_cast is not supported in C++ for OpenCL. 327 if (getLangOpts().OpenCLCPlusPlus) { 328 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 329 << "dynamic_cast"); 330 } 331 332 if (!TypeDependent) { 333 Op.CheckDynamicCast(); 334 if (Op.SrcExpr.isInvalid()) 335 return ExprError(); 336 } 337 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType, 338 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 339 &Op.BasePath, DestTInfo, 340 OpLoc, Parens.getEnd(), 341 AngleBrackets)); 342 } 343 case tok::kw_reinterpret_cast: { 344 if (!TypeDependent) { 345 Op.CheckReinterpretCast(); 346 if (Op.SrcExpr.isInvalid()) 347 return ExprError(); 348 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 349 } 350 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 351 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 352 nullptr, DestTInfo, OpLoc, 353 Parens.getEnd(), 354 AngleBrackets)); 355 } 356 case tok::kw_static_cast: { 357 if (!TypeDependent) { 358 Op.CheckStaticCast(); 359 if (Op.SrcExpr.isInvalid()) 360 return ExprError(); 361 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E); 362 } 363 364 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType, 365 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 366 &Op.BasePath, DestTInfo, 367 OpLoc, Parens.getEnd(), 368 AngleBrackets)); 369 } 370 } 371 } 372 373 ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D, 374 ExprResult Operand, 375 SourceLocation RParenLoc) { 376 assert(!D.isInvalidType()); 377 378 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType()); 379 if (D.isInvalidType()) 380 return ExprError(); 381 382 return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc); 383 } 384 385 ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc, 386 TypeSourceInfo *TSI, Expr *Operand, 387 SourceLocation RParenLoc) { 388 CastOperation Op(*this, TSI->getType(), Operand); 389 Op.OpRange = SourceRange(KWLoc, RParenLoc); 390 TypeLoc TL = TSI->getTypeLoc(); 391 Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); 392 393 if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) { 394 Op.CheckBuiltinBitCast(); 395 if (Op.SrcExpr.isInvalid()) 396 return ExprError(); 397 } 398 399 BuiltinBitCastExpr *BCE = 400 new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind, 401 Op.SrcExpr.get(), TSI, KWLoc, RParenLoc); 402 return Op.complete(BCE); 403 } 404 405 /// Try to diagnose a failed overloaded cast. Returns true if 406 /// diagnostics were emitted. 407 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 408 SourceRange range, Expr *src, 409 QualType destType, 410 bool listInitialization) { 411 switch (CT) { 412 // These cast kinds don't consider user-defined conversions. 413 case CT_Const: 414 case CT_Reinterpret: 415 case CT_Dynamic: 416 case CT_Addrspace: 417 return false; 418 419 // These do. 420 case CT_Static: 421 case CT_CStyle: 422 case CT_Functional: 423 break; 424 } 425 426 QualType srcType = src->getType(); 427 if (!destType->isRecordType() && !srcType->isRecordType()) 428 return false; 429 430 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 431 InitializationKind initKind 432 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 433 range, listInitialization) 434 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range, 435 listInitialization) 436 : InitializationKind::CreateCast(/*type range?*/ range); 437 InitializationSequence sequence(S, entity, initKind, src); 438 439 assert(sequence.Failed() && "initialization succeeded on second try?"); 440 switch (sequence.getFailureKind()) { 441 default: return false; 442 443 case InitializationSequence::FK_ConstructorOverloadFailed: 444 case InitializationSequence::FK_UserConversionOverloadFailed: 445 break; 446 } 447 448 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 449 450 unsigned msg = 0; 451 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 452 453 switch (sequence.getFailedOverloadResult()) { 454 case OR_Success: llvm_unreachable("successful failed overload"); 455 case OR_No_Viable_Function: 456 if (candidates.empty()) 457 msg = diag::err_ovl_no_conversion_in_cast; 458 else 459 msg = diag::err_ovl_no_viable_conversion_in_cast; 460 howManyCandidates = OCD_AllCandidates; 461 break; 462 463 case OR_Ambiguous: 464 msg = diag::err_ovl_ambiguous_conversion_in_cast; 465 howManyCandidates = OCD_AmbiguousCandidates; 466 break; 467 468 case OR_Deleted: 469 msg = diag::err_ovl_deleted_conversion_in_cast; 470 howManyCandidates = OCD_ViableCandidates; 471 break; 472 } 473 474 candidates.NoteCandidates( 475 PartialDiagnosticAt(range.getBegin(), 476 S.PDiag(msg) << CT << srcType << destType << range 477 << src->getSourceRange()), 478 S, howManyCandidates, src); 479 480 return true; 481 } 482 483 /// Diagnose a failed cast. 484 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 485 SourceRange opRange, Expr *src, QualType destType, 486 bool listInitialization) { 487 if (msg == diag::err_bad_cxx_cast_generic && 488 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType, 489 listInitialization)) 490 return; 491 492 S.Diag(opRange.getBegin(), msg) << castType 493 << src->getType() << destType << opRange << src->getSourceRange(); 494 495 // Detect if both types are (ptr to) class, and note any incompleteness. 496 int DifferentPtrness = 0; 497 QualType From = destType; 498 if (auto Ptr = From->getAs<PointerType>()) { 499 From = Ptr->getPointeeType(); 500 DifferentPtrness++; 501 } 502 QualType To = src->getType(); 503 if (auto Ptr = To->getAs<PointerType>()) { 504 To = Ptr->getPointeeType(); 505 DifferentPtrness--; 506 } 507 if (!DifferentPtrness) { 508 auto RecFrom = From->getAs<RecordType>(); 509 auto RecTo = To->getAs<RecordType>(); 510 if (RecFrom && RecTo) { 511 auto DeclFrom = RecFrom->getAsCXXRecordDecl(); 512 if (!DeclFrom->isCompleteDefinition()) 513 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom; 514 auto DeclTo = RecTo->getAsCXXRecordDecl(); 515 if (!DeclTo->isCompleteDefinition()) 516 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo; 517 } 518 } 519 } 520 521 namespace { 522 /// The kind of unwrapping we did when determining whether a conversion casts 523 /// away constness. 524 enum CastAwayConstnessKind { 525 /// The conversion does not cast away constness. 526 CACK_None = 0, 527 /// We unwrapped similar types. 528 CACK_Similar = 1, 529 /// We unwrapped dissimilar types with similar representations (eg, a pointer 530 /// versus an Objective-C object pointer). 531 CACK_SimilarKind = 2, 532 /// We unwrapped representationally-unrelated types, such as a pointer versus 533 /// a pointer-to-member. 534 CACK_Incoherent = 3, 535 }; 536 } 537 538 /// Unwrap one level of types for CastsAwayConstness. 539 /// 540 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from 541 /// both types, provided that they're both pointer-like or array-like. Unlike 542 /// the Sema function, doesn't care if the unwrapped pieces are related. 543 /// 544 /// This function may remove additional levels as necessary for correctness: 545 /// the resulting T1 is unwrapped sufficiently that it is never an array type, 546 /// so that its qualifiers can be directly compared to those of T2 (which will 547 /// have the combined set of qualifiers from all indermediate levels of T2), 548 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers 549 /// with those from T2. 550 static CastAwayConstnessKind 551 unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) { 552 enum { None, Ptr, MemPtr, BlockPtr, Array }; 553 auto Classify = [](QualType T) { 554 if (T->isAnyPointerType()) return Ptr; 555 if (T->isMemberPointerType()) return MemPtr; 556 if (T->isBlockPointerType()) return BlockPtr; 557 // We somewhat-arbitrarily don't look through VLA types here. This is at 558 // least consistent with the behavior of UnwrapSimilarTypes. 559 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array; 560 return None; 561 }; 562 563 auto Unwrap = [&](QualType T) { 564 if (auto *AT = Context.getAsArrayType(T)) 565 return AT->getElementType(); 566 return T->getPointeeType(); 567 }; 568 569 CastAwayConstnessKind Kind; 570 571 if (T2->isReferenceType()) { 572 // Special case: if the destination type is a reference type, unwrap it as 573 // the first level. (The source will have been an lvalue expression in this 574 // case, so there is no corresponding "reference to" in T1 to remove.) This 575 // simulates removing a "pointer to" from both sides. 576 T2 = T2->getPointeeType(); 577 Kind = CastAwayConstnessKind::CACK_Similar; 578 } else if (Context.UnwrapSimilarTypes(T1, T2)) { 579 Kind = CastAwayConstnessKind::CACK_Similar; 580 } else { 581 // Try unwrapping mismatching levels. 582 int T1Class = Classify(T1); 583 if (T1Class == None) 584 return CastAwayConstnessKind::CACK_None; 585 586 int T2Class = Classify(T2); 587 if (T2Class == None) 588 return CastAwayConstnessKind::CACK_None; 589 590 T1 = Unwrap(T1); 591 T2 = Unwrap(T2); 592 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind 593 : CastAwayConstnessKind::CACK_Incoherent; 594 } 595 596 // We've unwrapped at least one level. If the resulting T1 is a (possibly 597 // multidimensional) array type, any qualifier on any matching layer of 598 // T2 is considered to correspond to T1. Decompose down to the element 599 // type of T1 so that we can compare properly. 600 while (true) { 601 Context.UnwrapSimilarArrayTypes(T1, T2); 602 603 if (Classify(T1) != Array) 604 break; 605 606 auto T2Class = Classify(T2); 607 if (T2Class == None) 608 break; 609 610 if (T2Class != Array) 611 Kind = CastAwayConstnessKind::CACK_Incoherent; 612 else if (Kind != CastAwayConstnessKind::CACK_Incoherent) 613 Kind = CastAwayConstnessKind::CACK_SimilarKind; 614 615 T1 = Unwrap(T1); 616 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers()); 617 } 618 619 return Kind; 620 } 621 622 /// Check if the pointer conversion from SrcType to DestType casts away 623 /// constness as defined in C++ [expr.const.cast]. This is used by the cast 624 /// checkers. Both arguments must denote pointer (possibly to member) types. 625 /// 626 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 627 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 628 static CastAwayConstnessKind 629 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 630 bool CheckCVR, bool CheckObjCLifetime, 631 QualType *TheOffendingSrcType = nullptr, 632 QualType *TheOffendingDestType = nullptr, 633 Qualifiers *CastAwayQualifiers = nullptr) { 634 // If the only checking we care about is for Objective-C lifetime qualifiers, 635 // and we're not in ObjC mode, there's nothing to check. 636 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC) 637 return CastAwayConstnessKind::CACK_None; 638 639 if (!DestType->isReferenceType()) { 640 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 641 SrcType->isBlockPointerType()) && 642 "Source type is not pointer or pointer to member."); 643 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 644 DestType->isBlockPointerType()) && 645 "Destination type is not pointer or pointer to member."); 646 } 647 648 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 649 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 650 651 // Find the qualifiers. We only care about cvr-qualifiers for the 652 // purpose of this check, because other qualifiers (address spaces, 653 // Objective-C GC, etc.) are part of the type's identity. 654 QualType PrevUnwrappedSrcType = UnwrappedSrcType; 655 QualType PrevUnwrappedDestType = UnwrappedDestType; 656 auto WorstKind = CastAwayConstnessKind::CACK_Similar; 657 bool AllConstSoFar = true; 658 while (auto Kind = unwrapCastAwayConstnessLevel( 659 Self.Context, UnwrappedSrcType, UnwrappedDestType)) { 660 // Track the worst kind of unwrap we needed to do before we found a 661 // problem. 662 if (Kind > WorstKind) 663 WorstKind = Kind; 664 665 // Determine the relevant qualifiers at this level. 666 Qualifiers SrcQuals, DestQuals; 667 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 668 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 669 670 // We do not meaningfully track object const-ness of Objective-C object 671 // types. Remove const from the source type if either the source or 672 // the destination is an Objective-C object type. 673 if (UnwrappedSrcType->isObjCObjectType() || 674 UnwrappedDestType->isObjCObjectType()) 675 SrcQuals.removeConst(); 676 677 if (CheckCVR) { 678 Qualifiers SrcCvrQuals = 679 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()); 680 Qualifiers DestCvrQuals = 681 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()); 682 683 if (SrcCvrQuals != DestCvrQuals) { 684 if (CastAwayQualifiers) 685 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals; 686 687 // If we removed a cvr-qualifier, this is casting away 'constness'. 688 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) { 689 if (TheOffendingSrcType) 690 *TheOffendingSrcType = PrevUnwrappedSrcType; 691 if (TheOffendingDestType) 692 *TheOffendingDestType = PrevUnwrappedDestType; 693 return WorstKind; 694 } 695 696 // If any prior level was not 'const', this is also casting away 697 // 'constness'. We noted the outermost type missing a 'const' already. 698 if (!AllConstSoFar) 699 return WorstKind; 700 } 701 } 702 703 if (CheckObjCLifetime && 704 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 705 return WorstKind; 706 707 // If we found our first non-const-qualified type, this may be the place 708 // where things start to go wrong. 709 if (AllConstSoFar && !DestQuals.hasConst()) { 710 AllConstSoFar = false; 711 if (TheOffendingSrcType) 712 *TheOffendingSrcType = PrevUnwrappedSrcType; 713 if (TheOffendingDestType) 714 *TheOffendingDestType = PrevUnwrappedDestType; 715 } 716 717 PrevUnwrappedSrcType = UnwrappedSrcType; 718 PrevUnwrappedDestType = UnwrappedDestType; 719 } 720 721 return CastAwayConstnessKind::CACK_None; 722 } 723 724 static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK, 725 unsigned &DiagID) { 726 switch (CACK) { 727 case CastAwayConstnessKind::CACK_None: 728 llvm_unreachable("did not cast away constness"); 729 730 case CastAwayConstnessKind::CACK_Similar: 731 // FIXME: Accept these as an extension too? 732 case CastAwayConstnessKind::CACK_SimilarKind: 733 DiagID = diag::err_bad_cxx_cast_qualifiers_away; 734 return TC_Failed; 735 736 case CastAwayConstnessKind::CACK_Incoherent: 737 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent; 738 return TC_Extension; 739 } 740 741 llvm_unreachable("unexpected cast away constness kind"); 742 } 743 744 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 745 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 746 /// checked downcasts in class hierarchies. 747 void CastOperation::CheckDynamicCast() { 748 CheckNoDerefRAII NoderefCheck(*this); 749 750 if (ValueKind == VK_RValue) 751 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 752 else if (isPlaceholder()) 753 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 754 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 755 return; 756 757 QualType OrigSrcType = SrcExpr.get()->getType(); 758 QualType DestType = Self.Context.getCanonicalType(this->DestType); 759 760 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 761 // or "pointer to cv void". 762 763 QualType DestPointee; 764 const PointerType *DestPointer = DestType->getAs<PointerType>(); 765 const ReferenceType *DestReference = nullptr; 766 if (DestPointer) { 767 DestPointee = DestPointer->getPointeeType(); 768 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 769 DestPointee = DestReference->getPointeeType(); 770 } else { 771 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 772 << this->DestType << DestRange; 773 SrcExpr = ExprError(); 774 return; 775 } 776 777 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 778 if (DestPointee->isVoidType()) { 779 assert(DestPointer && "Reference to void is not possible"); 780 } else if (DestRecord) { 781 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 782 diag::err_bad_cast_incomplete, 783 DestRange)) { 784 SrcExpr = ExprError(); 785 return; 786 } 787 } else { 788 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 789 << DestPointee.getUnqualifiedType() << DestRange; 790 SrcExpr = ExprError(); 791 return; 792 } 793 794 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 795 // complete class type, [...]. If T is an lvalue reference type, v shall be 796 // an lvalue of a complete class type, [...]. If T is an rvalue reference 797 // type, v shall be an expression having a complete class type, [...] 798 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 799 QualType SrcPointee; 800 if (DestPointer) { 801 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 802 SrcPointee = SrcPointer->getPointeeType(); 803 } else { 804 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 805 << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange(); 806 SrcExpr = ExprError(); 807 return; 808 } 809 } else if (DestReference->isLValueReferenceType()) { 810 if (!SrcExpr.get()->isLValue()) { 811 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 812 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 813 } 814 SrcPointee = SrcType; 815 } else { 816 // If we're dynamic_casting from a prvalue to an rvalue reference, we need 817 // to materialize the prvalue before we bind the reference to it. 818 if (SrcExpr.get()->isRValue()) 819 SrcExpr = Self.CreateMaterializeTemporaryExpr( 820 SrcType, SrcExpr.get(), /*IsLValueReference*/ false); 821 SrcPointee = SrcType; 822 } 823 824 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 825 if (SrcRecord) { 826 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 827 diag::err_bad_cast_incomplete, 828 SrcExpr.get())) { 829 SrcExpr = ExprError(); 830 return; 831 } 832 } else { 833 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 834 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 835 SrcExpr = ExprError(); 836 return; 837 } 838 839 assert((DestPointer || DestReference) && 840 "Bad destination non-ptr/ref slipped through."); 841 assert((DestRecord || DestPointee->isVoidType()) && 842 "Bad destination pointee slipped through."); 843 assert(SrcRecord && "Bad source pointee slipped through."); 844 845 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 846 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 847 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 848 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 849 SrcExpr = ExprError(); 850 return; 851 } 852 853 // C++ 5.2.7p3: If the type of v is the same as the required result type, 854 // [except for cv]. 855 if (DestRecord == SrcRecord) { 856 Kind = CK_NoOp; 857 return; 858 } 859 860 // C++ 5.2.7p5 861 // Upcasts are resolved statically. 862 if (DestRecord && 863 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) { 864 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 865 OpRange.getBegin(), OpRange, 866 &BasePath)) { 867 SrcExpr = ExprError(); 868 return; 869 } 870 871 Kind = CK_DerivedToBase; 872 return; 873 } 874 875 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 876 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 877 assert(SrcDecl && "Definition missing"); 878 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 879 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 880 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 881 SrcExpr = ExprError(); 882 } 883 884 // dynamic_cast is not available with -fno-rtti. 885 // As an exception, dynamic_cast to void* is available because it doesn't 886 // use RTTI. 887 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) { 888 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti); 889 SrcExpr = ExprError(); 890 return; 891 } 892 893 // Done. Everything else is run-time checks. 894 Kind = CK_Dynamic; 895 } 896 897 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 898 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code 899 /// like this: 900 /// const char *str = "literal"; 901 /// legacy_function(const_cast\<char*\>(str)); 902 void CastOperation::CheckConstCast() { 903 CheckNoDerefRAII NoderefCheck(*this); 904 905 if (ValueKind == VK_RValue) 906 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 907 else if (isPlaceholder()) 908 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get()); 909 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 910 return; 911 912 unsigned msg = diag::err_bad_cxx_cast_generic; 913 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg); 914 if (TCR != TC_Success && msg != 0) { 915 Self.Diag(OpRange.getBegin(), msg) << CT_Const 916 << SrcExpr.get()->getType() << DestType << OpRange; 917 } 918 if (!isValidCast(TCR)) 919 SrcExpr = ExprError(); 920 } 921 922 void CastOperation::CheckAddrspaceCast() { 923 unsigned msg = diag::err_bad_cxx_cast_generic; 924 auto TCR = 925 TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind); 926 if (TCR != TC_Success && msg != 0) { 927 Self.Diag(OpRange.getBegin(), msg) 928 << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange; 929 } 930 if (!isValidCast(TCR)) 931 SrcExpr = ExprError(); 932 } 933 934 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast 935 /// or downcast between respective pointers or references. 936 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, 937 QualType DestType, 938 SourceRange OpRange) { 939 QualType SrcType = SrcExpr->getType(); 940 // When casting from pointer or reference, get pointee type; use original 941 // type otherwise. 942 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl(); 943 const CXXRecordDecl *SrcRD = 944 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl(); 945 946 // Examining subobjects for records is only possible if the complete and 947 // valid definition is available. Also, template instantiation is not 948 // allowed here. 949 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl()) 950 return; 951 952 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl(); 953 954 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl()) 955 return; 956 957 enum { 958 ReinterpretUpcast, 959 ReinterpretDowncast 960 } ReinterpretKind; 961 962 CXXBasePaths BasePaths; 963 964 if (SrcRD->isDerivedFrom(DestRD, BasePaths)) 965 ReinterpretKind = ReinterpretUpcast; 966 else if (DestRD->isDerivedFrom(SrcRD, BasePaths)) 967 ReinterpretKind = ReinterpretDowncast; 968 else 969 return; 970 971 bool VirtualBase = true; 972 bool NonZeroOffset = false; 973 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(), 974 E = BasePaths.end(); 975 I != E; ++I) { 976 const CXXBasePath &Path = *I; 977 CharUnits Offset = CharUnits::Zero(); 978 bool IsVirtual = false; 979 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end(); 980 IElem != EElem; ++IElem) { 981 IsVirtual = IElem->Base->isVirtual(); 982 if (IsVirtual) 983 break; 984 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl(); 985 assert(BaseRD && "Base type should be a valid unqualified class type"); 986 // Don't check if any base has invalid declaration or has no definition 987 // since it has no layout info. 988 const CXXRecordDecl *Class = IElem->Class, 989 *ClassDefinition = Class->getDefinition(); 990 if (Class->isInvalidDecl() || !ClassDefinition || 991 !ClassDefinition->isCompleteDefinition()) 992 return; 993 994 const ASTRecordLayout &DerivedLayout = 995 Self.Context.getASTRecordLayout(Class); 996 Offset += DerivedLayout.getBaseClassOffset(BaseRD); 997 } 998 if (!IsVirtual) { 999 // Don't warn if any path is a non-virtually derived base at offset zero. 1000 if (Offset.isZero()) 1001 return; 1002 // Offset makes sense only for non-virtual bases. 1003 else 1004 NonZeroOffset = true; 1005 } 1006 VirtualBase = VirtualBase && IsVirtual; 1007 } 1008 1009 (void) NonZeroOffset; // Silence set but not used warning. 1010 assert((VirtualBase || NonZeroOffset) && 1011 "Should have returned if has non-virtual base with zero offset"); 1012 1013 QualType BaseType = 1014 ReinterpretKind == ReinterpretUpcast? DestType : SrcType; 1015 QualType DerivedType = 1016 ReinterpretKind == ReinterpretUpcast? SrcType : DestType; 1017 1018 SourceLocation BeginLoc = OpRange.getBegin(); 1019 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static) 1020 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind) 1021 << OpRange; 1022 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static) 1023 << int(ReinterpretKind) 1024 << FixItHint::CreateReplacement(BeginLoc, "static_cast"); 1025 } 1026 1027 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 1028 /// valid. 1029 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 1030 /// like this: 1031 /// char *bytes = reinterpret_cast\<char*\>(int_ptr); 1032 void CastOperation::CheckReinterpretCast() { 1033 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) 1034 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 1035 else 1036 checkNonOverloadPlaceholders(); 1037 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 1038 return; 1039 1040 unsigned msg = diag::err_bad_cxx_cast_generic; 1041 TryCastResult tcr = 1042 TryReinterpretCast(Self, SrcExpr, DestType, 1043 /*CStyle*/false, OpRange, msg, Kind); 1044 if (tcr != TC_Success && msg != 0) { 1045 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 1046 return; 1047 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1048 //FIXME: &f<int>; is overloaded and resolvable 1049 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 1050 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 1051 << DestType << OpRange; 1052 Self.NoteAllOverloadCandidates(SrcExpr.get()); 1053 1054 } else { 1055 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), 1056 DestType, /*listInitialization=*/false); 1057 } 1058 } 1059 1060 if (isValidCast(tcr)) { 1061 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 1062 checkObjCConversion(Sema::CCK_OtherCast); 1063 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange); 1064 } else { 1065 SrcExpr = ExprError(); 1066 } 1067 } 1068 1069 1070 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 1071 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 1072 /// implicit conversions explicit and getting rid of data loss warnings. 1073 void CastOperation::CheckStaticCast() { 1074 CheckNoDerefRAII NoderefCheck(*this); 1075 1076 if (isPlaceholder()) { 1077 checkNonOverloadPlaceholders(); 1078 if (SrcExpr.isInvalid()) 1079 return; 1080 } 1081 1082 // This test is outside everything else because it's the only case where 1083 // a non-lvalue-reference target type does not lead to decay. 1084 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1085 if (DestType->isVoidType()) { 1086 Kind = CK_ToVoid; 1087 1088 if (claimPlaceholder(BuiltinType::Overload)) { 1089 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 1090 false, // Decay Function to ptr 1091 true, // Complain 1092 OpRange, DestType, diag::err_bad_static_cast_overload); 1093 if (SrcExpr.isInvalid()) 1094 return; 1095 } 1096 1097 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 1098 return; 1099 } 1100 1101 if (ValueKind == VK_RValue && !DestType->isRecordType() && 1102 !isPlaceholder(BuiltinType::Overload)) { 1103 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 1104 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 1105 return; 1106 } 1107 1108 unsigned msg = diag::err_bad_cxx_cast_generic; 1109 TryCastResult tcr 1110 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 1111 Kind, BasePath, /*ListInitialization=*/false); 1112 if (tcr != TC_Success && msg != 0) { 1113 if (SrcExpr.isInvalid()) 1114 return; 1115 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1116 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 1117 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 1118 << oe->getName() << DestType << OpRange 1119 << oe->getQualifierLoc().getSourceRange(); 1120 Self.NoteAllOverloadCandidates(SrcExpr.get()); 1121 } else { 1122 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType, 1123 /*listInitialization=*/false); 1124 } 1125 } 1126 1127 if (isValidCast(tcr)) { 1128 if (Kind == CK_BitCast) 1129 checkCastAlign(); 1130 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 1131 checkObjCConversion(Sema::CCK_OtherCast); 1132 } else { 1133 SrcExpr = ExprError(); 1134 } 1135 } 1136 1137 static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) { 1138 auto *SrcPtrType = SrcType->getAs<PointerType>(); 1139 if (!SrcPtrType) 1140 return false; 1141 auto *DestPtrType = DestType->getAs<PointerType>(); 1142 if (!DestPtrType) 1143 return false; 1144 return SrcPtrType->getPointeeType().getAddressSpace() != 1145 DestPtrType->getPointeeType().getAddressSpace(); 1146 } 1147 1148 /// TryStaticCast - Check if a static cast can be performed, and do so if 1149 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting 1150 /// and casting away constness. 1151 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 1152 QualType DestType, 1153 Sema::CheckedConversionKind CCK, 1154 SourceRange OpRange, unsigned &msg, 1155 CastKind &Kind, CXXCastPath &BasePath, 1156 bool ListInitialization) { 1157 // Determine whether we have the semantics of a C-style cast. 1158 bool CStyle 1159 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1160 1161 // The order the tests is not entirely arbitrary. There is one conversion 1162 // that can be handled in two different ways. Given: 1163 // struct A {}; 1164 // struct B : public A { 1165 // B(); B(const A&); 1166 // }; 1167 // const A &a = B(); 1168 // the cast static_cast<const B&>(a) could be seen as either a static 1169 // reference downcast, or an explicit invocation of the user-defined 1170 // conversion using B's conversion constructor. 1171 // DR 427 specifies that the downcast is to be applied here. 1172 1173 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 1174 // Done outside this function. 1175 1176 TryCastResult tcr; 1177 1178 // C++ 5.2.9p5, reference downcast. 1179 // See the function for details. 1180 // DR 427 specifies that this is to be applied before paragraph 2. 1181 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, 1182 OpRange, msg, Kind, BasePath); 1183 if (tcr != TC_NotApplicable) 1184 return tcr; 1185 1186 // C++11 [expr.static.cast]p3: 1187 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 1188 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1189 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 1190 BasePath, msg); 1191 if (tcr != TC_NotApplicable) 1192 return tcr; 1193 1194 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 1195 // [...] if the declaration "T t(e);" is well-formed, [...]. 1196 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 1197 Kind, ListInitialization); 1198 if (SrcExpr.isInvalid()) 1199 return TC_Failed; 1200 if (tcr != TC_NotApplicable) 1201 return tcr; 1202 1203 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 1204 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 1205 // conversions, subject to further restrictions. 1206 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 1207 // of qualification conversions impossible. 1208 // In the CStyle case, the earlier attempt to const_cast should have taken 1209 // care of reverse qualification conversions. 1210 1211 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 1212 1213 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 1214 // converted to an integral type. [...] A value of a scoped enumeration type 1215 // can also be explicitly converted to a floating-point type [...]. 1216 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 1217 if (Enum->getDecl()->isScoped()) { 1218 if (DestType->isBooleanType()) { 1219 Kind = CK_IntegralToBoolean; 1220 return TC_Success; 1221 } else if (DestType->isIntegralType(Self.Context)) { 1222 Kind = CK_IntegralCast; 1223 return TC_Success; 1224 } else if (DestType->isRealFloatingType()) { 1225 Kind = CK_IntegralToFloating; 1226 return TC_Success; 1227 } 1228 } 1229 } 1230 1231 // Reverse integral promotion/conversion. All such conversions are themselves 1232 // again integral promotions or conversions and are thus already handled by 1233 // p2 (TryDirectInitialization above). 1234 // (Note: any data loss warnings should be suppressed.) 1235 // The exception is the reverse of enum->integer, i.e. integer->enum (and 1236 // enum->enum). See also C++ 5.2.9p7. 1237 // The same goes for reverse floating point promotion/conversion and 1238 // floating-integral conversions. Again, only floating->enum is relevant. 1239 if (DestType->isEnumeralType()) { 1240 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1241 diag::err_bad_cast_incomplete)) { 1242 SrcExpr = ExprError(); 1243 return TC_Failed; 1244 } 1245 if (SrcType->isIntegralOrEnumerationType()) { 1246 // [expr.static.cast]p10 If the enumeration type has a fixed underlying 1247 // type, the value is first converted to that type by integral conversion 1248 const EnumType *Enum = DestType->getAs<EnumType>(); 1249 Kind = Enum->getDecl()->isFixed() && 1250 Enum->getDecl()->getIntegerType()->isBooleanType() 1251 ? CK_IntegralToBoolean 1252 : CK_IntegralCast; 1253 return TC_Success; 1254 } else if (SrcType->isRealFloatingType()) { 1255 Kind = CK_FloatingToIntegral; 1256 return TC_Success; 1257 } 1258 } 1259 1260 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 1261 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 1262 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 1263 Kind, BasePath); 1264 if (tcr != TC_NotApplicable) 1265 return tcr; 1266 1267 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 1268 // conversion. C++ 5.2.9p9 has additional information. 1269 // DR54's access restrictions apply here also. 1270 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 1271 OpRange, msg, Kind, BasePath); 1272 if (tcr != TC_NotApplicable) 1273 return tcr; 1274 1275 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 1276 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 1277 // just the usual constness stuff. 1278 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 1279 QualType SrcPointee = SrcPointer->getPointeeType(); 1280 if (SrcPointee->isVoidType()) { 1281 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 1282 QualType DestPointee = DestPointer->getPointeeType(); 1283 if (DestPointee->isIncompleteOrObjectType()) { 1284 // This is definitely the intended conversion, but it might fail due 1285 // to a qualifier violation. Note that we permit Objective-C lifetime 1286 // and GC qualifier mismatches here. 1287 if (!CStyle) { 1288 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 1289 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 1290 DestPointeeQuals.removeObjCGCAttr(); 1291 DestPointeeQuals.removeObjCLifetime(); 1292 SrcPointeeQuals.removeObjCGCAttr(); 1293 SrcPointeeQuals.removeObjCLifetime(); 1294 if (DestPointeeQuals != SrcPointeeQuals && 1295 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 1296 msg = diag::err_bad_cxx_cast_qualifiers_away; 1297 return TC_Failed; 1298 } 1299 } 1300 Kind = IsAddressSpaceConversion(SrcType, DestType) 1301 ? CK_AddressSpaceConversion 1302 : CK_BitCast; 1303 return TC_Success; 1304 } 1305 1306 // Microsoft permits static_cast from 'pointer-to-void' to 1307 // 'pointer-to-function'. 1308 if (!CStyle && Self.getLangOpts().MSVCCompat && 1309 DestPointee->isFunctionType()) { 1310 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange; 1311 Kind = CK_BitCast; 1312 return TC_Success; 1313 } 1314 } 1315 else if (DestType->isObjCObjectPointerType()) { 1316 // allow both c-style cast and static_cast of objective-c pointers as 1317 // they are pervasive. 1318 Kind = CK_CPointerToObjCPointerCast; 1319 return TC_Success; 1320 } 1321 else if (CStyle && DestType->isBlockPointerType()) { 1322 // allow c-style cast of void * to block pointers. 1323 Kind = CK_AnyPointerToBlockPointerCast; 1324 return TC_Success; 1325 } 1326 } 1327 } 1328 // Allow arbitrary objective-c pointer conversion with static casts. 1329 if (SrcType->isObjCObjectPointerType() && 1330 DestType->isObjCObjectPointerType()) { 1331 Kind = CK_BitCast; 1332 return TC_Success; 1333 } 1334 // Allow ns-pointer to cf-pointer conversion in either direction 1335 // with static casts. 1336 if (!CStyle && 1337 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind)) 1338 return TC_Success; 1339 1340 // See if it looks like the user is trying to convert between 1341 // related record types, and select a better diagnostic if so. 1342 if (auto SrcPointer = SrcType->getAs<PointerType>()) 1343 if (auto DestPointer = DestType->getAs<PointerType>()) 1344 if (SrcPointer->getPointeeType()->getAs<RecordType>() && 1345 DestPointer->getPointeeType()->getAs<RecordType>()) 1346 msg = diag::err_bad_cxx_cast_unrelated_class; 1347 1348 // We tried everything. Everything! Nothing works! :-( 1349 return TC_NotApplicable; 1350 } 1351 1352 /// Tests whether a conversion according to N2844 is valid. 1353 TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 1354 QualType DestType, bool CStyle, 1355 CastKind &Kind, CXXCastPath &BasePath, 1356 unsigned &msg) { 1357 // C++11 [expr.static.cast]p3: 1358 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 1359 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 1360 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 1361 if (!R) 1362 return TC_NotApplicable; 1363 1364 if (!SrcExpr->isGLValue()) 1365 return TC_NotApplicable; 1366 1367 // Because we try the reference downcast before this function, from now on 1368 // this is the only cast possibility, so we issue an error if we fail now. 1369 // FIXME: Should allow casting away constness if CStyle. 1370 QualType FromType = SrcExpr->getType(); 1371 QualType ToType = R->getPointeeType(); 1372 if (CStyle) { 1373 FromType = FromType.getUnqualifiedType(); 1374 ToType = ToType.getUnqualifiedType(); 1375 } 1376 1377 Sema::ReferenceConversions RefConv; 1378 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship( 1379 SrcExpr->getBeginLoc(), ToType, FromType, &RefConv); 1380 if (RefResult != Sema::Ref_Compatible) { 1381 if (CStyle || RefResult == Sema::Ref_Incompatible) 1382 return TC_NotApplicable; 1383 // Diagnose types which are reference-related but not compatible here since 1384 // we can provide better diagnostics. In these cases forwarding to 1385 // [expr.static.cast]p4 should never result in a well-formed cast. 1386 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast 1387 : diag::err_bad_rvalue_to_rvalue_cast; 1388 return TC_Failed; 1389 } 1390 1391 if (RefConv & Sema::ReferenceConversions::DerivedToBase) { 1392 Kind = CK_DerivedToBase; 1393 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1394 /*DetectVirtual=*/true); 1395 if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(), 1396 R->getPointeeType(), Paths)) 1397 return TC_NotApplicable; 1398 1399 Self.BuildBasePathArray(Paths, BasePath); 1400 } else 1401 Kind = CK_NoOp; 1402 1403 return TC_Success; 1404 } 1405 1406 /// Tests whether a conversion according to C++ 5.2.9p5 is valid. 1407 TryCastResult 1408 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 1409 bool CStyle, SourceRange OpRange, 1410 unsigned &msg, CastKind &Kind, 1411 CXXCastPath &BasePath) { 1412 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 1413 // cast to type "reference to cv2 D", where D is a class derived from B, 1414 // if a valid standard conversion from "pointer to D" to "pointer to B" 1415 // exists, cv2 >= cv1, and B is not a virtual base class of D. 1416 // In addition, DR54 clarifies that the base must be accessible in the 1417 // current context. Although the wording of DR54 only applies to the pointer 1418 // variant of this rule, the intent is clearly for it to apply to the this 1419 // conversion as well. 1420 1421 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 1422 if (!DestReference) { 1423 return TC_NotApplicable; 1424 } 1425 bool RValueRef = DestReference->isRValueReferenceType(); 1426 if (!RValueRef && !SrcExpr->isLValue()) { 1427 // We know the left side is an lvalue reference, so we can suggest a reason. 1428 msg = diag::err_bad_cxx_cast_rvalue; 1429 return TC_NotApplicable; 1430 } 1431 1432 QualType DestPointee = DestReference->getPointeeType(); 1433 1434 // FIXME: If the source is a prvalue, we should issue a warning (because the 1435 // cast always has undefined behavior), and for AST consistency, we should 1436 // materialize a temporary. 1437 return TryStaticDowncast(Self, 1438 Self.Context.getCanonicalType(SrcExpr->getType()), 1439 Self.Context.getCanonicalType(DestPointee), CStyle, 1440 OpRange, SrcExpr->getType(), DestType, msg, Kind, 1441 BasePath); 1442 } 1443 1444 /// Tests whether a conversion according to C++ 5.2.9p8 is valid. 1445 TryCastResult 1446 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 1447 bool CStyle, SourceRange OpRange, 1448 unsigned &msg, CastKind &Kind, 1449 CXXCastPath &BasePath) { 1450 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 1451 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 1452 // is a class derived from B, if a valid standard conversion from "pointer 1453 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 1454 // class of D. 1455 // In addition, DR54 clarifies that the base must be accessible in the 1456 // current context. 1457 1458 const PointerType *DestPointer = DestType->getAs<PointerType>(); 1459 if (!DestPointer) { 1460 return TC_NotApplicable; 1461 } 1462 1463 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 1464 if (!SrcPointer) { 1465 msg = diag::err_bad_static_cast_pointer_nonpointer; 1466 return TC_NotApplicable; 1467 } 1468 1469 return TryStaticDowncast(Self, 1470 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 1471 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 1472 CStyle, OpRange, SrcType, DestType, msg, Kind, 1473 BasePath); 1474 } 1475 1476 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 1477 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 1478 /// DestType is possible and allowed. 1479 TryCastResult 1480 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 1481 bool CStyle, SourceRange OpRange, QualType OrigSrcType, 1482 QualType OrigDestType, unsigned &msg, 1483 CastKind &Kind, CXXCastPath &BasePath) { 1484 // We can only work with complete types. But don't complain if it doesn't work 1485 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) || 1486 !Self.isCompleteType(OpRange.getBegin(), DestType)) 1487 return TC_NotApplicable; 1488 1489 // Downcast can only happen in class hierarchies, so we need classes. 1490 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 1491 return TC_NotApplicable; 1492 } 1493 1494 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1495 /*DetectVirtual=*/true); 1496 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) { 1497 return TC_NotApplicable; 1498 } 1499 1500 // Target type does derive from source type. Now we're serious. If an error 1501 // appears now, it's not ignored. 1502 // This may not be entirely in line with the standard. Take for example: 1503 // struct A {}; 1504 // struct B : virtual A { 1505 // B(A&); 1506 // }; 1507 // 1508 // void f() 1509 // { 1510 // (void)static_cast<const B&>(*((A*)0)); 1511 // } 1512 // As far as the standard is concerned, p5 does not apply (A is virtual), so 1513 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 1514 // However, both GCC and Comeau reject this example, and accepting it would 1515 // mean more complex code if we're to preserve the nice error message. 1516 // FIXME: Being 100% compliant here would be nice to have. 1517 1518 // Must preserve cv, as always, unless we're in C-style mode. 1519 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 1520 msg = diag::err_bad_cxx_cast_qualifiers_away; 1521 return TC_Failed; 1522 } 1523 1524 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 1525 // This code is analoguous to that in CheckDerivedToBaseConversion, except 1526 // that it builds the paths in reverse order. 1527 // To sum up: record all paths to the base and build a nice string from 1528 // them. Use it to spice up the error message. 1529 if (!Paths.isRecordingPaths()) { 1530 Paths.clear(); 1531 Paths.setRecordingPaths(true); 1532 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths); 1533 } 1534 std::string PathDisplayStr; 1535 std::set<unsigned> DisplayedPaths; 1536 for (clang::CXXBasePath &Path : Paths) { 1537 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) { 1538 // We haven't displayed a path to this particular base 1539 // class subobject yet. 1540 PathDisplayStr += "\n "; 1541 for (CXXBasePathElement &PE : llvm::reverse(Path)) 1542 PathDisplayStr += PE.Base->getType().getAsString() + " -> "; 1543 PathDisplayStr += QualType(DestType).getAsString(); 1544 } 1545 } 1546 1547 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 1548 << QualType(SrcType).getUnqualifiedType() 1549 << QualType(DestType).getUnqualifiedType() 1550 << PathDisplayStr << OpRange; 1551 msg = 0; 1552 return TC_Failed; 1553 } 1554 1555 if (Paths.getDetectedVirtual() != nullptr) { 1556 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 1557 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 1558 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 1559 msg = 0; 1560 return TC_Failed; 1561 } 1562 1563 if (!CStyle) { 1564 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1565 SrcType, DestType, 1566 Paths.front(), 1567 diag::err_downcast_from_inaccessible_base)) { 1568 case Sema::AR_accessible: 1569 case Sema::AR_delayed: // be optimistic 1570 case Sema::AR_dependent: // be optimistic 1571 break; 1572 1573 case Sema::AR_inaccessible: 1574 msg = 0; 1575 return TC_Failed; 1576 } 1577 } 1578 1579 Self.BuildBasePathArray(Paths, BasePath); 1580 Kind = CK_BaseToDerived; 1581 return TC_Success; 1582 } 1583 1584 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to 1585 /// C++ 5.2.9p9 is valid: 1586 /// 1587 /// An rvalue of type "pointer to member of D of type cv1 T" can be 1588 /// converted to an rvalue of type "pointer to member of B of type cv2 T", 1589 /// where B is a base class of D [...]. 1590 /// 1591 TryCastResult 1592 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 1593 QualType DestType, bool CStyle, 1594 SourceRange OpRange, 1595 unsigned &msg, CastKind &Kind, 1596 CXXCastPath &BasePath) { 1597 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 1598 if (!DestMemPtr) 1599 return TC_NotApplicable; 1600 1601 bool WasOverloadedFunction = false; 1602 DeclAccessPair FoundOverload; 1603 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 1604 if (FunctionDecl *Fn 1605 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 1606 FoundOverload)) { 1607 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 1608 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 1609 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 1610 WasOverloadedFunction = true; 1611 } 1612 } 1613 1614 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 1615 if (!SrcMemPtr) { 1616 msg = diag::err_bad_static_cast_member_pointer_nonmp; 1617 return TC_NotApplicable; 1618 } 1619 1620 // Lock down the inheritance model right now in MS ABI, whether or not the 1621 // pointee types are the same. 1622 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1623 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 1624 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 1625 } 1626 1627 // T == T, modulo cv 1628 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 1629 DestMemPtr->getPointeeType())) 1630 return TC_NotApplicable; 1631 1632 // B base of D 1633 QualType SrcClass(SrcMemPtr->getClass(), 0); 1634 QualType DestClass(DestMemPtr->getClass(), 0); 1635 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1636 /*DetectVirtual=*/true); 1637 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths)) 1638 return TC_NotApplicable; 1639 1640 // B is a base of D. But is it an allowed base? If not, it's a hard error. 1641 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 1642 Paths.clear(); 1643 Paths.setRecordingPaths(true); 1644 bool StillOkay = 1645 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths); 1646 assert(StillOkay); 1647 (void)StillOkay; 1648 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 1649 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 1650 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 1651 msg = 0; 1652 return TC_Failed; 1653 } 1654 1655 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 1656 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 1657 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 1658 msg = 0; 1659 return TC_Failed; 1660 } 1661 1662 if (!CStyle) { 1663 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 1664 DestClass, SrcClass, 1665 Paths.front(), 1666 diag::err_upcast_to_inaccessible_base)) { 1667 case Sema::AR_accessible: 1668 case Sema::AR_delayed: 1669 case Sema::AR_dependent: 1670 // Optimistically assume that the delayed and dependent cases 1671 // will work out. 1672 break; 1673 1674 case Sema::AR_inaccessible: 1675 msg = 0; 1676 return TC_Failed; 1677 } 1678 } 1679 1680 if (WasOverloadedFunction) { 1681 // Resolve the address of the overloaded function again, this time 1682 // allowing complaints if something goes wrong. 1683 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 1684 DestType, 1685 true, 1686 FoundOverload); 1687 if (!Fn) { 1688 msg = 0; 1689 return TC_Failed; 1690 } 1691 1692 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 1693 if (!SrcExpr.isUsable()) { 1694 msg = 0; 1695 return TC_Failed; 1696 } 1697 } 1698 1699 Self.BuildBasePathArray(Paths, BasePath); 1700 Kind = CK_DerivedToBaseMemberPointer; 1701 return TC_Success; 1702 } 1703 1704 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 1705 /// is valid: 1706 /// 1707 /// An expression e can be explicitly converted to a type T using a 1708 /// @c static_cast if the declaration "T t(e);" is well-formed [...]. 1709 TryCastResult 1710 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 1711 Sema::CheckedConversionKind CCK, 1712 SourceRange OpRange, unsigned &msg, 1713 CastKind &Kind, bool ListInitialization) { 1714 if (DestType->isRecordType()) { 1715 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 1716 diag::err_bad_cast_incomplete) || 1717 Self.RequireNonAbstractType(OpRange.getBegin(), DestType, 1718 diag::err_allocation_of_abstract_type)) { 1719 msg = 0; 1720 return TC_Failed; 1721 } 1722 } 1723 1724 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 1725 InitializationKind InitKind 1726 = (CCK == Sema::CCK_CStyleCast) 1727 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange, 1728 ListInitialization) 1729 : (CCK == Sema::CCK_FunctionalCast) 1730 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization) 1731 : InitializationKind::CreateCast(OpRange); 1732 Expr *SrcExprRaw = SrcExpr.get(); 1733 // FIXME: Per DR242, we should check for an implicit conversion sequence 1734 // or for a constructor that could be invoked by direct-initialization 1735 // here, not for an initialization sequence. 1736 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw); 1737 1738 // At this point of CheckStaticCast, if the destination is a reference, 1739 // or the expression is an overload expression this has to work. 1740 // There is no other way that works. 1741 // On the other hand, if we're checking a C-style cast, we've still got 1742 // the reinterpret_cast way. 1743 bool CStyle 1744 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 1745 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 1746 return TC_NotApplicable; 1747 1748 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw); 1749 if (Result.isInvalid()) { 1750 msg = 0; 1751 return TC_Failed; 1752 } 1753 1754 if (InitSeq.isConstructorInitialization()) 1755 Kind = CK_ConstructorConversion; 1756 else 1757 Kind = CK_NoOp; 1758 1759 SrcExpr = Result; 1760 return TC_Success; 1761 } 1762 1763 /// TryConstCast - See if a const_cast from source to destination is allowed, 1764 /// and perform it if it is. 1765 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, 1766 QualType DestType, bool CStyle, 1767 unsigned &msg) { 1768 DestType = Self.Context.getCanonicalType(DestType); 1769 QualType SrcType = SrcExpr.get()->getType(); 1770 bool NeedToMaterializeTemporary = false; 1771 1772 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 1773 // C++11 5.2.11p4: 1774 // if a pointer to T1 can be explicitly converted to the type "pointer to 1775 // T2" using a const_cast, then the following conversions can also be 1776 // made: 1777 // -- an lvalue of type T1 can be explicitly converted to an lvalue of 1778 // type T2 using the cast const_cast<T2&>; 1779 // -- a glvalue of type T1 can be explicitly converted to an xvalue of 1780 // type T2 using the cast const_cast<T2&&>; and 1781 // -- if T1 is a class type, a prvalue of type T1 can be explicitly 1782 // converted to an xvalue of type T2 using the cast const_cast<T2&&>. 1783 1784 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) { 1785 // Cannot const_cast non-lvalue to lvalue reference type. But if this 1786 // is C-style, static_cast might find a way, so we simply suggest a 1787 // message and tell the parent to keep searching. 1788 msg = diag::err_bad_cxx_cast_rvalue; 1789 return TC_NotApplicable; 1790 } 1791 1792 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) { 1793 if (!SrcType->isRecordType()) { 1794 // Cannot const_cast non-class prvalue to rvalue reference type. But if 1795 // this is C-style, static_cast can do this. 1796 msg = diag::err_bad_cxx_cast_rvalue; 1797 return TC_NotApplicable; 1798 } 1799 1800 // Materialize the class prvalue so that the const_cast can bind a 1801 // reference to it. 1802 NeedToMaterializeTemporary = true; 1803 } 1804 1805 // It's not completely clear under the standard whether we can 1806 // const_cast bit-field gl-values. Doing so would not be 1807 // intrinsically complicated, but for now, we say no for 1808 // consistency with other compilers and await the word of the 1809 // committee. 1810 if (SrcExpr.get()->refersToBitField()) { 1811 msg = diag::err_bad_cxx_cast_bitfield; 1812 return TC_NotApplicable; 1813 } 1814 1815 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 1816 SrcType = Self.Context.getPointerType(SrcType); 1817 } 1818 1819 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 1820 // the rules for const_cast are the same as those used for pointers. 1821 1822 if (!DestType->isPointerType() && 1823 !DestType->isMemberPointerType() && 1824 !DestType->isObjCObjectPointerType()) { 1825 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 1826 // was a reference type, we converted it to a pointer above. 1827 // The status of rvalue references isn't entirely clear, but it looks like 1828 // conversion to them is simply invalid. 1829 // C++ 5.2.11p3: For two pointer types [...] 1830 if (!CStyle) 1831 msg = diag::err_bad_const_cast_dest; 1832 return TC_NotApplicable; 1833 } 1834 if (DestType->isFunctionPointerType() || 1835 DestType->isMemberFunctionPointerType()) { 1836 // Cannot cast direct function pointers. 1837 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 1838 // T is the ultimate pointee of source and target type. 1839 if (!CStyle) 1840 msg = diag::err_bad_const_cast_dest; 1841 return TC_NotApplicable; 1842 } 1843 1844 // C++ [expr.const.cast]p3: 1845 // "For two similar types T1 and T2, [...]" 1846 // 1847 // We only allow a const_cast to change cvr-qualifiers, not other kinds of 1848 // type qualifiers. (Likewise, we ignore other changes when determining 1849 // whether a cast casts away constness.) 1850 if (!Self.Context.hasCvrSimilarType(SrcType, DestType)) 1851 return TC_NotApplicable; 1852 1853 if (NeedToMaterializeTemporary) 1854 // This is a const_cast from a class prvalue to an rvalue reference type. 1855 // Materialize a temporary to store the result of the conversion. 1856 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(), 1857 SrcExpr.get(), 1858 /*IsLValueReference*/ false); 1859 1860 return TC_Success; 1861 } 1862 1863 // Checks for undefined behavior in reinterpret_cast. 1864 // The cases that is checked for is: 1865 // *reinterpret_cast<T*>(&a) 1866 // reinterpret_cast<T&>(a) 1867 // where accessing 'a' as type 'T' will result in undefined behavior. 1868 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 1869 bool IsDereference, 1870 SourceRange Range) { 1871 unsigned DiagID = IsDereference ? 1872 diag::warn_pointer_indirection_from_incompatible_type : 1873 diag::warn_undefined_reinterpret_cast; 1874 1875 if (Diags.isIgnored(DiagID, Range.getBegin())) 1876 return; 1877 1878 QualType SrcTy, DestTy; 1879 if (IsDereference) { 1880 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 1881 return; 1882 } 1883 SrcTy = SrcType->getPointeeType(); 1884 DestTy = DestType->getPointeeType(); 1885 } else { 1886 if (!DestType->getAs<ReferenceType>()) { 1887 return; 1888 } 1889 SrcTy = SrcType; 1890 DestTy = DestType->getPointeeType(); 1891 } 1892 1893 // Cast is compatible if the types are the same. 1894 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 1895 return; 1896 } 1897 // or one of the types is a char or void type 1898 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 1899 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 1900 return; 1901 } 1902 // or one of the types is a tag type. 1903 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 1904 return; 1905 } 1906 1907 // FIXME: Scoped enums? 1908 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 1909 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 1910 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 1911 return; 1912 } 1913 } 1914 1915 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 1916 } 1917 1918 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, 1919 QualType DestType) { 1920 QualType SrcType = SrcExpr.get()->getType(); 1921 if (Self.Context.hasSameType(SrcType, DestType)) 1922 return; 1923 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>()) 1924 if (SrcPtrTy->isObjCSelType()) { 1925 QualType DT = DestType; 1926 if (isa<PointerType>(DestType)) 1927 DT = DestType->getPointeeType(); 1928 if (!DT.getUnqualifiedType()->isVoidType()) 1929 Self.Diag(SrcExpr.get()->getExprLoc(), 1930 diag::warn_cast_pointer_from_sel) 1931 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 1932 } 1933 } 1934 1935 /// Diagnose casts that change the calling convention of a pointer to a function 1936 /// defined in the current TU. 1937 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, 1938 QualType DstType, SourceRange OpRange) { 1939 // Check if this cast would change the calling convention of a function 1940 // pointer type. 1941 QualType SrcType = SrcExpr.get()->getType(); 1942 if (Self.Context.hasSameType(SrcType, DstType) || 1943 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType()) 1944 return; 1945 const auto *SrcFTy = 1946 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); 1947 const auto *DstFTy = 1948 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>(); 1949 CallingConv SrcCC = SrcFTy->getCallConv(); 1950 CallingConv DstCC = DstFTy->getCallConv(); 1951 if (SrcCC == DstCC) 1952 return; 1953 1954 // We have a calling convention cast. Check if the source is a pointer to a 1955 // known, specific function that has already been defined. 1956 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts(); 1957 if (auto *UO = dyn_cast<UnaryOperator>(Src)) 1958 if (UO->getOpcode() == UO_AddrOf) 1959 Src = UO->getSubExpr()->IgnoreParenImpCasts(); 1960 auto *DRE = dyn_cast<DeclRefExpr>(Src); 1961 if (!DRE) 1962 return; 1963 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 1964 if (!FD) 1965 return; 1966 1967 // Only warn if we are casting from the default convention to a non-default 1968 // convention. This can happen when the programmer forgot to apply the calling 1969 // convention to the function declaration and then inserted this cast to 1970 // satisfy the type system. 1971 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention( 1972 FD->isVariadic(), FD->isCXXInstanceMember()); 1973 if (DstCC == DefaultCC || SrcCC != DefaultCC) 1974 return; 1975 1976 // Diagnose this cast, as it is probably bad. 1977 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC); 1978 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC); 1979 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv) 1980 << SrcCCName << DstCCName << OpRange; 1981 1982 // The checks above are cheaper than checking if the diagnostic is enabled. 1983 // However, it's worth checking if the warning is enabled before we construct 1984 // a fixit. 1985 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin())) 1986 return; 1987 1988 // Try to suggest a fixit to change the calling convention of the function 1989 // whose address was taken. Try to use the latest macro for the convention. 1990 // For example, users probably want to write "WINAPI" instead of "__stdcall" 1991 // to match the Windows header declarations. 1992 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc(); 1993 Preprocessor &PP = Self.getPreprocessor(); 1994 SmallVector<TokenValue, 6> AttrTokens; 1995 SmallString<64> CCAttrText; 1996 llvm::raw_svector_ostream OS(CCAttrText); 1997 if (Self.getLangOpts().MicrosoftExt) { 1998 // __stdcall or __vectorcall 1999 OS << "__" << DstCCName; 2000 IdentifierInfo *II = PP.getIdentifierInfo(OS.str()); 2001 AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) 2002 ? TokenValue(II->getTokenID()) 2003 : TokenValue(II)); 2004 } else { 2005 // __attribute__((stdcall)) or __attribute__((vectorcall)) 2006 OS << "__attribute__((" << DstCCName << "))"; 2007 AttrTokens.push_back(tok::kw___attribute); 2008 AttrTokens.push_back(tok::l_paren); 2009 AttrTokens.push_back(tok::l_paren); 2010 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName); 2011 AttrTokens.push_back(II->isKeyword(Self.getLangOpts()) 2012 ? TokenValue(II->getTokenID()) 2013 : TokenValue(II)); 2014 AttrTokens.push_back(tok::r_paren); 2015 AttrTokens.push_back(tok::r_paren); 2016 } 2017 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens); 2018 if (!AttrSpelling.empty()) 2019 CCAttrText = AttrSpelling; 2020 OS << ' '; 2021 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit) 2022 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText); 2023 } 2024 2025 static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange, 2026 const Expr *SrcExpr, QualType DestType, 2027 Sema &Self) { 2028 QualType SrcType = SrcExpr->getType(); 2029 2030 // Not warning on reinterpret_cast, boolean, constant expressions, etc 2031 // are not explicit design choices, but consistent with GCC's behavior. 2032 // Feel free to modify them if you've reason/evidence for an alternative. 2033 if (CStyle && SrcType->isIntegralType(Self.Context) 2034 && !SrcType->isBooleanType() 2035 && !SrcType->isEnumeralType() 2036 && !SrcExpr->isIntegerConstantExpr(Self.Context) 2037 && Self.Context.getTypeSize(DestType) > 2038 Self.Context.getTypeSize(SrcType)) { 2039 // Separate between casts to void* and non-void* pointers. 2040 // Some APIs use (abuse) void* for something like a user context, 2041 // and often that value is an integer even if it isn't a pointer itself. 2042 // Having a separate warning flag allows users to control the warning 2043 // for their workflow. 2044 unsigned Diag = DestType->isVoidPointerType() ? 2045 diag::warn_int_to_void_pointer_cast 2046 : diag::warn_int_to_pointer_cast; 2047 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; 2048 } 2049 } 2050 2051 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, 2052 ExprResult &Result) { 2053 // We can only fix an overloaded reinterpret_cast if 2054 // - it is a template with explicit arguments that resolves to an lvalue 2055 // unambiguously, or 2056 // - it is the only function in an overload set that may have its address 2057 // taken. 2058 2059 Expr *E = Result.get(); 2060 // TODO: what if this fails because of DiagnoseUseOfDecl or something 2061 // like it? 2062 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2063 Result, 2064 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 2065 ) && 2066 Result.isUsable()) 2067 return true; 2068 2069 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 2070 // preserves Result. 2071 Result = E; 2072 if (!Self.resolveAndFixAddressOfSingleOverloadCandidate( 2073 Result, /*DoFunctionPointerConversion=*/true)) 2074 return false; 2075 return Result.isUsable(); 2076 } 2077 2078 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 2079 QualType DestType, bool CStyle, 2080 SourceRange OpRange, 2081 unsigned &msg, 2082 CastKind &Kind) { 2083 bool IsLValueCast = false; 2084 2085 DestType = Self.Context.getCanonicalType(DestType); 2086 QualType SrcType = SrcExpr.get()->getType(); 2087 2088 // Is the source an overloaded name? (i.e. &foo) 2089 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5) 2090 if (SrcType == Self.Context.OverloadTy) { 2091 ExprResult FixedExpr = SrcExpr; 2092 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr)) 2093 return TC_NotApplicable; 2094 2095 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr"); 2096 SrcExpr = FixedExpr; 2097 SrcType = SrcExpr.get()->getType(); 2098 } 2099 2100 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 2101 if (!SrcExpr.get()->isGLValue()) { 2102 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the 2103 // similar comment in const_cast. 2104 msg = diag::err_bad_cxx_cast_rvalue; 2105 return TC_NotApplicable; 2106 } 2107 2108 if (!CStyle) { 2109 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 2110 /*IsDereference=*/false, OpRange); 2111 } 2112 2113 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 2114 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 2115 // built-in & and * operators. 2116 2117 const char *inappropriate = nullptr; 2118 switch (SrcExpr.get()->getObjectKind()) { 2119 case OK_Ordinary: 2120 break; 2121 case OK_BitField: 2122 msg = diag::err_bad_cxx_cast_bitfield; 2123 return TC_NotApplicable; 2124 // FIXME: Use a specific diagnostic for the rest of these cases. 2125 case OK_VectorComponent: inappropriate = "vector element"; break; 2126 case OK_MatrixComponent: 2127 inappropriate = "matrix element"; 2128 break; 2129 case OK_ObjCProperty: inappropriate = "property expression"; break; 2130 case OK_ObjCSubscript: inappropriate = "container subscripting expression"; 2131 break; 2132 } 2133 if (inappropriate) { 2134 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 2135 << inappropriate << DestType 2136 << OpRange << SrcExpr.get()->getSourceRange(); 2137 msg = 0; SrcExpr = ExprError(); 2138 return TC_NotApplicable; 2139 } 2140 2141 // This code does this transformation for the checked types. 2142 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 2143 SrcType = Self.Context.getPointerType(SrcType); 2144 2145 IsLValueCast = true; 2146 } 2147 2148 // Canonicalize source for comparison. 2149 SrcType = Self.Context.getCanonicalType(SrcType); 2150 2151 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 2152 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 2153 if (DestMemPtr && SrcMemPtr) { 2154 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 2155 // can be explicitly converted to an rvalue of type "pointer to member 2156 // of Y of type T2" if T1 and T2 are both function types or both object 2157 // types. 2158 if (DestMemPtr->isMemberFunctionPointer() != 2159 SrcMemPtr->isMemberFunctionPointer()) 2160 return TC_NotApplicable; 2161 2162 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2163 // We need to determine the inheritance model that the class will use if 2164 // haven't yet. 2165 (void)Self.isCompleteType(OpRange.getBegin(), SrcType); 2166 (void)Self.isCompleteType(OpRange.getBegin(), DestType); 2167 } 2168 2169 // Don't allow casting between member pointers of different sizes. 2170 if (Self.Context.getTypeSize(DestMemPtr) != 2171 Self.Context.getTypeSize(SrcMemPtr)) { 2172 msg = diag::err_bad_cxx_cast_member_pointer_size; 2173 return TC_Failed; 2174 } 2175 2176 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 2177 // constness. 2178 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 2179 // we accept it. 2180 if (auto CACK = 2181 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 2182 /*CheckObjCLifetime=*/CStyle)) 2183 return getCastAwayConstnessCastKind(CACK, msg); 2184 2185 // A valid member pointer cast. 2186 assert(!IsLValueCast); 2187 Kind = CK_ReinterpretMemberPointer; 2188 return TC_Success; 2189 } 2190 2191 // See below for the enumeral issue. 2192 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 2193 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 2194 // type large enough to hold it. A value of std::nullptr_t can be 2195 // converted to an integral type; the conversion has the same meaning 2196 // and validity as a conversion of (void*)0 to the integral type. 2197 if (Self.Context.getTypeSize(SrcType) > 2198 Self.Context.getTypeSize(DestType)) { 2199 msg = diag::err_bad_reinterpret_cast_small_int; 2200 return TC_Failed; 2201 } 2202 Kind = CK_PointerToIntegral; 2203 return TC_Success; 2204 } 2205 2206 // Allow reinterpret_casts between vectors of the same size and 2207 // between vectors and integers of the same size. 2208 bool destIsVector = DestType->isVectorType(); 2209 bool srcIsVector = SrcType->isVectorType(); 2210 if (srcIsVector || destIsVector) { 2211 // The non-vector type, if any, must have integral type. This is 2212 // the same rule that C vector casts use; note, however, that enum 2213 // types are not integral in C++. 2214 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) || 2215 (!srcIsVector && !SrcType->isIntegralType(Self.Context))) 2216 return TC_NotApplicable; 2217 2218 // The size we want to consider is eltCount * eltSize. 2219 // That's exactly what the lax-conversion rules will check. 2220 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) { 2221 Kind = CK_BitCast; 2222 return TC_Success; 2223 } 2224 2225 // Otherwise, pick a reasonable diagnostic. 2226 if (!destIsVector) 2227 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 2228 else if (!srcIsVector) 2229 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 2230 else 2231 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 2232 2233 return TC_Failed; 2234 } 2235 2236 if (SrcType == DestType) { 2237 // C++ 5.2.10p2 has a note that mentions that, subject to all other 2238 // restrictions, a cast to the same type is allowed so long as it does not 2239 // cast away constness. In C++98, the intent was not entirely clear here, 2240 // since all other paragraphs explicitly forbid casts to the same type. 2241 // C++11 clarifies this case with p2. 2242 // 2243 // The only allowed types are: integral, enumeration, pointer, or 2244 // pointer-to-member types. We also won't restrict Obj-C pointers either. 2245 Kind = CK_NoOp; 2246 TryCastResult Result = TC_NotApplicable; 2247 if (SrcType->isIntegralOrEnumerationType() || 2248 SrcType->isAnyPointerType() || 2249 SrcType->isMemberPointerType() || 2250 SrcType->isBlockPointerType()) { 2251 Result = TC_Success; 2252 } 2253 return Result; 2254 } 2255 2256 bool destIsPtr = DestType->isAnyPointerType() || 2257 DestType->isBlockPointerType(); 2258 bool srcIsPtr = SrcType->isAnyPointerType() || 2259 SrcType->isBlockPointerType(); 2260 if (!destIsPtr && !srcIsPtr) { 2261 // Except for std::nullptr_t->integer and lvalue->reference, which are 2262 // handled above, at least one of the two arguments must be a pointer. 2263 return TC_NotApplicable; 2264 } 2265 2266 if (DestType->isIntegralType(Self.Context)) { 2267 assert(srcIsPtr && "One type must be a pointer"); 2268 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 2269 // type large enough to hold it; except in Microsoft mode, where the 2270 // integral type size doesn't matter (except we don't allow bool). 2271 if ((Self.Context.getTypeSize(SrcType) > 2272 Self.Context.getTypeSize(DestType))) { 2273 bool MicrosoftException = 2274 Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType(); 2275 if (MicrosoftException) { 2276 unsigned Diag = SrcType->isVoidPointerType() 2277 ? diag::warn_void_pointer_to_int_cast 2278 : diag::warn_pointer_to_int_cast; 2279 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; 2280 } else { 2281 msg = diag::err_bad_reinterpret_cast_small_int; 2282 return TC_Failed; 2283 } 2284 } 2285 Kind = CK_PointerToIntegral; 2286 return TC_Success; 2287 } 2288 2289 if (SrcType->isIntegralOrEnumerationType()) { 2290 assert(destIsPtr && "One type must be a pointer"); 2291 checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self); 2292 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 2293 // converted to a pointer. 2294 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 2295 // necessarily converted to a null pointer value.] 2296 Kind = CK_IntegralToPointer; 2297 return TC_Success; 2298 } 2299 2300 if (!destIsPtr || !srcIsPtr) { 2301 // With the valid non-pointer conversions out of the way, we can be even 2302 // more stringent. 2303 return TC_NotApplicable; 2304 } 2305 2306 // Cannot convert between block pointers and Objective-C object pointers. 2307 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 2308 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 2309 return TC_NotApplicable; 2310 2311 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 2312 // The C-style cast operator can. 2313 TryCastResult SuccessResult = TC_Success; 2314 if (auto CACK = 2315 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 2316 /*CheckObjCLifetime=*/CStyle)) 2317 SuccessResult = getCastAwayConstnessCastKind(CACK, msg); 2318 2319 if (IsAddressSpaceConversion(SrcType, DestType)) { 2320 Kind = CK_AddressSpaceConversion; 2321 assert(SrcType->isPointerType() && DestType->isPointerType()); 2322 if (!CStyle && 2323 !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf( 2324 SrcType->getPointeeType().getQualifiers())) { 2325 SuccessResult = TC_Failed; 2326 } 2327 } else if (IsLValueCast) { 2328 Kind = CK_LValueBitCast; 2329 } else if (DestType->isObjCObjectPointerType()) { 2330 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 2331 } else if (DestType->isBlockPointerType()) { 2332 if (!SrcType->isBlockPointerType()) { 2333 Kind = CK_AnyPointerToBlockPointerCast; 2334 } else { 2335 Kind = CK_BitCast; 2336 } 2337 } else { 2338 Kind = CK_BitCast; 2339 } 2340 2341 // Any pointer can be cast to an Objective-C pointer type with a C-style 2342 // cast. 2343 if (CStyle && DestType->isObjCObjectPointerType()) { 2344 return SuccessResult; 2345 } 2346 if (CStyle) 2347 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2348 2349 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); 2350 2351 // Not casting away constness, so the only remaining check is for compatible 2352 // pointer categories. 2353 2354 if (SrcType->isFunctionPointerType()) { 2355 if (DestType->isFunctionPointerType()) { 2356 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 2357 // a pointer to a function of a different type. 2358 return SuccessResult; 2359 } 2360 2361 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 2362 // an object type or vice versa is conditionally-supported. 2363 // Compilers support it in C++03 too, though, because it's necessary for 2364 // casting the return value of dlsym() and GetProcAddress(). 2365 // FIXME: Conditionally-supported behavior should be configurable in the 2366 // TargetInfo or similar. 2367 Self.Diag(OpRange.getBegin(), 2368 Self.getLangOpts().CPlusPlus11 ? 2369 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2370 << OpRange; 2371 return SuccessResult; 2372 } 2373 2374 if (DestType->isFunctionPointerType()) { 2375 // See above. 2376 Self.Diag(OpRange.getBegin(), 2377 Self.getLangOpts().CPlusPlus11 ? 2378 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj) 2379 << OpRange; 2380 return SuccessResult; 2381 } 2382 2383 // Diagnose address space conversion in nested pointers. 2384 QualType DestPtee = DestType->getPointeeType().isNull() 2385 ? DestType->getPointeeType() 2386 : DestType->getPointeeType()->getPointeeType(); 2387 QualType SrcPtee = SrcType->getPointeeType().isNull() 2388 ? SrcType->getPointeeType() 2389 : SrcType->getPointeeType()->getPointeeType(); 2390 while (!DestPtee.isNull() && !SrcPtee.isNull()) { 2391 if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) { 2392 Self.Diag(OpRange.getBegin(), 2393 diag::warn_bad_cxx_cast_nested_pointer_addr_space) 2394 << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2395 break; 2396 } 2397 DestPtee = DestPtee->getPointeeType(); 2398 SrcPtee = SrcPtee->getPointeeType(); 2399 } 2400 2401 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 2402 // a pointer to an object of different type. 2403 // Void pointers are not specified, but supported by every compiler out there. 2404 // So we finish by allowing everything that remains - it's got to be two 2405 // object pointers. 2406 return SuccessResult; 2407 } 2408 2409 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr, 2410 QualType DestType, bool CStyle, 2411 unsigned &msg, CastKind &Kind) { 2412 if (!Self.getLangOpts().OpenCL) 2413 // FIXME: As compiler doesn't have any information about overlapping addr 2414 // spaces at the moment we have to be permissive here. 2415 return TC_NotApplicable; 2416 // Even though the logic below is general enough and can be applied to 2417 // non-OpenCL mode too, we fast-path above because no other languages 2418 // define overlapping address spaces currently. 2419 auto SrcType = SrcExpr.get()->getType(); 2420 // FIXME: Should this be generalized to references? The reference parameter 2421 // however becomes a reference pointee type here and therefore rejected. 2422 // Perhaps this is the right behavior though according to C++. 2423 auto SrcPtrType = SrcType->getAs<PointerType>(); 2424 if (!SrcPtrType) 2425 return TC_NotApplicable; 2426 auto DestPtrType = DestType->getAs<PointerType>(); 2427 if (!DestPtrType) 2428 return TC_NotApplicable; 2429 auto SrcPointeeType = SrcPtrType->getPointeeType(); 2430 auto DestPointeeType = DestPtrType->getPointeeType(); 2431 if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) { 2432 msg = diag::err_bad_cxx_cast_addr_space_mismatch; 2433 return TC_Failed; 2434 } 2435 auto SrcPointeeTypeWithoutAS = 2436 Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType()); 2437 auto DestPointeeTypeWithoutAS = 2438 Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType()); 2439 if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS, 2440 DestPointeeTypeWithoutAS)) { 2441 Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace() 2442 ? CK_NoOp 2443 : CK_AddressSpaceConversion; 2444 return TC_Success; 2445 } else { 2446 return TC_NotApplicable; 2447 } 2448 } 2449 2450 void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) { 2451 // In OpenCL only conversions between pointers to objects in overlapping 2452 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps 2453 // with any named one, except for constant. 2454 2455 // Converting the top level pointee addrspace is permitted for compatible 2456 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but 2457 // if any of the nested pointee addrspaces differ, we emit a warning 2458 // regardless of addrspace compatibility. This makes 2459 // local int ** p; 2460 // return (generic int **) p; 2461 // warn even though local -> generic is permitted. 2462 if (Self.getLangOpts().OpenCL) { 2463 const Type *DestPtr, *SrcPtr; 2464 bool Nested = false; 2465 unsigned DiagID = diag::err_typecheck_incompatible_address_space; 2466 DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()), 2467 SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr()); 2468 2469 while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) { 2470 const PointerType *DestPPtr = cast<PointerType>(DestPtr); 2471 const PointerType *SrcPPtr = cast<PointerType>(SrcPtr); 2472 QualType DestPPointee = DestPPtr->getPointeeType(); 2473 QualType SrcPPointee = SrcPPtr->getPointeeType(); 2474 if (Nested 2475 ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace() 2476 : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) { 2477 Self.Diag(OpRange.getBegin(), DiagID) 2478 << SrcType << DestType << Sema::AA_Casting 2479 << SrcExpr.get()->getSourceRange(); 2480 if (!Nested) 2481 SrcExpr = ExprError(); 2482 return; 2483 } 2484 2485 DestPtr = DestPPtr->getPointeeType().getTypePtr(); 2486 SrcPtr = SrcPPtr->getPointeeType().getTypePtr(); 2487 Nested = true; 2488 DiagID = diag::ext_nested_pointer_qualifier_mismatch; 2489 } 2490 } 2491 } 2492 2493 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle, 2494 bool ListInitialization) { 2495 assert(Self.getLangOpts().CPlusPlus); 2496 2497 // Handle placeholders. 2498 if (isPlaceholder()) { 2499 // C-style casts can resolve __unknown_any types. 2500 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2501 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2502 SrcExpr.get(), Kind, 2503 ValueKind, BasePath); 2504 return; 2505 } 2506 2507 checkNonOverloadPlaceholders(); 2508 if (SrcExpr.isInvalid()) 2509 return; 2510 } 2511 2512 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 2513 // This test is outside everything else because it's the only case where 2514 // a non-lvalue-reference target type does not lead to decay. 2515 if (DestType->isVoidType()) { 2516 Kind = CK_ToVoid; 2517 2518 if (claimPlaceholder(BuiltinType::Overload)) { 2519 Self.ResolveAndFixSingleFunctionTemplateSpecialization( 2520 SrcExpr, /* Decay Function to ptr */ false, 2521 /* Complain */ true, DestRange, DestType, 2522 diag::err_bad_cstyle_cast_overload); 2523 if (SrcExpr.isInvalid()) 2524 return; 2525 } 2526 2527 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2528 return; 2529 } 2530 2531 // If the type is dependent, we won't do any other semantic analysis now. 2532 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() || 2533 SrcExpr.get()->isValueDependent()) { 2534 assert(Kind == CK_Dependent); 2535 return; 2536 } 2537 2538 if (ValueKind == VK_RValue && !DestType->isRecordType() && 2539 !isPlaceholder(BuiltinType::Overload)) { 2540 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2541 if (SrcExpr.isInvalid()) 2542 return; 2543 } 2544 2545 // AltiVec vector initialization with a single literal. 2546 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 2547 if (vecTy->getVectorKind() == VectorType::AltiVecVector 2548 && (SrcExpr.get()->getType()->isIntegerType() 2549 || SrcExpr.get()->getType()->isFloatingType())) { 2550 Kind = CK_VectorSplat; 2551 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2552 return; 2553 } 2554 2555 // C++ [expr.cast]p5: The conversions performed by 2556 // - a const_cast, 2557 // - a static_cast, 2558 // - a static_cast followed by a const_cast, 2559 // - a reinterpret_cast, or 2560 // - a reinterpret_cast followed by a const_cast, 2561 // can be performed using the cast notation of explicit type conversion. 2562 // [...] If a conversion can be interpreted in more than one of the ways 2563 // listed above, the interpretation that appears first in the list is used, 2564 // even if a cast resulting from that interpretation is ill-formed. 2565 // In plain language, this means trying a const_cast ... 2566 // Note that for address space we check compatibility after const_cast. 2567 unsigned msg = diag::err_bad_cxx_cast_generic; 2568 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType, 2569 /*CStyle*/ true, msg); 2570 if (SrcExpr.isInvalid()) 2571 return; 2572 if (isValidCast(tcr)) 2573 Kind = CK_NoOp; 2574 2575 Sema::CheckedConversionKind CCK = 2576 FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast; 2577 if (tcr == TC_NotApplicable) { 2578 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg, 2579 Kind); 2580 if (SrcExpr.isInvalid()) 2581 return; 2582 2583 if (tcr == TC_NotApplicable) { 2584 // ... or if that is not possible, a static_cast, ignoring const and 2585 // addr space, ... 2586 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind, 2587 BasePath, ListInitialization); 2588 if (SrcExpr.isInvalid()) 2589 return; 2590 2591 if (tcr == TC_NotApplicable) { 2592 // ... and finally a reinterpret_cast, ignoring const and addr space. 2593 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true, 2594 OpRange, msg, Kind); 2595 if (SrcExpr.isInvalid()) 2596 return; 2597 } 2598 } 2599 } 2600 2601 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 2602 isValidCast(tcr)) 2603 checkObjCConversion(CCK); 2604 2605 if (tcr != TC_Success && msg != 0) { 2606 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2607 DeclAccessPair Found; 2608 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 2609 DestType, 2610 /*Complain*/ true, 2611 Found); 2612 if (Fn) { 2613 // If DestType is a function type (not to be confused with the function 2614 // pointer type), it will be possible to resolve the function address, 2615 // but the type cast should be considered as failure. 2616 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression; 2617 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload) 2618 << OE->getName() << DestType << OpRange 2619 << OE->getQualifierLoc().getSourceRange(); 2620 Self.NoteAllOverloadCandidates(SrcExpr.get()); 2621 } 2622 } else { 2623 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 2624 OpRange, SrcExpr.get(), DestType, ListInitialization); 2625 } 2626 } 2627 2628 if (isValidCast(tcr)) { 2629 if (Kind == CK_BitCast) 2630 checkCastAlign(); 2631 } else { 2632 SrcExpr = ExprError(); 2633 } 2634 } 2635 2636 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a 2637 /// non-matching type. Such as enum function call to int, int call to 2638 /// pointer; etc. Cast to 'void' is an exception. 2639 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, 2640 QualType DestType) { 2641 if (Self.Diags.isIgnored(diag::warn_bad_function_cast, 2642 SrcExpr.get()->getExprLoc())) 2643 return; 2644 2645 if (!isa<CallExpr>(SrcExpr.get())) 2646 return; 2647 2648 QualType SrcType = SrcExpr.get()->getType(); 2649 if (DestType.getUnqualifiedType()->isVoidType()) 2650 return; 2651 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType()) 2652 && (DestType->isAnyPointerType() || DestType->isBlockPointerType())) 2653 return; 2654 if (SrcType->isIntegerType() && DestType->isIntegerType() && 2655 (SrcType->isBooleanType() == DestType->isBooleanType()) && 2656 (SrcType->isEnumeralType() == DestType->isEnumeralType())) 2657 return; 2658 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType()) 2659 return; 2660 if (SrcType->isEnumeralType() && DestType->isEnumeralType()) 2661 return; 2662 if (SrcType->isComplexType() && DestType->isComplexType()) 2663 return; 2664 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType()) 2665 return; 2666 if (SrcType->isFixedPointType() && DestType->isFixedPointType()) 2667 return; 2668 2669 Self.Diag(SrcExpr.get()->getExprLoc(), 2670 diag::warn_bad_function_cast) 2671 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2672 } 2673 2674 /// Check the semantics of a C-style cast operation, in C. 2675 void CastOperation::CheckCStyleCast() { 2676 assert(!Self.getLangOpts().CPlusPlus); 2677 2678 // C-style casts can resolve __unknown_any types. 2679 if (claimPlaceholder(BuiltinType::UnknownAny)) { 2680 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 2681 SrcExpr.get(), Kind, 2682 ValueKind, BasePath); 2683 return; 2684 } 2685 2686 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 2687 // type needs to be scalar. 2688 if (DestType->isVoidType()) { 2689 // We don't necessarily do lvalue-to-rvalue conversions on this. 2690 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get()); 2691 if (SrcExpr.isInvalid()) 2692 return; 2693 2694 // Cast to void allows any expr type. 2695 Kind = CK_ToVoid; 2696 return; 2697 } 2698 2699 // Overloads are allowed with C extensions, so we need to support them. 2700 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 2701 DeclAccessPair DAP; 2702 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction( 2703 SrcExpr.get(), DestType, /*Complain=*/true, DAP)) 2704 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD); 2705 else 2706 return; 2707 assert(SrcExpr.isUsable()); 2708 } 2709 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get()); 2710 if (SrcExpr.isInvalid()) 2711 return; 2712 QualType SrcType = SrcExpr.get()->getType(); 2713 2714 assert(!SrcType->isPlaceholderType()); 2715 2716 checkAddressSpaceCast(SrcType, DestType); 2717 if (SrcExpr.isInvalid()) 2718 return; 2719 2720 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 2721 diag::err_typecheck_cast_to_incomplete)) { 2722 SrcExpr = ExprError(); 2723 return; 2724 } 2725 2726 // Allow casting a sizeless built-in type to itself. 2727 if (DestType->isSizelessBuiltinType() && 2728 Self.Context.hasSameUnqualifiedType(DestType, SrcType)) { 2729 Kind = CK_NoOp; 2730 return; 2731 } 2732 2733 if (!DestType->isScalarType() && !DestType->isVectorType()) { 2734 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 2735 2736 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 2737 // GCC struct/union extension: allow cast to self. 2738 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 2739 << DestType << SrcExpr.get()->getSourceRange(); 2740 Kind = CK_NoOp; 2741 return; 2742 } 2743 2744 // GCC's cast to union extension. 2745 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 2746 RecordDecl *RD = DestRecordTy->getDecl(); 2747 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) { 2748 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 2749 << SrcExpr.get()->getSourceRange(); 2750 Kind = CK_ToUnion; 2751 return; 2752 } else { 2753 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 2754 << SrcType << SrcExpr.get()->getSourceRange(); 2755 SrcExpr = ExprError(); 2756 return; 2757 } 2758 } 2759 2760 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type. 2761 if (Self.getLangOpts().OpenCL && DestType->isEventT()) { 2762 Expr::EvalResult Result; 2763 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) { 2764 llvm::APSInt CastInt = Result.Val.getInt(); 2765 if (0 == CastInt) { 2766 Kind = CK_ZeroToOCLOpaqueType; 2767 return; 2768 } 2769 Self.Diag(OpRange.getBegin(), 2770 diag::err_opencl_cast_non_zero_to_event_t) 2771 << CastInt.toString(10) << SrcExpr.get()->getSourceRange(); 2772 SrcExpr = ExprError(); 2773 return; 2774 } 2775 } 2776 2777 // Reject any other conversions to non-scalar types. 2778 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 2779 << DestType << SrcExpr.get()->getSourceRange(); 2780 SrcExpr = ExprError(); 2781 return; 2782 } 2783 2784 // The type we're casting to is known to be a scalar or vector. 2785 2786 // Require the operand to be a scalar or vector. 2787 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 2788 Self.Diag(SrcExpr.get()->getExprLoc(), 2789 diag::err_typecheck_expect_scalar_operand) 2790 << SrcType << SrcExpr.get()->getSourceRange(); 2791 SrcExpr = ExprError(); 2792 return; 2793 } 2794 2795 if (DestType->isExtVectorType()) { 2796 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind); 2797 return; 2798 } 2799 2800 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 2801 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 2802 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 2803 Kind = CK_VectorSplat; 2804 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get()); 2805 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 2806 SrcExpr = ExprError(); 2807 } 2808 return; 2809 } 2810 2811 if (SrcType->isVectorType()) { 2812 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 2813 SrcExpr = ExprError(); 2814 return; 2815 } 2816 2817 // The source and target types are both scalars, i.e. 2818 // - arithmetic types (fundamental, enum, and complex) 2819 // - all kinds of pointers 2820 // Note that member pointers were filtered out with C++, above. 2821 2822 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 2823 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 2824 SrcExpr = ExprError(); 2825 return; 2826 } 2827 2828 // Can't cast to or from bfloat 2829 if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) { 2830 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16) 2831 << SrcExpr.get()->getSourceRange(); 2832 SrcExpr = ExprError(); 2833 return; 2834 } 2835 if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) { 2836 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16) 2837 << SrcExpr.get()->getSourceRange(); 2838 SrcExpr = ExprError(); 2839 return; 2840 } 2841 2842 // If either type is a pointer, the other type has to be either an 2843 // integer or a pointer. 2844 if (!DestType->isArithmeticType()) { 2845 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 2846 Self.Diag(SrcExpr.get()->getExprLoc(), 2847 diag::err_cast_pointer_from_non_pointer_int) 2848 << SrcType << SrcExpr.get()->getSourceRange(); 2849 SrcExpr = ExprError(); 2850 return; 2851 } 2852 checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType, 2853 Self); 2854 } else if (!SrcType->isArithmeticType()) { 2855 if (!DestType->isIntegralType(Self.Context) && 2856 DestType->isArithmeticType()) { 2857 Self.Diag(SrcExpr.get()->getBeginLoc(), 2858 diag::err_cast_pointer_to_non_pointer_int) 2859 << DestType << SrcExpr.get()->getSourceRange(); 2860 SrcExpr = ExprError(); 2861 return; 2862 } 2863 2864 if ((Self.Context.getTypeSize(SrcType) > 2865 Self.Context.getTypeSize(DestType)) && 2866 !DestType->isBooleanType()) { 2867 // C 6.3.2.3p6: Any pointer type may be converted to an integer type. 2868 // Except as previously specified, the result is implementation-defined. 2869 // If the result cannot be represented in the integer type, the behavior 2870 // is undefined. The result need not be in the range of values of any 2871 // integer type. 2872 unsigned Diag; 2873 if (SrcType->isVoidPointerType()) 2874 Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast 2875 : diag::warn_void_pointer_to_int_cast; 2876 else if (DestType->isEnumeralType()) 2877 Diag = diag::warn_pointer_to_enum_cast; 2878 else 2879 Diag = diag::warn_pointer_to_int_cast; 2880 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange; 2881 } 2882 } 2883 2884 if (Self.getLangOpts().OpenCL && 2885 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 2886 if (DestType->isHalfType()) { 2887 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half) 2888 << DestType << SrcExpr.get()->getSourceRange(); 2889 SrcExpr = ExprError(); 2890 return; 2891 } 2892 } 2893 2894 // ARC imposes extra restrictions on casts. 2895 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) { 2896 checkObjCConversion(Sema::CCK_CStyleCast); 2897 if (SrcExpr.isInvalid()) 2898 return; 2899 2900 const PointerType *CastPtr = DestType->getAs<PointerType>(); 2901 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) { 2902 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 2903 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 2904 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 2905 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 2906 ExprPtr->getPointeeType()->isObjCLifetimeType() && 2907 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 2908 Self.Diag(SrcExpr.get()->getBeginLoc(), 2909 diag::err_typecheck_incompatible_ownership) 2910 << SrcType << DestType << Sema::AA_Casting 2911 << SrcExpr.get()->getSourceRange(); 2912 return; 2913 } 2914 } 2915 } 2916 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 2917 Self.Diag(SrcExpr.get()->getBeginLoc(), 2918 diag::err_arc_convesion_of_weak_unavailable) 2919 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 2920 SrcExpr = ExprError(); 2921 return; 2922 } 2923 } 2924 2925 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType); 2926 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange); 2927 DiagnoseBadFunctionCast(Self, SrcExpr, DestType); 2928 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 2929 if (SrcExpr.isInvalid()) 2930 return; 2931 2932 if (Kind == CK_BitCast) 2933 checkCastAlign(); 2934 } 2935 2936 void CastOperation::CheckBuiltinBitCast() { 2937 QualType SrcType = SrcExpr.get()->getType(); 2938 2939 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 2940 diag::err_typecheck_cast_to_incomplete) || 2941 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 2942 diag::err_incomplete_type)) { 2943 SrcExpr = ExprError(); 2944 return; 2945 } 2946 2947 if (SrcExpr.get()->isRValue()) 2948 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(), 2949 /*IsLValueReference=*/false); 2950 2951 CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType); 2952 CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType); 2953 if (DestSize != SourceSize) { 2954 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch) 2955 << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity(); 2956 SrcExpr = ExprError(); 2957 return; 2958 } 2959 2960 if (!DestType.isTriviallyCopyableType(Self.Context)) { 2961 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) 2962 << 1; 2963 SrcExpr = ExprError(); 2964 return; 2965 } 2966 2967 if (!SrcType.isTriviallyCopyableType(Self.Context)) { 2968 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable) 2969 << 0; 2970 SrcExpr = ExprError(); 2971 return; 2972 } 2973 2974 Kind = CK_LValueToRValueBitCast; 2975 } 2976 2977 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either 2978 /// const, volatile or both. 2979 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, 2980 QualType DestType) { 2981 if (SrcExpr.isInvalid()) 2982 return; 2983 2984 QualType SrcType = SrcExpr.get()->getType(); 2985 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) || 2986 DestType->isLValueReferenceType())) 2987 return; 2988 2989 QualType TheOffendingSrcType, TheOffendingDestType; 2990 Qualifiers CastAwayQualifiers; 2991 if (CastsAwayConstness(Self, SrcType, DestType, true, false, 2992 &TheOffendingSrcType, &TheOffendingDestType, 2993 &CastAwayQualifiers) != 2994 CastAwayConstnessKind::CACK_Similar) 2995 return; 2996 2997 // FIXME: 'restrict' is not properly handled here. 2998 int qualifiers = -1; 2999 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) { 3000 qualifiers = 0; 3001 } else if (CastAwayQualifiers.hasConst()) { 3002 qualifiers = 1; 3003 } else if (CastAwayQualifiers.hasVolatile()) { 3004 qualifiers = 2; 3005 } 3006 // This is a variant of int **x; const int **y = (const int **)x; 3007 if (qualifiers == -1) 3008 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2) 3009 << SrcType << DestType; 3010 else 3011 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual) 3012 << TheOffendingSrcType << TheOffendingDestType << qualifiers; 3013 } 3014 3015 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 3016 TypeSourceInfo *CastTypeInfo, 3017 SourceLocation RPLoc, 3018 Expr *CastExpr) { 3019 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 3020 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 3021 Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc()); 3022 3023 if (getLangOpts().CPlusPlus) { 3024 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false, 3025 isa<InitListExpr>(CastExpr)); 3026 } else { 3027 Op.CheckCStyleCast(); 3028 } 3029 3030 if (Op.SrcExpr.isInvalid()) 3031 return ExprError(); 3032 3033 // -Wcast-qual 3034 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType); 3035 3036 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType, 3037 Op.ValueKind, Op.Kind, Op.SrcExpr.get(), 3038 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc)); 3039 } 3040 3041 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 3042 QualType Type, 3043 SourceLocation LPLoc, 3044 Expr *CastExpr, 3045 SourceLocation RPLoc) { 3046 assert(LPLoc.isValid() && "List-initialization shouldn't get here."); 3047 CastOperation Op(*this, Type, CastExpr); 3048 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 3049 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc()); 3050 3051 Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false); 3052 if (Op.SrcExpr.isInvalid()) 3053 return ExprError(); 3054 3055 auto *SubExpr = Op.SrcExpr.get(); 3056 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) 3057 SubExpr = BindExpr->getSubExpr(); 3058 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr)) 3059 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc)); 3060 3061 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 3062 Op.ValueKind, CastTypeInfo, Op.Kind, 3063 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc)); 3064 } 3065