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