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