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