clang API Documentation
00001 //===--- SemaCXXCast.cpp - Semantic Analysis for 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 casts. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "clang/Sema/Initialization.h" 00016 #include "clang/AST/ExprCXX.h" 00017 #include "clang/AST/ExprObjC.h" 00018 #include "clang/AST/ASTContext.h" 00019 #include "clang/AST/CXXInheritance.h" 00020 #include "clang/Basic/PartialDiagnostic.h" 00021 #include "llvm/ADT/SmallVector.h" 00022 #include <set> 00023 using namespace clang; 00024 00025 00026 00027 enum TryCastResult { 00028 TC_NotApplicable, ///< The cast method is not applicable. 00029 TC_Success, ///< The cast method is appropriate and successful. 00030 TC_Failed ///< The cast method is appropriate, but failed. A 00031 ///< diagnostic has been emitted. 00032 }; 00033 00034 enum CastType { 00035 CT_Const, ///< const_cast 00036 CT_Static, ///< static_cast 00037 CT_Reinterpret, ///< reinterpret_cast 00038 CT_Dynamic, ///< dynamic_cast 00039 CT_CStyle, ///< (Type)expr 00040 CT_Functional ///< Type(expr) 00041 }; 00042 00043 namespace { 00044 struct CastOperation { 00045 CastOperation(Sema &S, QualType destType, ExprResult src) 00046 : Self(S), SrcExpr(src), DestType(destType), 00047 ResultType(destType.getNonLValueExprType(S.Context)), 00048 ValueKind(Expr::getValueKindForType(destType)), 00049 Kind(CK_Dependent), IsARCUnbridgedCast(false) { 00050 00051 if (const BuiltinType *placeholder = 00052 src.get()->getType()->getAsPlaceholderType()) { 00053 PlaceholderKind = placeholder->getKind(); 00054 } else { 00055 PlaceholderKind = (BuiltinType::Kind) 0; 00056 } 00057 } 00058 00059 Sema &Self; 00060 ExprResult SrcExpr; 00061 QualType DestType; 00062 QualType ResultType; 00063 ExprValueKind ValueKind; 00064 CastKind Kind; 00065 bool IsARCUnbridgedCast; 00066 BuiltinType::Kind PlaceholderKind; 00067 CXXCastPath BasePath; 00068 00069 SourceRange OpRange; 00070 SourceRange DestRange; 00071 00072 // Top-level semantics-checking routines. 00073 void CheckConstCast(); 00074 void CheckReinterpretCast(); 00075 void CheckStaticCast(); 00076 void CheckDynamicCast(); 00077 void CheckCXXCStyleCast(bool FunctionalCast); 00078 void CheckCStyleCast(); 00079 00080 // Internal convenience methods. 00081 00082 /// Try to handle the given placeholder expression kind. Return 00083 /// true if the source expression has the appropriate placeholder 00084 /// kind. A placeholder can only be claimed once. 00085 bool claimPlaceholder(BuiltinType::Kind K) { 00086 if (PlaceholderKind != K) return false; 00087 00088 PlaceholderKind = (BuiltinType::Kind) 0; 00089 return true; 00090 } 00091 00092 bool isPlaceholder() const { 00093 return PlaceholderKind != 0; 00094 } 00095 bool isPlaceholder(BuiltinType::Kind K) const { 00096 return PlaceholderKind == K; 00097 } 00098 00099 void checkCastAlign() { 00100 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange); 00101 } 00102 00103 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) { 00104 Expr *src = SrcExpr.get(); 00105 Self.CheckObjCARCConversion(OpRange, DestType, src, CCK); 00106 SrcExpr = src; 00107 } 00108 00109 /// Check for and handle non-overload placeholder expressions. 00110 void checkNonOverloadPlaceholders() { 00111 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload)) 00112 return; 00113 00114 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take()); 00115 if (SrcExpr.isInvalid()) 00116 return; 00117 PlaceholderKind = (BuiltinType::Kind) 0; 00118 } 00119 }; 00120 } 00121 00122 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 00123 bool CheckCVR, bool CheckObjCLifetime); 00124 00125 // The Try functions attempt a specific way of casting. If they succeed, they 00126 // return TC_Success. If their way of casting is not appropriate for the given 00127 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic 00128 // to emit if no other way succeeds. If their way of casting is appropriate but 00129 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if 00130 // they emit a specialized diagnostic. 00131 // All diagnostics returned by these functions must expect the same three 00132 // arguments: 00133 // %0: Cast Type (a value from the CastType enumeration) 00134 // %1: Source Type 00135 // %2: Destination Type 00136 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, 00137 QualType DestType, bool CStyle, 00138 CastKind &Kind, 00139 CXXCastPath &BasePath, 00140 unsigned &msg); 00141 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, 00142 QualType DestType, bool CStyle, 00143 const SourceRange &OpRange, 00144 unsigned &msg, 00145 CastKind &Kind, 00146 CXXCastPath &BasePath); 00147 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, 00148 QualType DestType, bool CStyle, 00149 const SourceRange &OpRange, 00150 unsigned &msg, 00151 CastKind &Kind, 00152 CXXCastPath &BasePath); 00153 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, 00154 CanQualType DestType, bool CStyle, 00155 const SourceRange &OpRange, 00156 QualType OrigSrcType, 00157 QualType OrigDestType, unsigned &msg, 00158 CastKind &Kind, 00159 CXXCastPath &BasePath); 00160 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, 00161 QualType SrcType, 00162 QualType DestType,bool CStyle, 00163 const SourceRange &OpRange, 00164 unsigned &msg, 00165 CastKind &Kind, 00166 CXXCastPath &BasePath); 00167 00168 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, 00169 QualType DestType, 00170 Sema::CheckedConversionKind CCK, 00171 const SourceRange &OpRange, 00172 unsigned &msg, 00173 CastKind &Kind); 00174 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 00175 QualType DestType, 00176 Sema::CheckedConversionKind CCK, 00177 const SourceRange &OpRange, 00178 unsigned &msg, 00179 CastKind &Kind, 00180 CXXCastPath &BasePath); 00181 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 00182 bool CStyle, unsigned &msg); 00183 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 00184 QualType DestType, bool CStyle, 00185 const SourceRange &OpRange, 00186 unsigned &msg, 00187 CastKind &Kind); 00188 00189 00190 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 00191 ExprResult 00192 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 00193 SourceLocation LAngleBracketLoc, Declarator &D, 00194 SourceLocation RAngleBracketLoc, 00195 SourceLocation LParenLoc, Expr *E, 00196 SourceLocation RParenLoc) { 00197 00198 assert(!D.isInvalidType()); 00199 00200 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType()); 00201 if (D.isInvalidType()) 00202 return ExprError(); 00203 00204 if (getLangOptions().CPlusPlus) { 00205 // Check that there are no default arguments (C++ only). 00206 CheckExtraCXXDefaultArguments(D); 00207 } 00208 00209 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E), 00210 SourceRange(LAngleBracketLoc, RAngleBracketLoc), 00211 SourceRange(LParenLoc, RParenLoc)); 00212 } 00213 00214 ExprResult 00215 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 00216 TypeSourceInfo *DestTInfo, Expr *E, 00217 SourceRange AngleBrackets, SourceRange Parens) { 00218 ExprResult Ex = Owned(E); 00219 QualType DestType = DestTInfo->getType(); 00220 00221 // If the type is dependent, we won't do the semantic analysis now. 00222 // FIXME: should we check this in a more fine-grained manner? 00223 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent(); 00224 00225 CastOperation Op(*this, DestType, E); 00226 Op.OpRange = SourceRange(OpLoc, Parens.getEnd()); 00227 Op.DestRange = AngleBrackets; 00228 00229 switch (Kind) { 00230 default: llvm_unreachable("Unknown C++ cast!"); 00231 00232 case tok::kw_const_cast: 00233 if (!TypeDependent) { 00234 Op.CheckConstCast(); 00235 if (Op.SrcExpr.isInvalid()) 00236 return ExprError(); 00237 } 00238 return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.ValueKind, 00239 Op.SrcExpr.take(), DestTInfo, OpLoc, 00240 Parens.getEnd())); 00241 00242 case tok::kw_dynamic_cast: { 00243 if (!TypeDependent) { 00244 Op.CheckDynamicCast(); 00245 if (Op.SrcExpr.isInvalid()) 00246 return ExprError(); 00247 } 00248 return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType, 00249 Op.ValueKind, Op.Kind, 00250 Op.SrcExpr.take(), &Op.BasePath, 00251 DestTInfo, OpLoc, Parens.getEnd())); 00252 } 00253 case tok::kw_reinterpret_cast: { 00254 if (!TypeDependent) { 00255 Op.CheckReinterpretCast(); 00256 if (Op.SrcExpr.isInvalid()) 00257 return ExprError(); 00258 } 00259 return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType, 00260 Op.ValueKind, Op.Kind, 00261 Op.SrcExpr.take(), 0, 00262 DestTInfo, OpLoc, 00263 Parens.getEnd())); 00264 } 00265 case tok::kw_static_cast: { 00266 if (!TypeDependent) { 00267 Op.CheckStaticCast(); 00268 if (Op.SrcExpr.isInvalid()) 00269 return ExprError(); 00270 } 00271 00272 return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.ValueKind, 00273 Op.Kind, Op.SrcExpr.take(), 00274 &Op.BasePath, DestTInfo, OpLoc, 00275 Parens.getEnd())); 00276 } 00277 } 00278 00279 return ExprError(); 00280 } 00281 00282 /// Try to diagnose a failed overloaded cast. Returns true if 00283 /// diagnostics were emitted. 00284 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, 00285 SourceRange range, Expr *src, 00286 QualType destType) { 00287 switch (CT) { 00288 // These cast kinds don't consider user-defined conversions. 00289 case CT_Const: 00290 case CT_Reinterpret: 00291 case CT_Dynamic: 00292 return false; 00293 00294 // These do. 00295 case CT_Static: 00296 case CT_CStyle: 00297 case CT_Functional: 00298 break; 00299 } 00300 00301 QualType srcType = src->getType(); 00302 if (!destType->isRecordType() && !srcType->isRecordType()) 00303 return false; 00304 00305 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType); 00306 InitializationKind initKind 00307 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(), 00308 range) 00309 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range) 00310 : InitializationKind::CreateCast(/*type range?*/ range); 00311 InitializationSequence sequence(S, entity, initKind, &src, 1); 00312 00313 assert(sequence.Failed() && "initialization succeeded on second try?"); 00314 switch (sequence.getFailureKind()) { 00315 default: return false; 00316 00317 case InitializationSequence::FK_ConstructorOverloadFailed: 00318 case InitializationSequence::FK_UserConversionOverloadFailed: 00319 break; 00320 } 00321 00322 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet(); 00323 00324 unsigned msg = 0; 00325 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates; 00326 00327 switch (sequence.getFailedOverloadResult()) { 00328 case OR_Success: llvm_unreachable("successful failed overload"); 00329 return false; 00330 case OR_No_Viable_Function: 00331 if (candidates.empty()) 00332 msg = diag::err_ovl_no_conversion_in_cast; 00333 else 00334 msg = diag::err_ovl_no_viable_conversion_in_cast; 00335 howManyCandidates = OCD_AllCandidates; 00336 break; 00337 00338 case OR_Ambiguous: 00339 msg = diag::err_ovl_ambiguous_conversion_in_cast; 00340 howManyCandidates = OCD_ViableCandidates; 00341 break; 00342 00343 case OR_Deleted: 00344 msg = diag::err_ovl_deleted_conversion_in_cast; 00345 howManyCandidates = OCD_ViableCandidates; 00346 break; 00347 } 00348 00349 S.Diag(range.getBegin(), msg) 00350 << CT << srcType << destType 00351 << range << src->getSourceRange(); 00352 00353 candidates.NoteCandidates(S, howManyCandidates, &src, 1); 00354 00355 return true; 00356 } 00357 00358 /// Diagnose a failed cast. 00359 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, 00360 SourceRange opRange, Expr *src, QualType destType) { 00361 if (src->getType() == S.Context.BoundMemberTy) { 00362 (void) S.CheckPlaceholderExpr(src); // will always fail 00363 return; 00364 } 00365 00366 if (msg == diag::err_bad_cxx_cast_generic && 00367 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType)) 00368 return; 00369 00370 S.Diag(opRange.getBegin(), msg) << castType 00371 << src->getType() << destType << opRange << src->getSourceRange(); 00372 } 00373 00374 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes, 00375 /// this removes one level of indirection from both types, provided that they're 00376 /// the same kind of pointer (plain or to-member). Unlike the Sema function, 00377 /// this one doesn't care if the two pointers-to-member don't point into the 00378 /// same class. This is because CastsAwayConstness doesn't care. 00379 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) { 00380 const PointerType *T1PtrType = T1->getAs<PointerType>(), 00381 *T2PtrType = T2->getAs<PointerType>(); 00382 if (T1PtrType && T2PtrType) { 00383 T1 = T1PtrType->getPointeeType(); 00384 T2 = T2PtrType->getPointeeType(); 00385 return true; 00386 } 00387 const ObjCObjectPointerType *T1ObjCPtrType = 00388 T1->getAs<ObjCObjectPointerType>(), 00389 *T2ObjCPtrType = 00390 T2->getAs<ObjCObjectPointerType>(); 00391 if (T1ObjCPtrType) { 00392 if (T2ObjCPtrType) { 00393 T1 = T1ObjCPtrType->getPointeeType(); 00394 T2 = T2ObjCPtrType->getPointeeType(); 00395 return true; 00396 } 00397 else if (T2PtrType) { 00398 T1 = T1ObjCPtrType->getPointeeType(); 00399 T2 = T2PtrType->getPointeeType(); 00400 return true; 00401 } 00402 } 00403 else if (T2ObjCPtrType) { 00404 if (T1PtrType) { 00405 T2 = T2ObjCPtrType->getPointeeType(); 00406 T1 = T1PtrType->getPointeeType(); 00407 return true; 00408 } 00409 } 00410 00411 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 00412 *T2MPType = T2->getAs<MemberPointerType>(); 00413 if (T1MPType && T2MPType) { 00414 T1 = T1MPType->getPointeeType(); 00415 T2 = T2MPType->getPointeeType(); 00416 return true; 00417 } 00418 00419 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(), 00420 *T2BPType = T2->getAs<BlockPointerType>(); 00421 if (T1BPType && T2BPType) { 00422 T1 = T1BPType->getPointeeType(); 00423 T2 = T2BPType->getPointeeType(); 00424 return true; 00425 } 00426 00427 return false; 00428 } 00429 00430 /// CastsAwayConstness - Check if the pointer conversion from SrcType to 00431 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by 00432 /// the cast checkers. Both arguments must denote pointer (possibly to member) 00433 /// types. 00434 /// 00435 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers. 00436 /// 00437 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers. 00438 static bool 00439 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, 00440 bool CheckCVR, bool CheckObjCLifetime) { 00441 // If the only checking we care about is for Objective-C lifetime qualifiers, 00442 // and we're not in ARC mode, there's nothing to check. 00443 if (!CheckCVR && CheckObjCLifetime && 00444 !Self.Context.getLangOptions().ObjCAutoRefCount) 00445 return false; 00446 00447 // Casting away constness is defined in C++ 5.2.11p8 with reference to 00448 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since 00449 // the rules are non-trivial. So first we construct Tcv *...cv* as described 00450 // in C++ 5.2.11p8. 00451 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || 00452 SrcType->isBlockPointerType()) && 00453 "Source type is not pointer or pointer to member."); 00454 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() || 00455 DestType->isBlockPointerType()) && 00456 "Destination type is not pointer or pointer to member."); 00457 00458 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 00459 UnwrappedDestType = Self.Context.getCanonicalType(DestType); 00460 SmallVector<Qualifiers, 8> cv1, cv2; 00461 00462 // Find the qualifiers. We only care about cvr-qualifiers for the 00463 // purpose of this check, because other qualifiers (address spaces, 00464 // Objective-C GC, etc.) are part of the type's identity. 00465 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 00466 // Determine the relevant qualifiers at this level. 00467 Qualifiers SrcQuals, DestQuals; 00468 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals); 00469 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals); 00470 00471 Qualifiers RetainedSrcQuals, RetainedDestQuals; 00472 if (CheckCVR) { 00473 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers()); 00474 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers()); 00475 } 00476 00477 if (CheckObjCLifetime && 00478 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals)) 00479 return true; 00480 00481 cv1.push_back(RetainedSrcQuals); 00482 cv2.push_back(RetainedDestQuals); 00483 } 00484 if (cv1.empty()) 00485 return false; 00486 00487 // Construct void pointers with those qualifiers (in reverse order of 00488 // unwrapping, of course). 00489 QualType SrcConstruct = Self.Context.VoidTy; 00490 QualType DestConstruct = Self.Context.VoidTy; 00491 ASTContext &Context = Self.Context; 00492 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(), 00493 i2 = cv2.rbegin(); 00494 i1 != cv1.rend(); ++i1, ++i2) { 00495 SrcConstruct 00496 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1)); 00497 DestConstruct 00498 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2)); 00499 } 00500 00501 // Test if they're compatible. 00502 bool ObjCLifetimeConversion; 00503 return SrcConstruct != DestConstruct && 00504 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false, 00505 ObjCLifetimeConversion); 00506 } 00507 00508 /// CheckDynamicCast - Check that a dynamic_cast<DestType>(SrcExpr) is valid. 00509 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 00510 /// checked downcasts in class hierarchies. 00511 void CastOperation::CheckDynamicCast() { 00512 QualType OrigSrcType = SrcExpr.get()->getType(); 00513 QualType DestType = Self.Context.getCanonicalType(this->DestType); 00514 00515 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 00516 // or "pointer to cv void". 00517 00518 QualType DestPointee; 00519 const PointerType *DestPointer = DestType->getAs<PointerType>(); 00520 const ReferenceType *DestReference = 0; 00521 if (DestPointer) { 00522 DestPointee = DestPointer->getPointeeType(); 00523 } else if ((DestReference = DestType->getAs<ReferenceType>())) { 00524 DestPointee = DestReference->getPointeeType(); 00525 } else { 00526 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr) 00527 << this->DestType << DestRange; 00528 return; 00529 } 00530 00531 const RecordType *DestRecord = DestPointee->getAs<RecordType>(); 00532 if (DestPointee->isVoidType()) { 00533 assert(DestPointer && "Reference to void is not possible"); 00534 } else if (DestRecord) { 00535 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee, 00536 Self.PDiag(diag::err_bad_dynamic_cast_incomplete) 00537 << DestRange)) 00538 return; 00539 } else { 00540 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 00541 << DestPointee.getUnqualifiedType() << DestRange; 00542 return; 00543 } 00544 00545 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 00546 // complete class type, [...]. If T is an lvalue reference type, v shall be 00547 // an lvalue of a complete class type, [...]. If T is an rvalue reference 00548 // type, v shall be an expression having a complete class type, [...] 00549 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType); 00550 QualType SrcPointee; 00551 if (DestPointer) { 00552 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 00553 SrcPointee = SrcPointer->getPointeeType(); 00554 } else { 00555 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr) 00556 << OrigSrcType << SrcExpr.get()->getSourceRange(); 00557 return; 00558 } 00559 } else if (DestReference->isLValueReferenceType()) { 00560 if (!SrcExpr.get()->isLValue()) { 00561 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue) 00562 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 00563 } 00564 SrcPointee = SrcType; 00565 } else { 00566 SrcPointee = SrcType; 00567 } 00568 00569 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>(); 00570 if (SrcRecord) { 00571 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee, 00572 Self.PDiag(diag::err_bad_dynamic_cast_incomplete) 00573 << SrcExpr.get()->getSourceRange())) 00574 return; 00575 } else { 00576 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class) 00577 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 00578 return; 00579 } 00580 00581 assert((DestPointer || DestReference) && 00582 "Bad destination non-ptr/ref slipped through."); 00583 assert((DestRecord || DestPointee->isVoidType()) && 00584 "Bad destination pointee slipped through."); 00585 assert(SrcRecord && "Bad source pointee slipped through."); 00586 00587 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 00588 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 00589 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away) 00590 << CT_Dynamic << OrigSrcType << this->DestType << OpRange; 00591 return; 00592 } 00593 00594 // C++ 5.2.7p3: If the type of v is the same as the required result type, 00595 // [except for cv]. 00596 if (DestRecord == SrcRecord) { 00597 Kind = CK_NoOp; 00598 return; 00599 } 00600 00601 // C++ 5.2.7p5 00602 // Upcasts are resolved statically. 00603 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) { 00604 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee, 00605 OpRange.getBegin(), OpRange, 00606 &BasePath)) 00607 return; 00608 00609 Kind = CK_DerivedToBase; 00610 00611 // If we are casting to or through a virtual base class, we need a 00612 // vtable. 00613 if (Self.BasePathInvolvesVirtualBase(BasePath)) 00614 Self.MarkVTableUsed(OpRange.getBegin(), 00615 cast<CXXRecordDecl>(SrcRecord->getDecl())); 00616 return; 00617 } 00618 00619 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 00620 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(); 00621 assert(SrcDecl && "Definition missing"); 00622 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) { 00623 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic) 00624 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange(); 00625 } 00626 Self.MarkVTableUsed(OpRange.getBegin(), 00627 cast<CXXRecordDecl>(SrcRecord->getDecl())); 00628 00629 // Done. Everything else is run-time checks. 00630 Kind = CK_Dynamic; 00631 } 00632 00633 /// CheckConstCast - Check that a const_cast<DestType>(SrcExpr) is valid. 00634 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code 00635 /// like this: 00636 /// const char *str = "literal"; 00637 /// legacy_function(const_cast<char*>(str)); 00638 void CastOperation::CheckConstCast() { 00639 if (ValueKind == VK_RValue) { 00640 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00641 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00642 return; 00643 } 00644 00645 unsigned msg = diag::err_bad_cxx_cast_generic; 00646 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success 00647 && msg != 0) 00648 Self.Diag(OpRange.getBegin(), msg) << CT_Const 00649 << SrcExpr.get()->getType() << DestType << OpRange; 00650 } 00651 00652 /// CheckReinterpretCast - Check that a reinterpret_cast<DestType>(SrcExpr) is 00653 /// valid. 00654 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 00655 /// like this: 00656 /// char *bytes = reinterpret_cast<char*>(int_ptr); 00657 void CastOperation::CheckReinterpretCast() { 00658 if (ValueKind == VK_RValue) { 00659 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00660 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00661 return; 00662 } 00663 00664 unsigned msg = diag::err_bad_cxx_cast_generic; 00665 TryCastResult tcr = 00666 TryReinterpretCast(Self, SrcExpr, DestType, 00667 /*CStyle*/false, OpRange, msg, Kind); 00668 if (tcr != TC_Success && msg != 0) 00669 { 00670 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00671 return; 00672 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 00673 //FIXME: &f<int>; is overloaded and resolvable 00674 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 00675 << OverloadExpr::find(SrcExpr.get()).Expression->getName() 00676 << DestType << OpRange; 00677 Self.NoteAllOverloadCandidates(SrcExpr.get()); 00678 00679 } else { 00680 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType); 00681 } 00682 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) { 00683 checkObjCARCConversion(Sema::CCK_OtherCast); 00684 } 00685 } 00686 00687 00688 /// CheckStaticCast - Check that a static_cast<DestType>(SrcExpr) is valid. 00689 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 00690 /// implicit conversions explicit and getting rid of data loss warnings. 00691 void CastOperation::CheckStaticCast() { 00692 if (isPlaceholder()) { 00693 checkNonOverloadPlaceholders(); 00694 if (SrcExpr.isInvalid()) 00695 return; 00696 } 00697 00698 // This test is outside everything else because it's the only case where 00699 // a non-lvalue-reference target type does not lead to decay. 00700 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 00701 if (DestType->isVoidType()) { 00702 Kind = CK_ToVoid; 00703 00704 if (claimPlaceholder(BuiltinType::Overload)) { 00705 ExprResult SingleFunctionExpression = 00706 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(), 00707 false, // Decay Function to ptr 00708 true, // Complain 00709 OpRange, DestType, diag::err_bad_static_cast_overload); 00710 if (SingleFunctionExpression.isUsable()) 00711 SrcExpr = SingleFunctionExpression; 00712 } 00713 00714 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 00715 return; 00716 } 00717 00718 if (ValueKind == VK_RValue && !DestType->isRecordType()) { 00719 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 00720 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error 00721 return; 00722 } 00723 00724 unsigned msg = diag::err_bad_cxx_cast_generic; 00725 TryCastResult tcr 00726 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg, 00727 Kind, BasePath); 00728 if (tcr != TC_Success && msg != 0) { 00729 if (SrcExpr.isInvalid()) 00730 return; 00731 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 00732 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression; 00733 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload) 00734 << oe->getName() << DestType << OpRange 00735 << oe->getQualifierLoc().getSourceRange(); 00736 Self.NoteAllOverloadCandidates(SrcExpr.get()); 00737 } else { 00738 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType); 00739 } 00740 } else if (tcr == TC_Success) { 00741 if (Kind == CK_BitCast) 00742 checkCastAlign(); 00743 if (Self.getLangOptions().ObjCAutoRefCount) 00744 checkObjCARCConversion(Sema::CCK_OtherCast); 00745 } else if (Kind == CK_BitCast) { 00746 checkCastAlign(); 00747 } 00748 } 00749 00750 /// TryStaticCast - Check if a static cast can be performed, and do so if 00751 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting 00752 /// and casting away constness. 00753 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, 00754 QualType DestType, 00755 Sema::CheckedConversionKind CCK, 00756 const SourceRange &OpRange, unsigned &msg, 00757 CastKind &Kind, 00758 CXXCastPath &BasePath) { 00759 // Determine whether we have the semantics of a C-style cast. 00760 bool CStyle 00761 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 00762 00763 // The order the tests is not entirely arbitrary. There is one conversion 00764 // that can be handled in two different ways. Given: 00765 // struct A {}; 00766 // struct B : public A { 00767 // B(); B(const A&); 00768 // }; 00769 // const A &a = B(); 00770 // the cast static_cast<const B&>(a) could be seen as either a static 00771 // reference downcast, or an explicit invocation of the user-defined 00772 // conversion using B's conversion constructor. 00773 // DR 427 specifies that the downcast is to be applied here. 00774 00775 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 00776 // Done outside this function. 00777 00778 TryCastResult tcr; 00779 00780 // C++ 5.2.9p5, reference downcast. 00781 // See the function for details. 00782 // DR 427 specifies that this is to be applied before paragraph 2. 00783 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange, 00784 msg, Kind, BasePath); 00785 if (tcr != TC_NotApplicable) 00786 return tcr; 00787 00788 // C++0x [expr.static.cast]p3: 00789 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2 00790 // T2" if "cv2 T2" is reference-compatible with "cv1 T1". 00791 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath, 00792 msg); 00793 if (tcr != TC_NotApplicable) 00794 return tcr; 00795 00796 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 00797 // [...] if the declaration "T t(e);" is well-formed, [...]. 00798 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg, 00799 Kind); 00800 if (SrcExpr.isInvalid()) 00801 return TC_Failed; 00802 if (tcr != TC_NotApplicable) 00803 return tcr; 00804 00805 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 00806 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 00807 // conversions, subject to further restrictions. 00808 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 00809 // of qualification conversions impossible. 00810 // In the CStyle case, the earlier attempt to const_cast should have taken 00811 // care of reverse qualification conversions. 00812 00813 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType()); 00814 00815 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly 00816 // converted to an integral type. [...] A value of a scoped enumeration type 00817 // can also be explicitly converted to a floating-point type [...]. 00818 if (const EnumType *Enum = SrcType->getAs<EnumType>()) { 00819 if (Enum->getDecl()->isScoped()) { 00820 if (DestType->isBooleanType()) { 00821 Kind = CK_IntegralToBoolean; 00822 return TC_Success; 00823 } else if (DestType->isIntegralType(Self.Context)) { 00824 Kind = CK_IntegralCast; 00825 return TC_Success; 00826 } else if (DestType->isRealFloatingType()) { 00827 Kind = CK_IntegralToFloating; 00828 return TC_Success; 00829 } 00830 } 00831 } 00832 00833 // Reverse integral promotion/conversion. All such conversions are themselves 00834 // again integral promotions or conversions and are thus already handled by 00835 // p2 (TryDirectInitialization above). 00836 // (Note: any data loss warnings should be suppressed.) 00837 // The exception is the reverse of enum->integer, i.e. integer->enum (and 00838 // enum->enum). See also C++ 5.2.9p7. 00839 // The same goes for reverse floating point promotion/conversion and 00840 // floating-integral conversions. Again, only floating->enum is relevant. 00841 if (DestType->isEnumeralType()) { 00842 if (SrcType->isIntegralOrEnumerationType()) { 00843 Kind = CK_IntegralCast; 00844 return TC_Success; 00845 } else if (SrcType->isRealFloatingType()) { 00846 Kind = CK_FloatingToIntegral; 00847 return TC_Success; 00848 } 00849 } 00850 00851 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 00852 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 00853 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg, 00854 Kind, BasePath); 00855 if (tcr != TC_NotApplicable) 00856 return tcr; 00857 00858 // Reverse member pointer conversion. C++ 4.11 specifies member pointer 00859 // conversion. C++ 5.2.9p9 has additional information. 00860 // DR54's access restrictions apply here also. 00861 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle, 00862 OpRange, msg, Kind, BasePath); 00863 if (tcr != TC_NotApplicable) 00864 return tcr; 00865 00866 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 00867 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 00868 // just the usual constness stuff. 00869 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) { 00870 QualType SrcPointee = SrcPointer->getPointeeType(); 00871 if (SrcPointee->isVoidType()) { 00872 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) { 00873 QualType DestPointee = DestPointer->getPointeeType(); 00874 if (DestPointee->isIncompleteOrObjectType()) { 00875 // This is definitely the intended conversion, but it might fail due 00876 // to a qualifier violation. Note that we permit Objective-C lifetime 00877 // and GC qualifier mismatches here. 00878 if (!CStyle) { 00879 Qualifiers DestPointeeQuals = DestPointee.getQualifiers(); 00880 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers(); 00881 DestPointeeQuals.removeObjCGCAttr(); 00882 DestPointeeQuals.removeObjCLifetime(); 00883 SrcPointeeQuals.removeObjCGCAttr(); 00884 SrcPointeeQuals.removeObjCLifetime(); 00885 if (DestPointeeQuals != SrcPointeeQuals && 00886 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) { 00887 msg = diag::err_bad_cxx_cast_qualifiers_away; 00888 return TC_Failed; 00889 } 00890 } 00891 Kind = CK_BitCast; 00892 return TC_Success; 00893 } 00894 } 00895 else if (DestType->isObjCObjectPointerType()) { 00896 // allow both c-style cast and static_cast of objective-c pointers as 00897 // they are pervasive. 00898 Kind = CK_CPointerToObjCPointerCast; 00899 return TC_Success; 00900 } 00901 else if (CStyle && DestType->isBlockPointerType()) { 00902 // allow c-style cast of void * to block pointers. 00903 Kind = CK_AnyPointerToBlockPointerCast; 00904 return TC_Success; 00905 } 00906 } 00907 } 00908 // Allow arbitray objective-c pointer conversion with static casts. 00909 if (SrcType->isObjCObjectPointerType() && 00910 DestType->isObjCObjectPointerType()) { 00911 Kind = CK_BitCast; 00912 return TC_Success; 00913 } 00914 00915 // We tried everything. Everything! Nothing works! :-( 00916 return TC_NotApplicable; 00917 } 00918 00919 /// Tests whether a conversion according to N2844 is valid. 00920 TryCastResult 00921 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, 00922 bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 00923 unsigned &msg) { 00924 // C++0x [expr.static.cast]p3: 00925 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 00926 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1". 00927 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>(); 00928 if (!R) 00929 return TC_NotApplicable; 00930 00931 if (!SrcExpr->isGLValue()) 00932 return TC_NotApplicable; 00933 00934 // Because we try the reference downcast before this function, from now on 00935 // this is the only cast possibility, so we issue an error if we fail now. 00936 // FIXME: Should allow casting away constness if CStyle. 00937 bool DerivedToBase; 00938 bool ObjCConversion; 00939 bool ObjCLifetimeConversion; 00940 QualType FromType = SrcExpr->getType(); 00941 QualType ToType = R->getPointeeType(); 00942 if (CStyle) { 00943 FromType = FromType.getUnqualifiedType(); 00944 ToType = ToType.getUnqualifiedType(); 00945 } 00946 00947 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(), 00948 ToType, FromType, 00949 DerivedToBase, ObjCConversion, 00950 ObjCLifetimeConversion) 00951 < Sema::Ref_Compatible_With_Added_Qualification) { 00952 msg = diag::err_bad_lvalue_to_rvalue_cast; 00953 return TC_Failed; 00954 } 00955 00956 if (DerivedToBase) { 00957 Kind = CK_DerivedToBase; 00958 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 00959 /*DetectVirtual=*/true); 00960 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths)) 00961 return TC_NotApplicable; 00962 00963 Self.BuildBasePathArray(Paths, BasePath); 00964 } else 00965 Kind = CK_NoOp; 00966 00967 return TC_Success; 00968 } 00969 00970 /// Tests whether a conversion according to C++ 5.2.9p5 is valid. 00971 TryCastResult 00972 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, 00973 bool CStyle, const SourceRange &OpRange, 00974 unsigned &msg, CastKind &Kind, 00975 CXXCastPath &BasePath) { 00976 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 00977 // cast to type "reference to cv2 D", where D is a class derived from B, 00978 // if a valid standard conversion from "pointer to D" to "pointer to B" 00979 // exists, cv2 >= cv1, and B is not a virtual base class of D. 00980 // In addition, DR54 clarifies that the base must be accessible in the 00981 // current context. Although the wording of DR54 only applies to the pointer 00982 // variant of this rule, the intent is clearly for it to apply to the this 00983 // conversion as well. 00984 00985 const ReferenceType *DestReference = DestType->getAs<ReferenceType>(); 00986 if (!DestReference) { 00987 return TC_NotApplicable; 00988 } 00989 bool RValueRef = DestReference->isRValueReferenceType(); 00990 if (!RValueRef && !SrcExpr->isLValue()) { 00991 // We know the left side is an lvalue reference, so we can suggest a reason. 00992 msg = diag::err_bad_cxx_cast_rvalue; 00993 return TC_NotApplicable; 00994 } 00995 00996 QualType DestPointee = DestReference->getPointeeType(); 00997 00998 return TryStaticDowncast(Self, 00999 Self.Context.getCanonicalType(SrcExpr->getType()), 01000 Self.Context.getCanonicalType(DestPointee), CStyle, 01001 OpRange, SrcExpr->getType(), DestType, msg, Kind, 01002 BasePath); 01003 } 01004 01005 /// Tests whether a conversion according to C++ 5.2.9p8 is valid. 01006 TryCastResult 01007 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, 01008 bool CStyle, const SourceRange &OpRange, 01009 unsigned &msg, CastKind &Kind, 01010 CXXCastPath &BasePath) { 01011 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 01012 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 01013 // is a class derived from B, if a valid standard conversion from "pointer 01014 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 01015 // class of D. 01016 // In addition, DR54 clarifies that the base must be accessible in the 01017 // current context. 01018 01019 const PointerType *DestPointer = DestType->getAs<PointerType>(); 01020 if (!DestPointer) { 01021 return TC_NotApplicable; 01022 } 01023 01024 const PointerType *SrcPointer = SrcType->getAs<PointerType>(); 01025 if (!SrcPointer) { 01026 msg = diag::err_bad_static_cast_pointer_nonpointer; 01027 return TC_NotApplicable; 01028 } 01029 01030 return TryStaticDowncast(Self, 01031 Self.Context.getCanonicalType(SrcPointer->getPointeeType()), 01032 Self.Context.getCanonicalType(DestPointer->getPointeeType()), 01033 CStyle, OpRange, SrcType, DestType, msg, Kind, 01034 BasePath); 01035 } 01036 01037 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and 01038 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to 01039 /// DestType is possible and allowed. 01040 TryCastResult 01041 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, 01042 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType, 01043 QualType OrigDestType, unsigned &msg, 01044 CastKind &Kind, CXXCastPath &BasePath) { 01045 // We can only work with complete types. But don't complain if it doesn't work 01046 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) || 01047 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0))) 01048 return TC_NotApplicable; 01049 01050 // Downcast can only happen in class hierarchies, so we need classes. 01051 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) { 01052 return TC_NotApplicable; 01053 } 01054 01055 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 01056 /*DetectVirtual=*/true); 01057 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) { 01058 return TC_NotApplicable; 01059 } 01060 01061 // Target type does derive from source type. Now we're serious. If an error 01062 // appears now, it's not ignored. 01063 // This may not be entirely in line with the standard. Take for example: 01064 // struct A {}; 01065 // struct B : virtual A { 01066 // B(A&); 01067 // }; 01068 // 01069 // void f() 01070 // { 01071 // (void)static_cast<const B&>(*((A*)0)); 01072 // } 01073 // As far as the standard is concerned, p5 does not apply (A is virtual), so 01074 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid. 01075 // However, both GCC and Comeau reject this example, and accepting it would 01076 // mean more complex code if we're to preserve the nice error message. 01077 // FIXME: Being 100% compliant here would be nice to have. 01078 01079 // Must preserve cv, as always, unless we're in C-style mode. 01080 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) { 01081 msg = diag::err_bad_cxx_cast_qualifiers_away; 01082 return TC_Failed; 01083 } 01084 01085 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 01086 // This code is analoguous to that in CheckDerivedToBaseConversion, except 01087 // that it builds the paths in reverse order. 01088 // To sum up: record all paths to the base and build a nice string from 01089 // them. Use it to spice up the error message. 01090 if (!Paths.isRecordingPaths()) { 01091 Paths.clear(); 01092 Paths.setRecordingPaths(true); 01093 Self.IsDerivedFrom(DestType, SrcType, Paths); 01094 } 01095 std::string PathDisplayStr; 01096 std::set<unsigned> DisplayedPaths; 01097 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end(); 01098 PI != PE; ++PI) { 01099 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) { 01100 // We haven't displayed a path to this particular base 01101 // class subobject yet. 01102 PathDisplayStr += "\n "; 01103 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(), 01104 EE = PI->rend(); 01105 EI != EE; ++EI) 01106 PathDisplayStr += EI->Base->getType().getAsString() + " -> "; 01107 PathDisplayStr += QualType(DestType).getAsString(); 01108 } 01109 } 01110 01111 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast) 01112 << QualType(SrcType).getUnqualifiedType() 01113 << QualType(DestType).getUnqualifiedType() 01114 << PathDisplayStr << OpRange; 01115 msg = 0; 01116 return TC_Failed; 01117 } 01118 01119 if (Paths.getDetectedVirtual() != 0) { 01120 QualType VirtualBase(Paths.getDetectedVirtual(), 0); 01121 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual) 01122 << OrigSrcType << OrigDestType << VirtualBase << OpRange; 01123 msg = 0; 01124 return TC_Failed; 01125 } 01126 01127 if (!CStyle) { 01128 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 01129 SrcType, DestType, 01130 Paths.front(), 01131 diag::err_downcast_from_inaccessible_base)) { 01132 case Sema::AR_accessible: 01133 case Sema::AR_delayed: // be optimistic 01134 case Sema::AR_dependent: // be optimistic 01135 break; 01136 01137 case Sema::AR_inaccessible: 01138 msg = 0; 01139 return TC_Failed; 01140 } 01141 } 01142 01143 Self.BuildBasePathArray(Paths, BasePath); 01144 Kind = CK_BaseToDerived; 01145 return TC_Success; 01146 } 01147 01148 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to 01149 /// C++ 5.2.9p9 is valid: 01150 /// 01151 /// An rvalue of type "pointer to member of D of type cv1 T" can be 01152 /// converted to an rvalue of type "pointer to member of B of type cv2 T", 01153 /// where B is a base class of D [...]. 01154 /// 01155 TryCastResult 01156 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 01157 QualType DestType, bool CStyle, 01158 const SourceRange &OpRange, 01159 unsigned &msg, CastKind &Kind, 01160 CXXCastPath &BasePath) { 01161 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(); 01162 if (!DestMemPtr) 01163 return TC_NotApplicable; 01164 01165 bool WasOverloadedFunction = false; 01166 DeclAccessPair FoundOverload; 01167 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 01168 if (FunctionDecl *Fn 01169 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false, 01170 FoundOverload)) { 01171 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn); 01172 SrcType = Self.Context.getMemberPointerType(Fn->getType(), 01173 Self.Context.getTypeDeclType(M->getParent()).getTypePtr()); 01174 WasOverloadedFunction = true; 01175 } 01176 } 01177 01178 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 01179 if (!SrcMemPtr) { 01180 msg = diag::err_bad_static_cast_member_pointer_nonmp; 01181 return TC_NotApplicable; 01182 } 01183 01184 // T == T, modulo cv 01185 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(), 01186 DestMemPtr->getPointeeType())) 01187 return TC_NotApplicable; 01188 01189 // B base of D 01190 QualType SrcClass(SrcMemPtr->getClass(), 0); 01191 QualType DestClass(DestMemPtr->getClass(), 0); 01192 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 01193 /*DetectVirtual=*/true); 01194 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) { 01195 return TC_NotApplicable; 01196 } 01197 01198 // B is a base of D. But is it an allowed base? If not, it's a hard error. 01199 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) { 01200 Paths.clear(); 01201 Paths.setRecordingPaths(true); 01202 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths); 01203 assert(StillOkay); 01204 (void)StillOkay; 01205 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths); 01206 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv) 01207 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange; 01208 msg = 0; 01209 return TC_Failed; 01210 } 01211 01212 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 01213 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual) 01214 << SrcClass << DestClass << QualType(VBase, 0) << OpRange; 01215 msg = 0; 01216 return TC_Failed; 01217 } 01218 01219 if (!CStyle) { 01220 switch (Self.CheckBaseClassAccess(OpRange.getBegin(), 01221 DestClass, SrcClass, 01222 Paths.front(), 01223 diag::err_upcast_to_inaccessible_base)) { 01224 case Sema::AR_accessible: 01225 case Sema::AR_delayed: 01226 case Sema::AR_dependent: 01227 // Optimistically assume that the delayed and dependent cases 01228 // will work out. 01229 break; 01230 01231 case Sema::AR_inaccessible: 01232 msg = 0; 01233 return TC_Failed; 01234 } 01235 } 01236 01237 if (WasOverloadedFunction) { 01238 // Resolve the address of the overloaded function again, this time 01239 // allowing complaints if something goes wrong. 01240 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 01241 DestType, 01242 true, 01243 FoundOverload); 01244 if (!Fn) { 01245 msg = 0; 01246 return TC_Failed; 01247 } 01248 01249 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn); 01250 if (!SrcExpr.isUsable()) { 01251 msg = 0; 01252 return TC_Failed; 01253 } 01254 } 01255 01256 Self.BuildBasePathArray(Paths, BasePath); 01257 Kind = CK_DerivedToBaseMemberPointer; 01258 return TC_Success; 01259 } 01260 01261 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 01262 /// is valid: 01263 /// 01264 /// An expression e can be explicitly converted to a type T using a 01265 /// @c static_cast if the declaration "T t(e);" is well-formed [...]. 01266 TryCastResult 01267 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, 01268 Sema::CheckedConversionKind CCK, 01269 const SourceRange &OpRange, unsigned &msg, 01270 CastKind &Kind) { 01271 if (DestType->isRecordType()) { 01272 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 01273 diag::err_bad_dynamic_cast_incomplete)) { 01274 msg = 0; 01275 return TC_Failed; 01276 } 01277 } 01278 01279 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType); 01280 InitializationKind InitKind 01281 = (CCK == Sema::CCK_CStyleCast) 01282 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange) 01283 : (CCK == Sema::CCK_FunctionalCast) 01284 ? InitializationKind::CreateFunctionalCast(OpRange) 01285 : InitializationKind::CreateCast(OpRange); 01286 Expr *SrcExprRaw = SrcExpr.get(); 01287 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1); 01288 01289 // At this point of CheckStaticCast, if the destination is a reference, 01290 // or the expression is an overload expression this has to work. 01291 // There is no other way that works. 01292 // On the other hand, if we're checking a C-style cast, we've still got 01293 // the reinterpret_cast way. 01294 bool CStyle 01295 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast); 01296 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType())) 01297 return TC_NotApplicable; 01298 01299 ExprResult Result 01300 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1)); 01301 if (Result.isInvalid()) { 01302 msg = 0; 01303 return TC_Failed; 01304 } 01305 01306 if (InitSeq.isConstructorInitialization()) 01307 Kind = CK_ConstructorConversion; 01308 else 01309 Kind = CK_NoOp; 01310 01311 SrcExpr = move(Result); 01312 return TC_Success; 01313 } 01314 01315 /// TryConstCast - See if a const_cast from source to destination is allowed, 01316 /// and perform it if it is. 01317 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType, 01318 bool CStyle, unsigned &msg) { 01319 DestType = Self.Context.getCanonicalType(DestType); 01320 QualType SrcType = SrcExpr->getType(); 01321 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) { 01322 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) { 01323 // Cannot const_cast non-lvalue to lvalue reference type. But if this 01324 // is C-style, static_cast might find a way, so we simply suggest a 01325 // message and tell the parent to keep searching. 01326 msg = diag::err_bad_cxx_cast_rvalue; 01327 return TC_NotApplicable; 01328 } 01329 01330 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2 01331 // [...] if a pointer to T1 can be [cast] to the type pointer to T2. 01332 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 01333 SrcType = Self.Context.getPointerType(SrcType); 01334 } 01335 01336 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...] 01337 // the rules for const_cast are the same as those used for pointers. 01338 01339 if (!DestType->isPointerType() && 01340 !DestType->isMemberPointerType() && 01341 !DestType->isObjCObjectPointerType()) { 01342 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 01343 // was a reference type, we converted it to a pointer above. 01344 // The status of rvalue references isn't entirely clear, but it looks like 01345 // conversion to them is simply invalid. 01346 // C++ 5.2.11p3: For two pointer types [...] 01347 if (!CStyle) 01348 msg = diag::err_bad_const_cast_dest; 01349 return TC_NotApplicable; 01350 } 01351 if (DestType->isFunctionPointerType() || 01352 DestType->isMemberFunctionPointerType()) { 01353 // Cannot cast direct function pointers. 01354 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 01355 // T is the ultimate pointee of source and target type. 01356 if (!CStyle) 01357 msg = diag::err_bad_const_cast_dest; 01358 return TC_NotApplicable; 01359 } 01360 SrcType = Self.Context.getCanonicalType(SrcType); 01361 01362 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 01363 // completely equal. 01364 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 01365 // in multi-level pointers may change, but the level count must be the same, 01366 // as must be the final pointee type. 01367 while (SrcType != DestType && 01368 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) { 01369 Qualifiers SrcQuals, DestQuals; 01370 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals); 01371 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals); 01372 01373 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that 01374 // the other qualifiers (e.g., address spaces) are identical. 01375 SrcQuals.removeCVRQualifiers(); 01376 DestQuals.removeCVRQualifiers(); 01377 if (SrcQuals != DestQuals) 01378 return TC_NotApplicable; 01379 } 01380 01381 // Since we're dealing in canonical types, the remainder must be the same. 01382 if (SrcType != DestType) 01383 return TC_NotApplicable; 01384 01385 return TC_Success; 01386 } 01387 01388 // Checks for undefined behavior in reinterpret_cast. 01389 // The cases that is checked for is: 01390 // *reinterpret_cast<T*>(&a) 01391 // reinterpret_cast<T&>(a) 01392 // where accessing 'a' as type 'T' will result in undefined behavior. 01393 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 01394 bool IsDereference, 01395 SourceRange Range) { 01396 unsigned DiagID = IsDereference ? 01397 diag::warn_pointer_indirection_from_incompatible_type : 01398 diag::warn_undefined_reinterpret_cast; 01399 01400 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) == 01401 DiagnosticsEngine::Ignored) { 01402 return; 01403 } 01404 01405 QualType SrcTy, DestTy; 01406 if (IsDereference) { 01407 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) { 01408 return; 01409 } 01410 SrcTy = SrcType->getPointeeType(); 01411 DestTy = DestType->getPointeeType(); 01412 } else { 01413 if (!DestType->getAs<ReferenceType>()) { 01414 return; 01415 } 01416 SrcTy = SrcType; 01417 DestTy = DestType->getPointeeType(); 01418 } 01419 01420 // Cast is compatible if the types are the same. 01421 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) { 01422 return; 01423 } 01424 // or one of the types is a char or void type 01425 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() || 01426 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) { 01427 return; 01428 } 01429 // or one of the types is a tag type. 01430 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) { 01431 return; 01432 } 01433 01434 // FIXME: Scoped enums? 01435 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) || 01436 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) { 01437 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) { 01438 return; 01439 } 01440 } 01441 01442 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range; 01443 } 01444 01445 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, 01446 QualType DestType, bool CStyle, 01447 const SourceRange &OpRange, 01448 unsigned &msg, 01449 CastKind &Kind) { 01450 bool IsLValueCast = false; 01451 01452 DestType = Self.Context.getCanonicalType(DestType); 01453 QualType SrcType = SrcExpr.get()->getType(); 01454 01455 // Is the source an overloaded name? (i.e. &foo) 01456 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ... 01457 if (SrcType == Self.Context.OverloadTy) { 01458 // ... unless foo<int> resolves to an lvalue unambiguously 01459 ExprResult SingleFunctionExpr = 01460 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(), 01461 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 01462 ); 01463 if (SingleFunctionExpr.isUsable()) { 01464 SrcExpr = move(SingleFunctionExpr); 01465 SrcType = SrcExpr.get()->getType(); 01466 } 01467 else 01468 return TC_NotApplicable; 01469 } 01470 01471 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) { 01472 bool LValue = DestTypeTmp->isLValueReferenceType(); 01473 if (LValue && !SrcExpr.get()->isLValue()) { 01474 // Cannot cast non-lvalue to lvalue reference type. See the similar 01475 // comment in const_cast. 01476 msg = diag::err_bad_cxx_cast_rvalue; 01477 return TC_NotApplicable; 01478 } 01479 01480 if (!CStyle) { 01481 Self.CheckCompatibleReinterpretCast(SrcType, DestType, 01482 /*isDereference=*/false, OpRange); 01483 } 01484 01485 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 01486 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 01487 // built-in & and * operators. 01488 01489 const char *inappropriate = 0; 01490 switch (SrcExpr.get()->getObjectKind()) { 01491 case OK_Ordinary: 01492 break; 01493 case OK_BitField: inappropriate = "bit-field"; break; 01494 case OK_VectorComponent: inappropriate = "vector element"; break; 01495 case OK_ObjCProperty: inappropriate = "property expression"; break; 01496 } 01497 if (inappropriate) { 01498 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference) 01499 << inappropriate << DestType 01500 << OpRange << SrcExpr.get()->getSourceRange(); 01501 msg = 0; SrcExpr = ExprError(); 01502 return TC_NotApplicable; 01503 } 01504 01505 // This code does this transformation for the checked types. 01506 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType()); 01507 SrcType = Self.Context.getPointerType(SrcType); 01508 01509 IsLValueCast = true; 01510 } 01511 01512 // Canonicalize source for comparison. 01513 SrcType = Self.Context.getCanonicalType(SrcType); 01514 01515 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(), 01516 *SrcMemPtr = SrcType->getAs<MemberPointerType>(); 01517 if (DestMemPtr && SrcMemPtr) { 01518 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1" 01519 // can be explicitly converted to an rvalue of type "pointer to member 01520 // of Y of type T2" if T1 and T2 are both function types or both object 01521 // types. 01522 if (DestMemPtr->getPointeeType()->isFunctionType() != 01523 SrcMemPtr->getPointeeType()->isFunctionType()) 01524 return TC_NotApplicable; 01525 01526 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away 01527 // constness. 01528 // A reinterpret_cast followed by a const_cast can, though, so in C-style, 01529 // we accept it. 01530 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 01531 /*CheckObjCLifetime=*/CStyle)) { 01532 msg = diag::err_bad_cxx_cast_qualifiers_away; 01533 return TC_Failed; 01534 } 01535 01536 // Don't allow casting between member pointers of different sizes. 01537 if (Self.Context.getTypeSize(DestMemPtr) != 01538 Self.Context.getTypeSize(SrcMemPtr)) { 01539 msg = diag::err_bad_cxx_cast_member_pointer_size; 01540 return TC_Failed; 01541 } 01542 01543 // A valid member pointer cast. 01544 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast; 01545 return TC_Success; 01546 } 01547 01548 // See below for the enumeral issue. 01549 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) { 01550 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral 01551 // type large enough to hold it. A value of std::nullptr_t can be 01552 // converted to an integral type; the conversion has the same meaning 01553 // and validity as a conversion of (void*)0 to the integral type. 01554 if (Self.Context.getTypeSize(SrcType) > 01555 Self.Context.getTypeSize(DestType)) { 01556 msg = diag::err_bad_reinterpret_cast_small_int; 01557 return TC_Failed; 01558 } 01559 Kind = CK_PointerToIntegral; 01560 return TC_Success; 01561 } 01562 01563 bool destIsVector = DestType->isVectorType(); 01564 bool srcIsVector = SrcType->isVectorType(); 01565 if (srcIsVector || destIsVector) { 01566 // FIXME: Should this also apply to floating point types? 01567 bool srcIsScalar = SrcType->isIntegralType(Self.Context); 01568 bool destIsScalar = DestType->isIntegralType(Self.Context); 01569 01570 // Check if this is a cast between a vector and something else. 01571 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) && 01572 !(srcIsVector && destIsVector)) 01573 return TC_NotApplicable; 01574 01575 // If both types have the same size, we can successfully cast. 01576 if (Self.Context.getTypeSize(SrcType) 01577 == Self.Context.getTypeSize(DestType)) { 01578 Kind = CK_BitCast; 01579 return TC_Success; 01580 } 01581 01582 if (destIsScalar) 01583 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size; 01584 else if (srcIsScalar) 01585 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size; 01586 else 01587 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size; 01588 01589 return TC_Failed; 01590 } 01591 01592 bool destIsPtr = DestType->isAnyPointerType() || 01593 DestType->isBlockPointerType(); 01594 bool srcIsPtr = SrcType->isAnyPointerType() || 01595 SrcType->isBlockPointerType(); 01596 if (!destIsPtr && !srcIsPtr) { 01597 // Except for std::nullptr_t->integer and lvalue->reference, which are 01598 // handled above, at least one of the two arguments must be a pointer. 01599 return TC_NotApplicable; 01600 } 01601 01602 if (SrcType == DestType) { 01603 // C++ 5.2.10p2 has a note that mentions that, subject to all other 01604 // restrictions, a cast to the same type is allowed. The intent is not 01605 // entirely clear here, since all other paragraphs explicitly forbid casts 01606 // to the same type. However, the behavior of compilers is pretty consistent 01607 // on this point: allow same-type conversion if the involved types are 01608 // pointers, disallow otherwise. 01609 Kind = CK_NoOp; 01610 return TC_Success; 01611 } 01612 01613 if (DestType->isIntegralType(Self.Context)) { 01614 assert(srcIsPtr && "One type must be a pointer"); 01615 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 01616 // type large enough to hold it; except in Microsoft mode, where the 01617 // integral type size doesn't matter. 01618 if ((Self.Context.getTypeSize(SrcType) > 01619 Self.Context.getTypeSize(DestType)) && 01620 !Self.getLangOptions().MicrosoftExt) { 01621 msg = diag::err_bad_reinterpret_cast_small_int; 01622 return TC_Failed; 01623 } 01624 Kind = CK_PointerToIntegral; 01625 return TC_Success; 01626 } 01627 01628 if (SrcType->isIntegralOrEnumerationType()) { 01629 assert(destIsPtr && "One type must be a pointer"); 01630 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 01631 // converted to a pointer. 01632 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not 01633 // necessarily converted to a null pointer value.] 01634 Kind = CK_IntegralToPointer; 01635 return TC_Success; 01636 } 01637 01638 if (!destIsPtr || !srcIsPtr) { 01639 // With the valid non-pointer conversions out of the way, we can be even 01640 // more stringent. 01641 return TC_NotApplicable; 01642 } 01643 01644 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 01645 // The C-style cast operator can. 01646 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle, 01647 /*CheckObjCLifetime=*/CStyle)) { 01648 msg = diag::err_bad_cxx_cast_qualifiers_away; 01649 return TC_Failed; 01650 } 01651 01652 // Cannot convert between block pointers and Objective-C object pointers. 01653 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) || 01654 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType())) 01655 return TC_NotApplicable; 01656 01657 if (IsLValueCast) { 01658 Kind = CK_LValueBitCast; 01659 } else if (DestType->isObjCObjectPointerType()) { 01660 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr); 01661 } else if (DestType->isBlockPointerType()) { 01662 if (!SrcType->isBlockPointerType()) { 01663 Kind = CK_AnyPointerToBlockPointerCast; 01664 } else { 01665 Kind = CK_BitCast; 01666 } 01667 } else { 01668 Kind = CK_BitCast; 01669 } 01670 01671 // Any pointer can be cast to an Objective-C pointer type with a C-style 01672 // cast. 01673 if (CStyle && DestType->isObjCObjectPointerType()) { 01674 return TC_Success; 01675 } 01676 01677 // Not casting away constness, so the only remaining check is for compatible 01678 // pointer categories. 01679 01680 if (SrcType->isFunctionPointerType()) { 01681 if (DestType->isFunctionPointerType()) { 01682 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 01683 // a pointer to a function of a different type. 01684 return TC_Success; 01685 } 01686 01687 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 01688 // an object type or vice versa is conditionally-supported. 01689 // Compilers support it in C++03 too, though, because it's necessary for 01690 // casting the return value of dlsym() and GetProcAddress(). 01691 // FIXME: Conditionally-supported behavior should be configurable in the 01692 // TargetInfo or similar. 01693 if (!Self.getLangOptions().CPlusPlus0x) 01694 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange; 01695 return TC_Success; 01696 } 01697 01698 if (DestType->isFunctionPointerType()) { 01699 // See above. 01700 if (!Self.getLangOptions().CPlusPlus0x) 01701 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange; 01702 return TC_Success; 01703 } 01704 01705 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 01706 // a pointer to an object of different type. 01707 // Void pointers are not specified, but supported by every compiler out there. 01708 // So we finish by allowing everything that remains - it's got to be two 01709 // object pointers. 01710 return TC_Success; 01711 } 01712 01713 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) { 01714 // Handle placeholders. 01715 if (isPlaceholder()) { 01716 // C-style casts can resolve __unknown_any types. 01717 if (claimPlaceholder(BuiltinType::UnknownAny)) { 01718 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 01719 SrcExpr.get(), Kind, 01720 ValueKind, BasePath); 01721 return; 01722 } 01723 01724 checkNonOverloadPlaceholders(); 01725 if (SrcExpr.isInvalid()) 01726 return; 01727 } 01728 01729 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 01730 // This test is outside everything else because it's the only case where 01731 // a non-lvalue-reference target type does not lead to decay. 01732 if (DestType->isVoidType()) { 01733 Kind = CK_ToVoid; 01734 01735 if (claimPlaceholder(BuiltinType::Overload)) { 01736 SrcExpr = Self.ResolveAndFixSingleFunctionTemplateSpecialization( 01737 SrcExpr.take(), /* Decay Function to ptr */ false, 01738 /* Complain */ true, DestRange, DestType, 01739 diag::err_bad_cstyle_cast_overload); 01740 if (SrcExpr.isInvalid()) 01741 return; 01742 } 01743 01744 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 01745 if (SrcExpr.isInvalid()) 01746 return; 01747 01748 return; 01749 } 01750 01751 // If the type is dependent, we won't do any other semantic analysis now. 01752 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) { 01753 assert(Kind == CK_Dependent); 01754 return; 01755 } 01756 01757 if (ValueKind == VK_RValue && !DestType->isRecordType()) { 01758 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 01759 if (SrcExpr.isInvalid()) 01760 return; 01761 } 01762 01763 // AltiVec vector initialization with a single literal. 01764 if (const VectorType *vecTy = DestType->getAs<VectorType>()) 01765 if (vecTy->getVectorKind() == VectorType::AltiVecVector 01766 && (SrcExpr.get()->getType()->isIntegerType() 01767 || SrcExpr.get()->getType()->isFloatingType())) { 01768 Kind = CK_VectorSplat; 01769 return; 01770 } 01771 01772 // C++ [expr.cast]p5: The conversions performed by 01773 // - a const_cast, 01774 // - a static_cast, 01775 // - a static_cast followed by a const_cast, 01776 // - a reinterpret_cast, or 01777 // - a reinterpret_cast followed by a const_cast, 01778 // can be performed using the cast notation of explicit type conversion. 01779 // [...] If a conversion can be interpreted in more than one of the ways 01780 // listed above, the interpretation that appears first in the list is used, 01781 // even if a cast resulting from that interpretation is ill-formed. 01782 // In plain language, this means trying a const_cast ... 01783 unsigned msg = diag::err_bad_cxx_cast_generic; 01784 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType, 01785 /*CStyle*/true, msg); 01786 if (tcr == TC_Success) 01787 Kind = CK_NoOp; 01788 01789 Sema::CheckedConversionKind CCK 01790 = FunctionalStyle? Sema::CCK_FunctionalCast 01791 : Sema::CCK_CStyleCast; 01792 if (tcr == TC_NotApplicable) { 01793 // ... or if that is not possible, a static_cast, ignoring const, ... 01794 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, 01795 msg, Kind, BasePath); 01796 if (SrcExpr.isInvalid()) 01797 return; 01798 01799 if (tcr == TC_NotApplicable) { 01800 // ... and finally a reinterpret_cast, ignoring const. 01801 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true, 01802 OpRange, msg, Kind); 01803 if (SrcExpr.isInvalid()) 01804 return; 01805 } 01806 } 01807 01808 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success) 01809 checkObjCARCConversion(CCK); 01810 01811 if (tcr != TC_Success && msg != 0) { 01812 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) { 01813 DeclAccessPair Found; 01814 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 01815 DestType, 01816 /*Complain*/ true, 01817 Found); 01818 01819 assert(!Fn && "cast failed but able to resolve overload expression!!"); 01820 (void)Fn; 01821 01822 } else { 01823 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle), 01824 OpRange, SrcExpr.get(), DestType); 01825 } 01826 } else if (Kind == CK_BitCast) { 01827 checkCastAlign(); 01828 } 01829 01830 // Clear out SrcExpr if there was a fatal error. 01831 if (tcr != TC_Success) 01832 SrcExpr = ExprError(); 01833 } 01834 01835 /// Check the semantics of a C-style cast operation, in C. 01836 void CastOperation::CheckCStyleCast() { 01837 assert(!Self.getLangOptions().CPlusPlus); 01838 01839 // Handle placeholders. 01840 if (isPlaceholder()) { 01841 // C-style casts can resolve __unknown_any types. 01842 if (claimPlaceholder(BuiltinType::UnknownAny)) { 01843 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType, 01844 SrcExpr.get(), Kind, 01845 ValueKind, BasePath); 01846 return; 01847 } 01848 01849 checkNonOverloadPlaceholders(); 01850 if (SrcExpr.isInvalid()) 01851 return; 01852 } 01853 01854 assert(!isPlaceholder()); 01855 01856 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 01857 // type needs to be scalar. 01858 if (DestType->isVoidType()) { 01859 // We don't necessarily do lvalue-to-rvalue conversions on this. 01860 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take()); 01861 if (SrcExpr.isInvalid()) 01862 return; 01863 01864 // Cast to void allows any expr type. 01865 Kind = CK_ToVoid; 01866 return; 01867 } 01868 01869 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take()); 01870 if (SrcExpr.isInvalid()) 01871 return; 01872 QualType SrcType = SrcExpr.get()->getType(); 01873 01874 if (Self.RequireCompleteType(OpRange.getBegin(), DestType, 01875 diag::err_typecheck_cast_to_incomplete)) { 01876 SrcExpr = ExprError(); 01877 return; 01878 } 01879 01880 if (!DestType->isScalarType() && !DestType->isVectorType()) { 01881 const RecordType *DestRecordTy = DestType->getAs<RecordType>(); 01882 01883 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){ 01884 // GCC struct/union extension: allow cast to self. 01885 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar) 01886 << DestType << SrcExpr.get()->getSourceRange(); 01887 Kind = CK_NoOp; 01888 return; 01889 } 01890 01891 // GCC's cast to union extension. 01892 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) { 01893 RecordDecl *RD = DestRecordTy->getDecl(); 01894 RecordDecl::field_iterator Field, FieldEnd; 01895 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 01896 Field != FieldEnd; ++Field) { 01897 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) && 01898 !Field->isUnnamedBitfield()) { 01899 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union) 01900 << SrcExpr.get()->getSourceRange(); 01901 break; 01902 } 01903 } 01904 if (Field == FieldEnd) { 01905 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type) 01906 << SrcType << SrcExpr.get()->getSourceRange(); 01907 SrcExpr = ExprError(); 01908 return; 01909 } 01910 Kind = CK_ToUnion; 01911 return; 01912 } 01913 01914 // Reject any other conversions to non-scalar types. 01915 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar) 01916 << DestType << SrcExpr.get()->getSourceRange(); 01917 SrcExpr = ExprError(); 01918 return; 01919 } 01920 01921 // The type we're casting to is known to be a scalar or vector. 01922 01923 // Require the operand to be a scalar or vector. 01924 if (!SrcType->isScalarType() && !SrcType->isVectorType()) { 01925 Self.Diag(SrcExpr.get()->getExprLoc(), 01926 diag::err_typecheck_expect_scalar_operand) 01927 << SrcType << SrcExpr.get()->getSourceRange(); 01928 SrcExpr = ExprError(); 01929 return; 01930 } 01931 01932 if (DestType->isExtVectorType()) { 01933 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind); 01934 return; 01935 } 01936 01937 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) { 01938 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector && 01939 (SrcType->isIntegerType() || SrcType->isFloatingType())) { 01940 Kind = CK_VectorSplat; 01941 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) { 01942 SrcExpr = ExprError(); 01943 } 01944 return; 01945 } 01946 01947 if (SrcType->isVectorType()) { 01948 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind)) 01949 SrcExpr = ExprError(); 01950 return; 01951 } 01952 01953 // The source and target types are both scalars, i.e. 01954 // - arithmetic types (fundamental, enum, and complex) 01955 // - all kinds of pointers 01956 // Note that member pointers were filtered out with C++, above. 01957 01958 if (isa<ObjCSelectorExpr>(SrcExpr.get())) { 01959 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr); 01960 SrcExpr = ExprError(); 01961 return; 01962 } 01963 01964 // If either type is a pointer, the other type has to be either an 01965 // integer or a pointer. 01966 if (!DestType->isArithmeticType()) { 01967 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) { 01968 Self.Diag(SrcExpr.get()->getExprLoc(), 01969 diag::err_cast_pointer_from_non_pointer_int) 01970 << SrcType << SrcExpr.get()->getSourceRange(); 01971 SrcExpr = ExprError(); 01972 return; 01973 } 01974 } else if (!SrcType->isArithmeticType()) { 01975 if (!DestType->isIntegralType(Self.Context) && 01976 DestType->isArithmeticType()) { 01977 Self.Diag(SrcExpr.get()->getLocStart(), 01978 diag::err_cast_pointer_to_non_pointer_int) 01979 << SrcType << SrcExpr.get()->getSourceRange(); 01980 SrcExpr = ExprError(); 01981 return; 01982 } 01983 } 01984 01985 // ARC imposes extra restrictions on casts. 01986 if (Self.getLangOptions().ObjCAutoRefCount) { 01987 checkObjCARCConversion(Sema::CCK_CStyleCast); 01988 if (SrcExpr.isInvalid()) 01989 return; 01990 01991 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) { 01992 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) { 01993 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 01994 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 01995 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 01996 ExprPtr->getPointeeType()->isObjCLifetimeType() && 01997 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 01998 Self.Diag(SrcExpr.get()->getLocStart(), 01999 diag::err_typecheck_incompatible_ownership) 02000 << SrcType << DestType << Sema::AA_Casting 02001 << SrcExpr.get()->getSourceRange(); 02002 return; 02003 } 02004 } 02005 } 02006 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) { 02007 Self.Diag(SrcExpr.get()->getLocStart(), 02008 diag::err_arc_convesion_of_weak_unavailable) 02009 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange(); 02010 SrcExpr = ExprError(); 02011 return; 02012 } 02013 } 02014 02015 Kind = Self.PrepareScalarCast(SrcExpr, DestType); 02016 if (SrcExpr.isInvalid()) 02017 return; 02018 02019 if (Kind == CK_BitCast) 02020 checkCastAlign(); 02021 } 02022 02023 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc, 02024 TypeSourceInfo *CastTypeInfo, 02025 SourceLocation RPLoc, 02026 Expr *CastExpr) { 02027 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 02028 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 02029 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd()); 02030 02031 if (getLangOptions().CPlusPlus) { 02032 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false); 02033 } else { 02034 Op.CheckCStyleCast(); 02035 } 02036 02037 if (Op.SrcExpr.isInvalid()) 02038 return ExprError(); 02039 02040 return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind, 02041 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, 02042 CastTypeInfo, LPLoc, RPLoc)); 02043 } 02044 02045 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo, 02046 SourceLocation LPLoc, 02047 Expr *CastExpr, 02048 SourceLocation RPLoc) { 02049 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr); 02050 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange(); 02051 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd()); 02052 02053 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true); 02054 if (Op.SrcExpr.isInvalid()) 02055 return ExprError(); 02056 02057 return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType, 02058 Op.ValueKind, CastTypeInfo, 02059 Op.DestRange.getBegin(), 02060 Op.Kind, Op.SrcExpr.take(), 02061 &Op.BasePath, RPLoc)); 02062 }