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