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