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