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