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