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