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

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