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