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