clang API Documentation

SemaCXXCast.cpp

Go to the documentation of this file.
00001 //===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for C++ named casts.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sema.h"
00015 #include "SemaInit.h"
00016 #include "clang/AST/ExprCXX.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/CXXInheritance.h"
00019 #include "clang/Basic/PartialDiagnostic.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include <set>
00022 using namespace clang;
00023 
00024 enum TryCastResult {
00025   TC_NotApplicable, ///< The cast method is not applicable.
00026   TC_Success,       ///< The cast method is appropriate and successful.
00027   TC_Failed         ///< The cast method is appropriate, but failed. A
00028                     ///< diagnostic has been emitted.
00029 };
00030 
00031 enum CastType {
00032   CT_Const,       ///< const_cast
00033   CT_Static,      ///< static_cast
00034   CT_Reinterpret, ///< reinterpret_cast
00035   CT_Dynamic,     ///< dynamic_cast
00036   CT_CStyle,      ///< (Type)expr
00037   CT_Functional   ///< Type(expr)
00038 };
00039 
00040 static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00041                            const SourceRange &OpRange,
00042                            const SourceRange &DestRange);
00043 static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00044                                  const SourceRange &OpRange,
00045                                  const SourceRange &DestRange,
00046                                  CastExpr::CastKind &Kind);
00047 static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00048                             const SourceRange &OpRange,
00049                             CastExpr::CastKind &Kind,
00050                             CXXBaseSpecifierArray &BasePath);
00051 static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00052                              const SourceRange &OpRange,
00053                              const SourceRange &DestRange,
00054                              CastExpr::CastKind &Kind,
00055                              CXXBaseSpecifierArray &BasePath);
00056 
00057 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
00058 
00059 // The Try functions attempt a specific way of casting. If they succeed, they
00060 // return TC_Success. If their way of casting is not appropriate for the given
00061 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
00062 // to emit if no other way succeeds. If their way of casting is appropriate but
00063 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
00064 // they emit a specialized diagnostic.
00065 // All diagnostics returned by these functions must expect the same three
00066 // arguments:
00067 // %0: Cast Type (a value from the CastType enumeration)
00068 // %1: Source Type
00069 // %2: Destination Type
00070 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
00071                                            QualType DestType, unsigned &msg);
00072 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
00073                                                QualType DestType, bool CStyle,
00074                                                const SourceRange &OpRange,
00075                                                unsigned &msg,
00076                                                CastExpr::CastKind &Kind,
00077                                                CXXBaseSpecifierArray &BasePath);
00078 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
00079                                               QualType DestType, bool CStyle,
00080                                               const SourceRange &OpRange,
00081                                               unsigned &msg,
00082                                               CastExpr::CastKind &Kind,
00083                                               CXXBaseSpecifierArray &BasePath);
00084 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
00085                                        CanQualType DestType, bool CStyle,
00086                                        const SourceRange &OpRange,
00087                                        QualType OrigSrcType,
00088                                        QualType OrigDestType, unsigned &msg,
00089                                        CastExpr::CastKind &Kind,
00090                                        CXXBaseSpecifierArray &BasePath);
00091 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
00092                                                QualType SrcType,
00093                                                QualType DestType,bool CStyle,
00094                                                const SourceRange &OpRange,
00095                                                unsigned &msg,
00096                                                CastExpr::CastKind &Kind,
00097                                                CXXBaseSpecifierArray &BasePath);
00098 
00099 static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
00100                                            QualType DestType, bool CStyle,
00101                                            const SourceRange &OpRange,
00102                                            unsigned &msg,
00103                                            CastExpr::CastKind &Kind);
00104 static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
00105                                    QualType DestType, bool CStyle,
00106                                    const SourceRange &OpRange,
00107                                    unsigned &msg,
00108                                    CastExpr::CastKind &Kind,
00109                                    CXXBaseSpecifierArray &BasePath);
00110 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
00111                                   bool CStyle, unsigned &msg);
00112 static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
00113                                         QualType DestType, bool CStyle,
00114                                         const SourceRange &OpRange,
00115                                         unsigned &msg,
00116                                         CastExpr::CastKind &Kind);
00117 
00118 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
00119 Action::OwningExprResult
00120 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
00121                         SourceLocation LAngleBracketLoc, TypeTy *Ty,
00122                         SourceLocation RAngleBracketLoc,
00123                         SourceLocation LParenLoc, ExprArg E,
00124                         SourceLocation RParenLoc) {
00125   
00126   TypeSourceInfo *DestTInfo;
00127   QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
00128   if (!DestTInfo)
00129     DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
00130 
00131   return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
00132                            SourceRange(LAngleBracketLoc, RAngleBracketLoc),
00133                            SourceRange(LParenLoc, RParenLoc));
00134 }
00135 
00136 Action::OwningExprResult
00137 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
00138                         TypeSourceInfo *DestTInfo, ExprArg E,
00139                         SourceRange AngleBrackets, SourceRange Parens) {
00140   Expr *Ex = E.takeAs<Expr>();
00141   QualType DestType = DestTInfo->getType();
00142 
00143   SourceRange OpRange(OpLoc, Parens.getEnd());
00144   SourceRange DestRange = AngleBrackets;
00145 
00146   // If the type is dependent, we won't do the semantic analysis now.
00147   // FIXME: should we check this in a more fine-grained manner?
00148   bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
00149 
00150   switch (Kind) {
00151   default: assert(0 && "Unknown C++ cast!");
00152 
00153   case tok::kw_const_cast:
00154     if (!TypeDependent)
00155       CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
00156     return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
00157                                                 Ex, DestTInfo, OpLoc));
00158 
00159   case tok::kw_dynamic_cast: {
00160     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00161     CXXBaseSpecifierArray BasePath;
00162     if (!TypeDependent)
00163       CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
00164     return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
00165                                                  Kind, Ex, BasePath, DestTInfo,
00166                                                  OpLoc));
00167   }
00168   case tok::kw_reinterpret_cast: {
00169     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00170     if (!TypeDependent)
00171       CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
00172     return Owned(new (Context) CXXReinterpretCastExpr(
00173                                   DestType.getNonReferenceType(),
00174                                   Kind, Ex, CXXBaseSpecifierArray(), 
00175                                   DestTInfo, OpLoc));
00176   }
00177   case tok::kw_static_cast: {
00178     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00179     CXXBaseSpecifierArray BasePath;
00180     if (!TypeDependent)
00181       CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
00182     
00183     return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
00184                                                  Kind, Ex, BasePath,
00185                                                  DestTInfo, OpLoc));
00186   }
00187   }
00188 
00189   return ExprError();
00190 }
00191 
00192 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
00193 /// this removes one level of indirection from both types, provided that they're
00194 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
00195 /// this one doesn't care if the two pointers-to-member don't point into the
00196 /// same class. This is because CastsAwayConstness doesn't care.
00197 bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
00198   const PointerType *T1PtrType = T1->getAs<PointerType>(),
00199                     *T2PtrType = T2->getAs<PointerType>();
00200   if (T1PtrType && T2PtrType) {
00201     T1 = T1PtrType->getPointeeType();
00202     T2 = T2PtrType->getPointeeType();
00203     return true;
00204   }
00205   const ObjCObjectPointerType *T1ObjCPtrType = 
00206                                             T1->getAs<ObjCObjectPointerType>(),
00207                               *T2ObjCPtrType = 
00208                                             T2->getAs<ObjCObjectPointerType>();
00209   if (T1ObjCPtrType) {
00210     if (T2ObjCPtrType) {
00211       T1 = T1ObjCPtrType->getPointeeType();
00212       T2 = T2ObjCPtrType->getPointeeType();
00213       return true;
00214     }
00215     else if (T2PtrType) {
00216       T1 = T1ObjCPtrType->getPointeeType();
00217       T2 = T2PtrType->getPointeeType();
00218       return true;
00219     }
00220   }
00221   else if (T2ObjCPtrType) {
00222     if (T1PtrType) {
00223       T2 = T2ObjCPtrType->getPointeeType();
00224       T1 = T1PtrType->getPointeeType();
00225       return true;
00226     }
00227   }
00228   
00229   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
00230                           *T2MPType = T2->getAs<MemberPointerType>();
00231   if (T1MPType && T2MPType) {
00232     T1 = T1MPType->getPointeeType();
00233     T2 = T2MPType->getPointeeType();
00234     return true;
00235   }
00236   return false;
00237 }
00238 
00239 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
00240 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
00241 /// the cast checkers.  Both arguments must denote pointer (possibly to member)
00242 /// types.
00243 static bool
00244 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
00245   // Casting away constness is defined in C++ 5.2.11p8 with reference to
00246   // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
00247   // the rules are non-trivial. So first we construct Tcv *...cv* as described
00248   // in C++ 5.2.11p8.
00249   assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
00250          "Source type is not pointer or pointer to member.");
00251   assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
00252          "Destination type is not pointer or pointer to member.");
00253 
00254   QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 
00255            UnwrappedDestType = Self.Context.getCanonicalType(DestType);
00256   llvm::SmallVector<Qualifiers, 8> cv1, cv2;
00257 
00258   // Find the qualifications.
00259   while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
00260     cv1.push_back(UnwrappedSrcType.getQualifiers());
00261     cv2.push_back(UnwrappedDestType.getQualifiers());
00262   }
00263   assert(cv1.size() > 0 && "Must have at least one pointer level.");
00264 
00265   // Construct void pointers with those qualifiers (in reverse order of
00266   // unwrapping, of course).
00267   QualType SrcConstruct = Self.Context.VoidTy;
00268   QualType DestConstruct = Self.Context.VoidTy;
00269   ASTContext &Context = Self.Context;
00270   for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
00271                                                           i2 = cv2.rbegin();
00272        i1 != cv1.rend(); ++i1, ++i2) {
00273     SrcConstruct
00274       = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
00275     DestConstruct
00276       = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
00277   }
00278 
00279   // Test if they're compatible.
00280   return SrcConstruct != DestConstruct &&
00281     !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
00282 }
00283 
00284 /// CheckDynamicCast - Check that a dynamic_cast<DestType>(SrcExpr) is valid.
00285 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
00286 /// checked downcasts in class hierarchies.
00287 static void
00288 CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00289                  const SourceRange &OpRange,
00290                  const SourceRange &DestRange, CastExpr::CastKind &Kind,
00291                  CXXBaseSpecifierArray &BasePath) {
00292   QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
00293   DestType = Self.Context.getCanonicalType(DestType);
00294 
00295   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
00296   //   or "pointer to cv void".
00297 
00298   QualType DestPointee;
00299   const PointerType *DestPointer = DestType->getAs<PointerType>();
00300   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
00301   if (DestPointer) {
00302     DestPointee = DestPointer->getPointeeType();
00303   } else if (DestReference) {
00304     DestPointee = DestReference->getPointeeType();
00305   } else {
00306     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
00307       << OrigDestType << DestRange;
00308     return;
00309   }
00310 
00311   const RecordType *DestRecord = DestPointee->getAs<RecordType>();
00312   if (DestPointee->isVoidType()) {
00313     assert(DestPointer && "Reference to void is not possible");
00314   } else if (DestRecord) {
00315     if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
00316                                Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
00317                                    << DestRange))
00318       return;
00319   } else {
00320     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
00321       << DestPointee.getUnqualifiedType() << DestRange;
00322     return;
00323   }
00324 
00325   // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
00326   //   complete class type, [...]. If T is an lvalue reference type, v shall be
00327   //   an lvalue of a complete class type, [...]. If T is an rvalue reference
00328   //   type, v shall be an expression having a complete effective class type,
00329   //   [...]
00330 
00331   QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
00332   QualType SrcPointee;
00333   if (DestPointer) {
00334     if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
00335       SrcPointee = SrcPointer->getPointeeType();
00336     } else {
00337       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
00338         << OrigSrcType << SrcExpr->getSourceRange();
00339       return;
00340     }
00341   } else if (DestReference->isLValueReferenceType()) {
00342     if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
00343       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
00344         << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
00345     }
00346     SrcPointee = SrcType;
00347   } else {
00348     SrcPointee = SrcType;
00349   }
00350 
00351   const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
00352   if (SrcRecord) {
00353     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
00354                              Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
00355                                    << SrcExpr->getSourceRange()))
00356       return;
00357   } else {
00358     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
00359       << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
00360     return;
00361   }
00362 
00363   assert((DestPointer || DestReference) &&
00364     "Bad destination non-ptr/ref slipped through.");
00365   assert((DestRecord || DestPointee->isVoidType()) &&
00366     "Bad destination pointee slipped through.");
00367   assert(SrcRecord && "Bad source pointee slipped through.");
00368 
00369   // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
00370   if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
00371     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
00372       << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
00373     return;
00374   }
00375 
00376   // C++ 5.2.7p3: If the type of v is the same as the required result type,
00377   //   [except for cv].
00378   if (DestRecord == SrcRecord) {
00379     return;
00380   }
00381 
00382   // C++ 5.2.7p5
00383   // Upcasts are resolved statically.
00384   if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
00385     if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
00386                                            OpRange.getBegin(), OpRange, 
00387                                            &BasePath))
00388         return;
00389         
00390     Kind = CastExpr::CK_DerivedToBase;
00391     return;
00392   }
00393 
00394   // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
00395   const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
00396   assert(SrcDecl && "Definition missing");
00397   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
00398     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
00399       << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
00400   }
00401 
00402   // Done. Everything else is run-time checks.
00403   Kind = CastExpr::CK_Dynamic;
00404 }
00405 
00406 /// CheckConstCast - Check that a const_cast<DestType>(SrcExpr) is valid.
00407 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
00408 /// like this:
00409 /// const char *str = "literal";
00410 /// legacy_function(const_cast<char*>(str));
00411 void
00412 CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00413                const SourceRange &OpRange, const SourceRange &DestRange) {
00414   if (!DestType->isLValueReferenceType())
00415     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
00416 
00417   unsigned msg = diag::err_bad_cxx_cast_generic;
00418   if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
00419       && msg != 0)
00420     Self.Diag(OpRange.getBegin(), msg) << CT_Const
00421       << SrcExpr->getType() << DestType << OpRange;
00422 }
00423 
00424 /// CheckReinterpretCast - Check that a reinterpret_cast<DestType>(SrcExpr) is
00425 /// valid.
00426 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
00427 /// like this:
00428 /// char *bytes = reinterpret_cast<char*>(int_ptr);
00429 void
00430 CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00431                      const SourceRange &OpRange, const SourceRange &DestRange,
00432                      CastExpr::CastKind &Kind) {
00433   if (!DestType->isLValueReferenceType())
00434     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
00435 
00436   unsigned msg = diag::err_bad_cxx_cast_generic;
00437   if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
00438                          msg, Kind)
00439       != TC_Success && msg != 0)
00440     Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
00441       << SrcExpr->getType() << DestType << OpRange;
00442 }
00443 
00444 
00445 /// CheckStaticCast - Check that a static_cast<DestType>(SrcExpr) is valid.
00446 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
00447 /// implicit conversions explicit and getting rid of data loss warnings.
00448 void
00449 CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00450                 const SourceRange &OpRange, CastExpr::CastKind &Kind,
00451                 CXXBaseSpecifierArray &BasePath) {
00452   // This test is outside everything else because it's the only case where
00453   // a non-lvalue-reference target type does not lead to decay.
00454   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
00455   if (DestType->isVoidType()) {
00456     Kind = CastExpr::CK_ToVoid;
00457     return;
00458   }
00459 
00460   if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
00461     Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
00462 
00463   unsigned msg = diag::err_bad_cxx_cast_generic;
00464   if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
00465                     Kind, BasePath) != TC_Success && msg != 0)
00466     Self.Diag(OpRange.getBegin(), msg) << CT_Static
00467       << SrcExpr->getType() << DestType << OpRange;
00468 }
00469 
00470 /// TryStaticCast - Check if a static cast can be performed, and do so if
00471 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
00472 /// and casting away constness.
00473 static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
00474                                    QualType DestType, bool CStyle,
00475                                    const SourceRange &OpRange, unsigned &msg,
00476                                    CastExpr::CastKind &Kind,
00477                                    CXXBaseSpecifierArray &BasePath) {
00478   // The order the tests is not entirely arbitrary. There is one conversion
00479   // that can be handled in two different ways. Given:
00480   // struct A {};
00481   // struct B : public A {
00482   //   B(); B(const A&);
00483   // };
00484   // const A &a = B();
00485   // the cast static_cast<const B&>(a) could be seen as either a static
00486   // reference downcast, or an explicit invocation of the user-defined
00487   // conversion using B's conversion constructor.
00488   // DR 427 specifies that the downcast is to be applied here.
00489 
00490   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
00491   // Done outside this function.
00492 
00493   TryCastResult tcr;
00494 
00495   // C++ 5.2.9p5, reference downcast.
00496   // See the function for details.
00497   // DR 427 specifies that this is to be applied before paragraph 2.
00498   tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
00499                                    msg, Kind, BasePath);
00500   if (tcr != TC_NotApplicable)
00501     return tcr;
00502 
00503   // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
00504   //   reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
00505   tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
00506   if (tcr != TC_NotApplicable) {
00507     Kind = CastExpr::CK_NoOp;
00508     return tcr;
00509   }
00510 
00511   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
00512   //   [...] if the declaration "T t(e);" is well-formed, [...].
00513   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
00514                               Kind);
00515   if (tcr != TC_NotApplicable)
00516     return tcr;
00517   
00518   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
00519   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
00520   // conversions, subject to further restrictions.
00521   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
00522   // of qualification conversions impossible.
00523   // In the CStyle case, the earlier attempt to const_cast should have taken
00524   // care of reverse qualification conversions.
00525 
00526   QualType OrigSrcType = SrcExpr->getType();
00527 
00528   QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
00529 
00530   // Reverse integral promotion/conversion. All such conversions are themselves
00531   // again integral promotions or conversions and are thus already handled by
00532   // p2 (TryDirectInitialization above).
00533   // (Note: any data loss warnings should be suppressed.)
00534   // The exception is the reverse of enum->integer, i.e. integer->enum (and
00535   // enum->enum). See also C++ 5.2.9p7.
00536   // The same goes for reverse floating point promotion/conversion and
00537   // floating-integral conversions. Again, only floating->enum is relevant.
00538   if (DestType->isEnumeralType()) {
00539     if (SrcType->isComplexType() || SrcType->isVectorType()) {
00540       // Fall through - these cannot be converted.
00541     } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
00542       Kind = CastExpr::CK_IntegralCast;
00543       return TC_Success;
00544     }
00545   }
00546 
00547   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
00548   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
00549   tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
00550                                  Kind, BasePath);
00551   if (tcr != TC_NotApplicable)
00552     return tcr;
00553 
00554   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
00555   // conversion. C++ 5.2.9p9 has additional information.
00556   // DR54's access restrictions apply here also.
00557   tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
00558                                      OpRange, msg, Kind, BasePath);
00559   if (tcr != TC_NotApplicable)
00560     return tcr;
00561 
00562   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
00563   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
00564   // just the usual constness stuff.
00565   if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
00566     QualType SrcPointee = SrcPointer->getPointeeType();
00567     if (SrcPointee->isVoidType()) {
00568       if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
00569         QualType DestPointee = DestPointer->getPointeeType();
00570         if (DestPointee->isIncompleteOrObjectType()) {
00571           // This is definitely the intended conversion, but it might fail due
00572           // to a const violation.
00573           if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
00574             msg = diag::err_bad_cxx_cast_const_away;
00575             return TC_Failed;
00576           }
00577           Kind = CastExpr::CK_BitCast;
00578           return TC_Success;
00579         }
00580       }
00581       else if (CStyle && DestType->isObjCObjectPointerType()) {
00582         // allow c-style cast of objective-c pointers as they are pervasive.
00583         Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
00584         return TC_Success;
00585       }
00586       else if (CStyle && DestType->isBlockPointerType()) {
00587         // allow c-style cast of void * to block pointers.
00588         Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
00589         return TC_Success;
00590       }
00591     }
00592   }
00593 
00594   // We tried everything. Everything! Nothing works! :-(
00595   return TC_NotApplicable;
00596 }
00597 
00598 /// Tests whether a conversion according to N2844 is valid.
00599 TryCastResult
00600 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
00601                       unsigned &msg) {
00602   // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
00603   //   reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
00604   const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
00605   if (!R)
00606     return TC_NotApplicable;
00607 
00608   if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
00609     return TC_NotApplicable;
00610 
00611   // Because we try the reference downcast before this function, from now on
00612   // this is the only cast possibility, so we issue an error if we fail now.
00613   // FIXME: Should allow casting away constness if CStyle.
00614   bool DerivedToBase;
00615   if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
00616                                         SrcExpr->getType(), R->getPointeeType(),
00617                                         DerivedToBase) <
00618         Sema::Ref_Compatible_With_Added_Qualification) {
00619     msg = diag::err_bad_lvalue_to_rvalue_cast;
00620     return TC_Failed;
00621   }
00622 
00623   // FIXME: We should probably have an AST node for lvalue-to-rvalue 
00624   // conversions.
00625   return TC_Success;
00626 }
00627 
00628 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
00629 TryCastResult
00630 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
00631                            bool CStyle, const SourceRange &OpRange,
00632                            unsigned &msg, CastExpr::CastKind &Kind,
00633                            CXXBaseSpecifierArray &BasePath) {
00634   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
00635   //   cast to type "reference to cv2 D", where D is a class derived from B,
00636   //   if a valid standard conversion from "pointer to D" to "pointer to B"
00637   //   exists, cv2 >= cv1, and B is not a virtual base class of D.
00638   // In addition, DR54 clarifies that the base must be accessible in the
00639   // current context. Although the wording of DR54 only applies to the pointer
00640   // variant of this rule, the intent is clearly for it to apply to the this
00641   // conversion as well.
00642 
00643   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
00644   if (!DestReference) {
00645     return TC_NotApplicable;
00646   }
00647   bool RValueRef = DestReference->isRValueReferenceType();
00648   if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
00649     // We know the left side is an lvalue reference, so we can suggest a reason.
00650     msg = diag::err_bad_cxx_cast_rvalue;
00651     return TC_NotApplicable;
00652   }
00653 
00654   QualType DestPointee = DestReference->getPointeeType();
00655 
00656   return TryStaticDowncast(Self, 
00657                            Self.Context.getCanonicalType(SrcExpr->getType()), 
00658                            Self.Context.getCanonicalType(DestPointee), CStyle,
00659                            OpRange, SrcExpr->getType(), DestType, msg, Kind,
00660                            BasePath);
00661 }
00662 
00663 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
00664 TryCastResult
00665 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
00666                          bool CStyle, const SourceRange &OpRange,
00667                          unsigned &msg, CastExpr::CastKind &Kind,
00668                          CXXBaseSpecifierArray &BasePath) {
00669   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
00670   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
00671   //   is a class derived from B, if a valid standard conversion from "pointer
00672   //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
00673   //   class of D.
00674   // In addition, DR54 clarifies that the base must be accessible in the
00675   // current context.
00676 
00677   const PointerType *DestPointer = DestType->getAs<PointerType>();
00678   if (!DestPointer) {
00679     return TC_NotApplicable;
00680   }
00681 
00682   const PointerType *SrcPointer = SrcType->getAs<PointerType>();
00683   if (!SrcPointer) {
00684     msg = diag::err_bad_static_cast_pointer_nonpointer;
00685     return TC_NotApplicable;
00686   }
00687 
00688   return TryStaticDowncast(Self, 
00689                    Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
00690                   Self.Context.getCanonicalType(DestPointer->getPointeeType()), 
00691                            CStyle, OpRange, SrcType, DestType, msg, Kind,
00692                            BasePath);
00693 }
00694 
00695 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
00696 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
00697 /// DestType is possible and allowed.
00698 TryCastResult
00699 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
00700                   bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
00701                   QualType OrigDestType, unsigned &msg, 
00702                   CastExpr::CastKind &Kind, CXXBaseSpecifierArray &BasePath) {
00703   // We can only work with complete types. But don't complain if it doesn't work
00704   if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
00705       Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
00706     return TC_NotApplicable;
00707 
00708   // Downcast can only happen in class hierarchies, so we need classes.
00709   if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
00710     return TC_NotApplicable;
00711   }
00712 
00713   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
00714                      /*DetectVirtual=*/true);
00715   if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
00716     return TC_NotApplicable;
00717   }
00718 
00719   // Target type does derive from source type. Now we're serious. If an error
00720   // appears now, it's not ignored.
00721   // This may not be entirely in line with the standard. Take for example:
00722   // struct A {};
00723   // struct B : virtual A {
00724   //   B(A&);
00725   // };
00726   //
00727   // void f()
00728   // {
00729   //   (void)static_cast<const B&>(*((A*)0));
00730   // }
00731   // As far as the standard is concerned, p5 does not apply (A is virtual), so
00732   // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
00733   // However, both GCC and Comeau reject this example, and accepting it would
00734   // mean more complex code if we're to preserve the nice error message.
00735   // FIXME: Being 100% compliant here would be nice to have.
00736 
00737   // Must preserve cv, as always, unless we're in C-style mode.
00738   if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
00739     msg = diag::err_bad_cxx_cast_const_away;
00740     return TC_Failed;
00741   }
00742 
00743   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
00744     // This code is analoguous to that in CheckDerivedToBaseConversion, except
00745     // that it builds the paths in reverse order.
00746     // To sum up: record all paths to the base and build a nice string from
00747     // them. Use it to spice up the error message.
00748     if (!Paths.isRecordingPaths()) {
00749       Paths.clear();
00750       Paths.setRecordingPaths(true);
00751       Self.IsDerivedFrom(DestType, SrcType, Paths);
00752     }
00753     std::string PathDisplayStr;
00754     std::set<unsigned> DisplayedPaths;
00755     for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
00756          PI != PE; ++PI) {
00757       if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
00758         // We haven't displayed a path to this particular base
00759         // class subobject yet.
00760         PathDisplayStr += "\n    ";
00761         for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
00762                                                  EE = PI->rend();
00763              EI != EE; ++EI)
00764           PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
00765         PathDisplayStr += QualType(DestType).getAsString();
00766       }
00767     }
00768 
00769     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
00770       << QualType(SrcType).getUnqualifiedType() 
00771       << QualType(DestType).getUnqualifiedType()
00772       << PathDisplayStr << OpRange;
00773     msg = 0;
00774     return TC_Failed;
00775   }
00776 
00777   if (Paths.getDetectedVirtual() != 0) {
00778     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
00779     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
00780       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
00781     msg = 0;
00782     return TC_Failed;
00783   }
00784 
00785   if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
00786                                            SrcType, DestType,
00787                                            Paths.front(),
00788                                 diag::err_downcast_from_inaccessible_base)) {
00789     msg = 0;
00790     return TC_Failed;
00791   }
00792 
00793   Self.BuildBasePathArray(Paths, BasePath);
00794   Kind = CastExpr::CK_BaseToDerived;
00795   return TC_Success;
00796 }
00797 
00798 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
00799 /// C++ 5.2.9p9 is valid:
00800 ///
00801 ///   An rvalue of type "pointer to member of D of type cv1 T" can be
00802 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
00803 ///   where B is a base class of D [...].
00804 ///
00805 TryCastResult
00806 TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType, 
00807                              QualType DestType, bool CStyle, 
00808                              const SourceRange &OpRange,
00809                              unsigned &msg, CastExpr::CastKind &Kind,
00810                              CXXBaseSpecifierArray &BasePath) {
00811   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
00812   if (!DestMemPtr)
00813     return TC_NotApplicable;
00814 
00815   bool WasOverloadedFunction = false;
00816   DeclAccessPair FoundOverload;
00817   if (SrcExpr->getType() == Self.Context.OverloadTy) {
00818     if (FunctionDecl *Fn
00819           = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
00820                                                     FoundOverload)) {
00821       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
00822       SrcType = Self.Context.getMemberPointerType(Fn->getType(),
00823                       Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
00824       WasOverloadedFunction = true;
00825     }
00826   }
00827   
00828   const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
00829   if (!SrcMemPtr) {
00830     msg = diag::err_bad_static_cast_member_pointer_nonmp;
00831     return TC_NotApplicable;
00832   }
00833 
00834   // T == T, modulo cv
00835   if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
00836                                            DestMemPtr->getPointeeType()))
00837     return TC_NotApplicable;
00838 
00839   // B base of D
00840   QualType SrcClass(SrcMemPtr->getClass(), 0);
00841   QualType DestClass(DestMemPtr->getClass(), 0);
00842   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
00843                   /*DetectVirtual=*/true);
00844   if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
00845     return TC_NotApplicable;
00846   }
00847 
00848   // B is a base of D. But is it an allowed base? If not, it's a hard error.
00849   if (Paths.isAmbiguous(DestClass)) {
00850     Paths.clear();
00851     Paths.setRecordingPaths(true);
00852     bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
00853     assert(StillOkay);
00854     StillOkay = StillOkay;
00855     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
00856     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
00857       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
00858     msg = 0;
00859     return TC_Failed;
00860   }
00861 
00862   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
00863     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
00864       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
00865     msg = 0;
00866     return TC_Failed;
00867   }
00868 
00869   if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
00870                                            DestType, SrcType,
00871                                            Paths.front(),
00872                                      diag::err_upcast_to_inaccessible_base)) {
00873     msg = 0;
00874     return TC_Failed;
00875   }
00876 
00877   if (WasOverloadedFunction) {
00878     // Resolve the address of the overloaded function again, this time
00879     // allowing complaints if something goes wrong.
00880     FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr, 
00881                                                                DestType, 
00882                                                                true,
00883                                                                FoundOverload);
00884     if (!Fn) {
00885       msg = 0;
00886       return TC_Failed;
00887     }
00888 
00889     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
00890     if (!SrcExpr) {
00891       msg = 0;
00892       return TC_Failed;
00893     }
00894   }
00895 
00896   Self.BuildBasePathArray(Paths, BasePath);
00897   Kind = CastExpr::CK_DerivedToBaseMemberPointer;
00898   return TC_Success;
00899 }
00900 
00901 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
00902 /// is valid:
00903 ///
00904 ///   An expression e can be explicitly converted to a type T using a
00905 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
00906 TryCastResult
00907 TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
00908                       bool CStyle, const SourceRange &OpRange, unsigned &msg,
00909                       CastExpr::CastKind &Kind) {
00910   if (DestType->isRecordType()) {
00911     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
00912                                  diag::err_bad_dynamic_cast_incomplete)) {
00913       msg = 0;
00914       return TC_Failed;
00915     }
00916   }
00917   
00918   // At this point of CheckStaticCast, if the destination is a reference,
00919   // this has to work. There is no other way that works.
00920   // On the other hand, if we're checking a C-style cast, we've still got
00921   // the reinterpret_cast way.
00922   InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
00923   InitializationKind InitKind
00924     = InitializationKind::CreateCast(/*FIXME:*/OpRange, 
00925                                                                CStyle);    
00926   InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
00927   if (InitSeq.getKind() == InitializationSequence::FailedSequence && 
00928       (CStyle || !DestType->isReferenceType()))
00929     return TC_NotApplicable;
00930     
00931   Sema::OwningExprResult Result
00932     = InitSeq.Perform(Self, Entity, InitKind,
00933                       Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
00934   if (Result.isInvalid()) {
00935     msg = 0;
00936     return TC_Failed;
00937   }
00938   
00939   if (InitSeq.isConstructorInitialization())
00940     Kind = CastExpr::CK_ConstructorConversion;
00941   else
00942     Kind = CastExpr::CK_NoOp;
00943   
00944   SrcExpr = Result.takeAs<Expr>();
00945   return TC_Success;
00946 }
00947 
00948 /// TryConstCast - See if a const_cast from source to destination is allowed,
00949 /// and perform it if it is.
00950 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
00951                                   bool CStyle, unsigned &msg) {
00952   DestType = Self.Context.getCanonicalType(DestType);
00953   QualType SrcType = SrcExpr->getType();
00954   if (const LValueReferenceType *DestTypeTmp =
00955         DestType->getAs<LValueReferenceType>()) {
00956     if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
00957       // Cannot const_cast non-lvalue to lvalue reference type. But if this
00958       // is C-style, static_cast might find a way, so we simply suggest a
00959       // message and tell the parent to keep searching.
00960       msg = diag::err_bad_cxx_cast_rvalue;
00961       return TC_NotApplicable;
00962     }
00963 
00964     // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
00965     //   [...] if a pointer to T1 can be [cast] to the type pointer to T2.
00966     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
00967     SrcType = Self.Context.getPointerType(SrcType);
00968   }
00969 
00970   // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
00971   //   the rules for const_cast are the same as those used for pointers.
00972 
00973   if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
00974     // Cannot cast to non-pointer, non-reference type. Note that, if DestType
00975     // was a reference type, we converted it to a pointer above.
00976     // The status of rvalue references isn't entirely clear, but it looks like
00977     // conversion to them is simply invalid.
00978     // C++ 5.2.11p3: For two pointer types [...]
00979     if (!CStyle)
00980       msg = diag::err_bad_const_cast_dest;
00981     return TC_NotApplicable;
00982   }
00983   if (DestType->isFunctionPointerType() ||
00984       DestType->isMemberFunctionPointerType()) {
00985     // Cannot cast direct function pointers.
00986     // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
00987     // T is the ultimate pointee of source and target type.
00988     if (!CStyle)
00989       msg = diag::err_bad_const_cast_dest;
00990     return TC_NotApplicable;
00991   }
00992   SrcType = Self.Context.getCanonicalType(SrcType);
00993 
00994   // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
00995   // completely equal.
00996   // FIXME: const_cast should probably not be able to convert between pointers
00997   // to different address spaces.
00998   // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
00999   // in multi-level pointers may change, but the level count must be the same,
01000   // as must be the final pointee type.
01001   while (SrcType != DestType &&
01002          Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
01003     Qualifiers Quals;
01004     SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
01005     DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
01006   }
01007 
01008   // Since we're dealing in canonical types, the remainder must be the same.
01009   if (SrcType != DestType)
01010     return TC_NotApplicable;
01011 
01012   return TC_Success;
01013 }
01014 
01015 static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
01016                                         QualType DestType, bool CStyle,
01017                                         const SourceRange &OpRange,
01018                                         unsigned &msg,
01019                                         CastExpr::CastKind &Kind) {
01020   DestType = Self.Context.getCanonicalType(DestType);
01021   QualType SrcType = SrcExpr->getType();
01022   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
01023     bool LValue = DestTypeTmp->isLValueReferenceType();
01024     if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
01025       // Cannot cast non-lvalue to reference type. See the similar comment in
01026       // const_cast.
01027       msg = diag::err_bad_cxx_cast_rvalue;
01028       return TC_NotApplicable;
01029     }
01030 
01031     // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
01032     //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
01033     //   built-in & and * operators.
01034     // This code does this transformation for the checked types.
01035     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
01036     SrcType = Self.Context.getPointerType(SrcType);
01037   }
01038 
01039   // Canonicalize source for comparison.
01040   SrcType = Self.Context.getCanonicalType(SrcType);
01041 
01042   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
01043                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
01044   if (DestMemPtr && SrcMemPtr) {
01045     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
01046     //   can be explicitly converted to an rvalue of type "pointer to member
01047     //   of Y of type T2" if T1 and T2 are both function types or both object
01048     //   types.
01049     if (DestMemPtr->getPointeeType()->isFunctionType() !=
01050         SrcMemPtr->getPointeeType()->isFunctionType())
01051       return TC_NotApplicable;
01052 
01053     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
01054     //   constness.
01055     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
01056     // we accept it.
01057     if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
01058       msg = diag::err_bad_cxx_cast_const_away;
01059       return TC_Failed;
01060     }
01061 
01062     // A valid member pointer cast.
01063     Kind = CastExpr::CK_BitCast;
01064     return TC_Success;
01065   }
01066 
01067   // See below for the enumeral issue.
01068   if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
01069       !DestType->isEnumeralType()) {
01070     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
01071     //   type large enough to hold it. A value of std::nullptr_t can be
01072     //   converted to an integral type; the conversion has the same meaning
01073     //   and validity as a conversion of (void*)0 to the integral type.
01074     if (Self.Context.getTypeSize(SrcType) >
01075         Self.Context.getTypeSize(DestType)) {
01076       msg = diag::err_bad_reinterpret_cast_small_int;
01077       return TC_Failed;
01078     }
01079     Kind = CastExpr::CK_PointerToIntegral;
01080     return TC_Success;
01081   }
01082 
01083   bool destIsVector = DestType->isVectorType();
01084   bool srcIsVector = SrcType->isVectorType();
01085   if (srcIsVector || destIsVector) {
01086     bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
01087     bool destIsScalar = 
01088       DestType->isIntegralType() && !DestType->isEnumeralType();
01089     
01090     // Check if this is a cast between a vector and something else.
01091     if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
01092         !(srcIsVector && destIsVector))
01093       return TC_NotApplicable;
01094 
01095     // If both types have the same size, we can successfully cast.
01096     if (Self.Context.getTypeSize(SrcType)
01097           == Self.Context.getTypeSize(DestType)) {
01098       Kind = CastExpr::CK_BitCast;
01099       return TC_Success;
01100     }
01101     
01102     if (destIsScalar)
01103       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
01104     else if (srcIsScalar)
01105       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
01106     else
01107       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
01108     
01109     return TC_Failed;
01110   }
01111   
01112   bool destIsPtr = DestType->isAnyPointerType();
01113   bool srcIsPtr = SrcType->isAnyPointerType();
01114   if (!destIsPtr && !srcIsPtr) {
01115     // Except for std::nullptr_t->integer and lvalue->reference, which are
01116     // handled above, at least one of the two arguments must be a pointer.
01117     return TC_NotApplicable;
01118   }
01119 
01120   if (SrcType == DestType) {
01121     // C++ 5.2.10p2 has a note that mentions that, subject to all other
01122     // restrictions, a cast to the same type is allowed. The intent is not
01123     // entirely clear here, since all other paragraphs explicitly forbid casts
01124     // to the same type. However, the behavior of compilers is pretty consistent
01125     // on this point: allow same-type conversion if the involved types are
01126     // pointers, disallow otherwise.
01127     Kind = CastExpr::CK_NoOp;
01128     return TC_Success;
01129   }
01130 
01131   // Note: Clang treats enumeration types as integral types. If this is ever
01132   // changed for C++, the additional check here will be redundant.
01133   if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
01134     assert(srcIsPtr && "One type must be a pointer");
01135     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
01136     //   type large enough to hold it.
01137     if (Self.Context.getTypeSize(SrcType) >
01138         Self.Context.getTypeSize(DestType)) {
01139       msg = diag::err_bad_reinterpret_cast_small_int;
01140       return TC_Failed;
01141     }
01142     Kind = CastExpr::CK_PointerToIntegral;
01143     return TC_Success;
01144   }
01145 
01146   if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
01147     assert(destIsPtr && "One type must be a pointer");
01148     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
01149     //   converted to a pointer.
01150     Kind = CastExpr::CK_IntegralToPointer;
01151     return TC_Success;
01152   }
01153 
01154   if (!destIsPtr || !srcIsPtr) {
01155     // With the valid non-pointer conversions out of the way, we can be even
01156     // more stringent.
01157     return TC_NotApplicable;
01158   }
01159 
01160   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
01161   // The C-style cast operator can.
01162   if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
01163     msg = diag::err_bad_cxx_cast_const_away;
01164     return TC_Failed;
01165   }
01166   if (CStyle && DestType->isObjCObjectPointerType()) {
01167     Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
01168     return TC_Success;
01169   }
01170   
01171   // Not casting away constness, so the only remaining check is for compatible
01172   // pointer categories.
01173   Kind = CastExpr::CK_BitCast;
01174 
01175   if (SrcType->isFunctionPointerType()) {
01176     if (DestType->isFunctionPointerType()) {
01177       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
01178       // a pointer to a function of a different type.
01179       return TC_Success;
01180     }
01181 
01182     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
01183     //   an object type or vice versa is conditionally-supported.
01184     // Compilers support it in C++03 too, though, because it's necessary for
01185     // casting the return value of dlsym() and GetProcAddress().
01186     // FIXME: Conditionally-supported behavior should be configurable in the
01187     // TargetInfo or similar.
01188     if (!Self.getLangOptions().CPlusPlus0x)
01189       Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
01190     return TC_Success;
01191   }
01192 
01193   if (DestType->isFunctionPointerType()) {
01194     // See above.
01195     if (!Self.getLangOptions().CPlusPlus0x)
01196       Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
01197     return TC_Success;
01198   }
01199 
01200   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
01201   //   a pointer to an object of different type.
01202   // Void pointers are not specified, but supported by every compiler out there.
01203   // So we finish by allowing everything that remains - it's got to be two
01204   // object pointers.
01205   return TC_Success;
01206 }
01207 
01208 bool 
01209 Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
01210                          CastExpr::CastKind &Kind, 
01211                          CXXBaseSpecifierArray &BasePath,
01212                          bool FunctionalStyle) {
01213   // This test is outside everything else because it's the only case where
01214   // a non-lvalue-reference target type does not lead to decay.
01215   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
01216   if (CastTy->isVoidType()) {
01217     Kind = CastExpr::CK_ToVoid;
01218     return false;
01219   }
01220 
01221   // If the type is dependent, we won't do any other semantic analysis now.
01222   if (CastTy->isDependentType() || CastExpr->isTypeDependent())
01223     return false;
01224 
01225   if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
01226     DefaultFunctionArrayLvalueConversion(CastExpr);
01227 
01228   // C++ [expr.cast]p5: The conversions performed by
01229   //   - a const_cast,
01230   //   - a static_cast,
01231   //   - a static_cast followed by a const_cast,
01232   //   - a reinterpret_cast, or
01233   //   - a reinterpret_cast followed by a const_cast,
01234   //   can be performed using the cast notation of explicit type conversion.
01235   //   [...] If a conversion can be interpreted in more than one of the ways
01236   //   listed above, the interpretation that appears first in the list is used,
01237   //   even if a cast resulting from that interpretation is ill-formed.
01238   // In plain language, this means trying a const_cast ...
01239   unsigned msg = diag::err_bad_cxx_cast_generic;
01240   TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
01241                                    msg);
01242   if (tcr == TC_Success)
01243     Kind = CastExpr::CK_NoOp;
01244 
01245   if (tcr == TC_NotApplicable) {
01246     // ... or if that is not possible, a static_cast, ignoring const, ...
01247     tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
01248                         BasePath);
01249     if (tcr == TC_NotApplicable) {
01250       // ... and finally a reinterpret_cast, ignoring const.
01251       tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
01252                                Kind);
01253     }
01254   }
01255 
01256   if (tcr != TC_Success && msg != 0)
01257     Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
01258       << CastExpr->getType() << CastTy << R;
01259 
01260   return tcr != TC_Success;
01261 }