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

source code of clang/lib/Sema/SemaCast.cpp