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