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