SemaCast.cpp revision 263508
1228072Sbapt//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
2228072Sbapt//
3228072Sbapt//                     The LLVM Compiler Infrastructure
4228072Sbapt//
5228072Sbapt// This file is distributed under the University of Illinois Open Source
6228072Sbapt// License. See LICENSE.TXT for details.
7228072Sbapt//
8228072Sbapt//===----------------------------------------------------------------------===//
9228072Sbapt//
10228072Sbapt//  This file implements semantic analysis for cast expressions, including
11228072Sbapt//  1) C-style casts like '(int) x'
12228072Sbapt//  2) C++ functional casts like 'int(x)'
13228072Sbapt//  3) C++ named casts like 'static_cast<int>(x)'
14228072Sbapt//
15228072Sbapt//===----------------------------------------------------------------------===//
16228072Sbapt
17228072Sbapt#include "clang/Sema/SemaInternal.h"
18228072Sbapt#include "clang/AST/ASTContext.h"
19228072Sbapt#include "clang/AST/CXXInheritance.h"
20228072Sbapt#include "clang/AST/ExprCXX.h"
21228072Sbapt#include "clang/AST/ExprObjC.h"
22228072Sbapt#include "clang/AST/RecordLayout.h"
23228072Sbapt#include "clang/Basic/PartialDiagnostic.h"
24228072Sbapt#include "clang/Sema/Initialization.h"
25228072Sbapt#include "llvm/ADT/SmallVector.h"
26228072Sbapt#include <set>
27228072Sbaptusing namespace clang;
28228072Sbapt
29228072Sbapt
30228072Sbapt
31228072Sbaptenum TryCastResult {
32228072Sbapt  TC_NotApplicable, ///< The cast method is not applicable.
33228072Sbapt  TC_Success,       ///< The cast method is appropriate and successful.
34228072Sbapt  TC_Failed         ///< The cast method is appropriate, but failed. A
35228072Sbapt                    ///< diagnostic has been emitted.
36228072Sbapt};
37228072Sbapt
38228072Sbaptenum CastType {
39228072Sbapt  CT_Const,       ///< const_cast
40228072Sbapt  CT_Static,      ///< static_cast
41228072Sbapt  CT_Reinterpret, ///< reinterpret_cast
42228072Sbapt  CT_Dynamic,     ///< dynamic_cast
43228072Sbapt  CT_CStyle,      ///< (Type)expr
44228072Sbapt  CT_Functional   ///< Type(expr)
45228072Sbapt};
46228072Sbapt
47228072Sbaptnamespace {
48228072Sbapt  struct CastOperation {
49228072Sbapt    CastOperation(Sema &S, QualType destType, ExprResult src)
50228072Sbapt      : Self(S), SrcExpr(src), DestType(destType),
51228072Sbapt        ResultType(destType.getNonLValueExprType(S.Context)),
52228072Sbapt        ValueKind(Expr::getValueKindForType(destType)),
53228072Sbapt        Kind(CK_Dependent), IsARCUnbridgedCast(false) {
54228072Sbapt
55228072Sbapt      if (const BuiltinType *placeholder =
56228072Sbapt            src.get()->getType()->getAsPlaceholderType()) {
57228072Sbapt        PlaceholderKind = placeholder->getKind();
58228072Sbapt      } else {
59228072Sbapt        PlaceholderKind = (BuiltinType::Kind) 0;
60228072Sbapt      }
61228072Sbapt    }
62228072Sbapt
63228072Sbapt    Sema &Self;
64228072Sbapt    ExprResult SrcExpr;
65228072Sbapt    QualType DestType;
66228072Sbapt    QualType ResultType;
67228072Sbapt    ExprValueKind ValueKind;
68228072Sbapt    CastKind Kind;
69228072Sbapt    BuiltinType::Kind PlaceholderKind;
70228072Sbapt    CXXCastPath BasePath;
71228072Sbapt    bool IsARCUnbridgedCast;
72228072Sbapt
73228072Sbapt    SourceRange OpRange;
74228072Sbapt    SourceRange DestRange;
75228072Sbapt
76228072Sbapt    // Top-level semantics-checking routines.
77228072Sbapt    void CheckConstCast();
78228072Sbapt    void CheckReinterpretCast();
79228072Sbapt    void CheckStaticCast();
80228072Sbapt    void CheckDynamicCast();
81228072Sbapt    void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
82228072Sbapt    void CheckCStyleCast();
83228072Sbapt
84228072Sbapt    /// Complete an apparently-successful cast operation that yields
85228072Sbapt    /// the given expression.
86228072Sbapt    ExprResult complete(CastExpr *castExpr) {
87228072Sbapt      // If this is an unbridged cast, wrap the result in an implicit
88228072Sbapt      // cast that yields the unbridged-cast placeholder type.
89228072Sbapt      if (IsARCUnbridgedCast) {
90228072Sbapt        castExpr = ImplicitCastExpr::Create(Self.Context,
91228072Sbapt                                            Self.Context.ARCUnbridgedCastTy,
92228072Sbapt                                            CK_Dependent, castExpr, 0,
93228072Sbapt                                            castExpr->getValueKind());
94228072Sbapt      }
95228072Sbapt      return Self.Owned(castExpr);
96228072Sbapt    }
97228072Sbapt
98228072Sbapt    // Internal convenience methods.
99228072Sbapt
100228072Sbapt    /// Try to handle the given placeholder expression kind.  Return
101228072Sbapt    /// true if the source expression has the appropriate placeholder
102228072Sbapt    /// kind.  A placeholder can only be claimed once.
103228072Sbapt    bool claimPlaceholder(BuiltinType::Kind K) {
104228072Sbapt      if (PlaceholderKind != K) return false;
105228072Sbapt
106228072Sbapt      PlaceholderKind = (BuiltinType::Kind) 0;
107228072Sbapt      return true;
108228072Sbapt    }
109228072Sbapt
110228072Sbapt    bool isPlaceholder() const {
111228072Sbapt      return PlaceholderKind != 0;
112228072Sbapt    }
113228072Sbapt    bool isPlaceholder(BuiltinType::Kind K) const {
114228072Sbapt      return PlaceholderKind == K;
115228072Sbapt    }
116228072Sbapt
117228072Sbapt    void checkCastAlign() {
118228072Sbapt      Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
119228072Sbapt    }
120228072Sbapt
121228072Sbapt    void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
122228072Sbapt      assert(Self.getLangOpts().ObjCAutoRefCount);
123228072Sbapt
124228072Sbapt      Expr *src = SrcExpr.get();
125228072Sbapt      if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
126228072Sbapt            Sema::ACR_unbridged)
127228072Sbapt        IsARCUnbridgedCast = true;
128228072Sbapt      SrcExpr = src;
129228072Sbapt    }
130228072Sbapt
131228072Sbapt    /// Check for and handle non-overload placeholder expressions.
132228072Sbapt    void checkNonOverloadPlaceholders() {
133228072Sbapt      if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
134228072Sbapt        return;
135228072Sbapt
136228072Sbapt      SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
137228072Sbapt      if (SrcExpr.isInvalid())
138228072Sbapt        return;
139228072Sbapt      PlaceholderKind = (BuiltinType::Kind) 0;
140228072Sbapt    }
141228072Sbapt  };
142228072Sbapt}
143228072Sbapt
144228072Sbaptstatic bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145228072Sbapt                               bool CheckCVR, bool CheckObjCLifetime);
146228072Sbapt
147228072Sbapt// The Try functions attempt a specific way of casting. If they succeed, they
148228072Sbapt// return TC_Success. If their way of casting is not appropriate for the given
149228072Sbapt// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
150228072Sbapt// to emit if no other way succeeds. If their way of casting is appropriate but
151228072Sbapt// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
152228072Sbapt// they emit a specialized diagnostic.
153228072Sbapt// All diagnostics returned by these functions must expect the same three
154228072Sbapt// arguments:
155228072Sbapt// %0: Cast Type (a value from the CastType enumeration)
156228072Sbapt// %1: Source Type
157228072Sbapt// %2: Destination Type
158228072Sbaptstatic TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
159228072Sbapt                                           QualType DestType, bool CStyle,
160228072Sbapt                                           CastKind &Kind,
161228072Sbapt                                           CXXCastPath &BasePath,
162228072Sbapt                                           unsigned &msg);
163228072Sbaptstatic TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
164228072Sbapt                                               QualType DestType, bool CStyle,
165228072Sbapt                                               const SourceRange &OpRange,
166228072Sbapt                                               unsigned &msg,
167228072Sbapt                                               CastKind &Kind,
168228072Sbapt                                               CXXCastPath &BasePath);
169228072Sbaptstatic TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170228072Sbapt                                              QualType DestType, bool CStyle,
171228072Sbapt                                              const SourceRange &OpRange,
172228072Sbapt                                              unsigned &msg,
173228072Sbapt                                              CastKind &Kind,
174228072Sbapt                                              CXXCastPath &BasePath);
175228072Sbaptstatic TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176228072Sbapt                                       CanQualType DestType, bool CStyle,
177228072Sbapt                                       const SourceRange &OpRange,
178228072Sbapt                                       QualType OrigSrcType,
179228072Sbapt                                       QualType OrigDestType, unsigned &msg,
180228072Sbapt                                       CastKind &Kind,
181228072Sbapt                                       CXXCastPath &BasePath);
182228072Sbaptstatic TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
183228072Sbapt                                               QualType SrcType,
184228072Sbapt                                               QualType DestType,bool CStyle,
185228072Sbapt                                               const SourceRange &OpRange,
186228072Sbapt                                               unsigned &msg,
187228072Sbapt                                               CastKind &Kind,
188228072Sbapt                                               CXXCastPath &BasePath);
189228072Sbapt
190228072Sbaptstatic TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
191228072Sbapt                                           QualType DestType,
192228072Sbapt                                           Sema::CheckedConversionKind CCK,
193228072Sbapt                                           const SourceRange &OpRange,
194228072Sbapt                                           unsigned &msg, CastKind &Kind,
195228072Sbapt                                           bool ListInitialization);
196228072Sbaptstatic TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
197228072Sbapt                                   QualType DestType,
198228072Sbapt                                   Sema::CheckedConversionKind CCK,
199228072Sbapt                                   const SourceRange &OpRange,
200228072Sbapt                                   unsigned &msg, CastKind &Kind,
201228072Sbapt                                   CXXCastPath &BasePath,
202228072Sbapt                                   bool ListInitialization);
203228072Sbaptstatic TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
204228072Sbapt                                  QualType DestType, bool CStyle,
205228072Sbapt                                  unsigned &msg);
206228072Sbaptstatic TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
207228072Sbapt                                        QualType DestType, bool CStyle,
208228072Sbapt                                        const SourceRange &OpRange,
209228072Sbapt                                        unsigned &msg,
210228072Sbapt                                        CastKind &Kind);
211228072Sbapt
212228072Sbapt
213228072Sbapt/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
214228072SbaptExprResult
215228072SbaptSema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
216228072Sbapt                        SourceLocation LAngleBracketLoc, Declarator &D,
217228072Sbapt                        SourceLocation RAngleBracketLoc,
218228072Sbapt                        SourceLocation LParenLoc, Expr *E,
219228072Sbapt                        SourceLocation RParenLoc) {
220228072Sbapt
221228072Sbapt  assert(!D.isInvalidType());
222228072Sbapt
223228072Sbapt  TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
224228072Sbapt  if (D.isInvalidType())
225228072Sbapt    return ExprError();
226228072Sbapt
227228072Sbapt  if (getLangOpts().CPlusPlus) {
228228072Sbapt    // Check that there are no default arguments (C++ only).
229228072Sbapt    CheckExtraCXXDefaultArguments(D);
230228072Sbapt  }
231228072Sbapt
232228072Sbapt  return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
233228072Sbapt                           SourceRange(LAngleBracketLoc, RAngleBracketLoc),
234228072Sbapt                           SourceRange(LParenLoc, RParenLoc));
235228072Sbapt}
236228072Sbapt
237228072SbaptExprResult
238228072SbaptSema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
239228072Sbapt                        TypeSourceInfo *DestTInfo, Expr *E,
240228072Sbapt                        SourceRange AngleBrackets, SourceRange Parens) {
241228072Sbapt  ExprResult Ex = Owned(E);
242228072Sbapt  QualType DestType = DestTInfo->getType();
243228072Sbapt
244228072Sbapt  // If the type is dependent, we won't do the semantic analysis now.
245228072Sbapt  // FIXME: should we check this in a more fine-grained manner?
246228072Sbapt  bool TypeDependent = DestType->isDependentType() ||
247228072Sbapt                       Ex.get()->isTypeDependent() ||
248228072Sbapt                       Ex.get()->isValueDependent();
249228072Sbapt
250228072Sbapt  CastOperation Op(*this, DestType, E);
251228072Sbapt  Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252228072Sbapt  Op.DestRange = AngleBrackets;
253228072Sbapt
254228072Sbapt  switch (Kind) {
255228072Sbapt  default: llvm_unreachable("Unknown C++ cast!");
256228072Sbapt
257228072Sbapt  case tok::kw_const_cast:
258228072Sbapt    if (!TypeDependent) {
259228072Sbapt      Op.CheckConstCast();
260228072Sbapt      if (Op.SrcExpr.isInvalid())
261228072Sbapt        return ExprError();
262228072Sbapt    }
263228072Sbapt    return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
264228072Sbapt                                  Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
265228072Sbapt                                                OpLoc, Parens.getEnd(),
266228072Sbapt                                                AngleBrackets));
267228072Sbapt
268228072Sbapt  case tok::kw_dynamic_cast: {
269228072Sbapt    if (!TypeDependent) {
270228072Sbapt      Op.CheckDynamicCast();
271228072Sbapt      if (Op.SrcExpr.isInvalid())
272228072Sbapt        return ExprError();
273228072Sbapt    }
274228072Sbapt    return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
275228072Sbapt                                    Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
276228072Sbapt                                                  &Op.BasePath, DestTInfo,
277228072Sbapt                                                  OpLoc, Parens.getEnd(),
278228072Sbapt                                                  AngleBrackets));
279228072Sbapt  }
280228072Sbapt  case tok::kw_reinterpret_cast: {
281228072Sbapt    if (!TypeDependent) {
282228072Sbapt      Op.CheckReinterpretCast();
283228072Sbapt      if (Op.SrcExpr.isInvalid())
284228072Sbapt        return ExprError();
285228072Sbapt    }
286228072Sbapt    return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
287228072Sbapt                                    Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
288228072Sbapt                                                      0, DestTInfo, OpLoc,
289228072Sbapt                                                      Parens.getEnd(),
290228072Sbapt                                                      AngleBrackets));
291228072Sbapt  }
292228072Sbapt  case tok::kw_static_cast: {
293228072Sbapt    if (!TypeDependent) {
294228072Sbapt      Op.CheckStaticCast();
295228072Sbapt      if (Op.SrcExpr.isInvalid())
296228072Sbapt        return ExprError();
297228072Sbapt    }
298228072Sbapt
299228072Sbapt    return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
300228072Sbapt                                   Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
301228072Sbapt                                                 &Op.BasePath, DestTInfo,
302228072Sbapt                                                 OpLoc, Parens.getEnd(),
303228072Sbapt                                                 AngleBrackets));
304228072Sbapt  }
305228072Sbapt  }
306228072Sbapt}
307228072Sbapt
308228072Sbapt/// Try to diagnose a failed overloaded cast.  Returns true if
309228072Sbapt/// diagnostics were emitted.
310228072Sbaptstatic bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
311228072Sbapt                                      SourceRange range, Expr *src,
312228072Sbapt                                      QualType destType,
313228072Sbapt                                      bool listInitialization) {
314228072Sbapt  switch (CT) {
315228072Sbapt  // These cast kinds don't consider user-defined conversions.
316228072Sbapt  case CT_Const:
317228072Sbapt  case CT_Reinterpret:
318228072Sbapt  case CT_Dynamic:
319228072Sbapt    return false;
320228072Sbapt
321228072Sbapt  // These do.
322228072Sbapt  case CT_Static:
323228072Sbapt  case CT_CStyle:
324228072Sbapt  case CT_Functional:
325228072Sbapt    break;
326228072Sbapt  }
327228072Sbapt
328228072Sbapt  QualType srcType = src->getType();
329228072Sbapt  if (!destType->isRecordType() && !srcType->isRecordType())
330228072Sbapt    return false;
331228072Sbapt
332228072Sbapt  InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
333228072Sbapt  InitializationKind initKind
334228072Sbapt    = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
335228072Sbapt                                                      range, listInitialization)
336228072Sbapt    : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
337228072Sbapt                                                             listInitialization)
338228072Sbapt    : InitializationKind::CreateCast(/*type range?*/ range);
339228072Sbapt  InitializationSequence sequence(S, entity, initKind, src);
340228072Sbapt
341228072Sbapt  assert(sequence.Failed() && "initialization succeeded on second try?");
342228072Sbapt  switch (sequence.getFailureKind()) {
343228072Sbapt  default: return false;
344228072Sbapt
345228072Sbapt  case InitializationSequence::FK_ConstructorOverloadFailed:
346228072Sbapt  case InitializationSequence::FK_UserConversionOverloadFailed:
347228072Sbapt    break;
348228072Sbapt  }
349228072Sbapt
350228072Sbapt  OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
351228072Sbapt
352228072Sbapt  unsigned msg = 0;
353228072Sbapt  OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
354228072Sbapt
355228072Sbapt  switch (sequence.getFailedOverloadResult()) {
356228072Sbapt  case OR_Success: llvm_unreachable("successful failed overload");
357228072Sbapt  case OR_No_Viable_Function:
358228072Sbapt    if (candidates.empty())
359228072Sbapt      msg = diag::err_ovl_no_conversion_in_cast;
360228072Sbapt    else
361228072Sbapt      msg = diag::err_ovl_no_viable_conversion_in_cast;
362228072Sbapt    howManyCandidates = OCD_AllCandidates;
363228072Sbapt    break;
364228072Sbapt
365228072Sbapt  case OR_Ambiguous:
366228072Sbapt    msg = diag::err_ovl_ambiguous_conversion_in_cast;
367228072Sbapt    howManyCandidates = OCD_ViableCandidates;
368228072Sbapt    break;
369228072Sbapt
370228072Sbapt  case OR_Deleted:
371228072Sbapt    msg = diag::err_ovl_deleted_conversion_in_cast;
372228072Sbapt    howManyCandidates = OCD_ViableCandidates;
373228072Sbapt    break;
374228072Sbapt  }
375228072Sbapt
376228072Sbapt  S.Diag(range.getBegin(), msg)
377228072Sbapt    << CT << srcType << destType
378228072Sbapt    << range << src->getSourceRange();
379228072Sbapt
380228072Sbapt  candidates.NoteCandidates(S, howManyCandidates, src);
381228072Sbapt
382228072Sbapt  return true;
383228072Sbapt}
384228072Sbapt
385228072Sbapt/// Diagnose a failed cast.
386228072Sbaptstatic void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
387228072Sbapt                            SourceRange opRange, Expr *src, QualType destType,
388228072Sbapt                            bool listInitialization) {
389228072Sbapt  if (msg == diag::err_bad_cxx_cast_generic &&
390228072Sbapt      tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
391228072Sbapt                                listInitialization))
392228072Sbapt    return;
393228072Sbapt
394228072Sbapt  S.Diag(opRange.getBegin(), msg) << castType
395228072Sbapt    << src->getType() << destType << opRange << src->getSourceRange();
396228072Sbapt}
397228072Sbapt
398228072Sbapt/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
399228072Sbapt/// this removes one level of indirection from both types, provided that they're
400228072Sbapt/// the same kind of pointer (plain or to-member). Unlike the Sema function,
401228072Sbapt/// this one doesn't care if the two pointers-to-member don't point into the
402228072Sbapt/// same class. This is because CastsAwayConstness doesn't care.
403228072Sbaptstatic bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
404228072Sbapt  const PointerType *T1PtrType = T1->getAs<PointerType>(),
405228072Sbapt                    *T2PtrType = T2->getAs<PointerType>();
406228072Sbapt  if (T1PtrType && T2PtrType) {
407228072Sbapt    T1 = T1PtrType->getPointeeType();
408228072Sbapt    T2 = T2PtrType->getPointeeType();
409228072Sbapt    return true;
410228072Sbapt  }
411228072Sbapt  const ObjCObjectPointerType *T1ObjCPtrType =
412228072Sbapt                                            T1->getAs<ObjCObjectPointerType>(),
413228072Sbapt                              *T2ObjCPtrType =
414228072Sbapt                                            T2->getAs<ObjCObjectPointerType>();
415228072Sbapt  if (T1ObjCPtrType) {
416228072Sbapt    if (T2ObjCPtrType) {
417228072Sbapt      T1 = T1ObjCPtrType->getPointeeType();
418228072Sbapt      T2 = T2ObjCPtrType->getPointeeType();
419228072Sbapt      return true;
420228072Sbapt    }
421228072Sbapt    else if (T2PtrType) {
422228072Sbapt      T1 = T1ObjCPtrType->getPointeeType();
423228072Sbapt      T2 = T2PtrType->getPointeeType();
424228072Sbapt      return true;
425228072Sbapt    }
426228072Sbapt  }
427228072Sbapt  else if (T2ObjCPtrType) {
428228072Sbapt    if (T1PtrType) {
429228072Sbapt      T2 = T2ObjCPtrType->getPointeeType();
430228072Sbapt      T1 = T1PtrType->getPointeeType();
431228072Sbapt      return true;
432228072Sbapt    }
433228072Sbapt  }
434228072Sbapt
435228072Sbapt  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
436228072Sbapt                          *T2MPType = T2->getAs<MemberPointerType>();
437228072Sbapt  if (T1MPType && T2MPType) {
438228072Sbapt    T1 = T1MPType->getPointeeType();
439228072Sbapt    T2 = T2MPType->getPointeeType();
440228072Sbapt    return true;
441228072Sbapt  }
442228072Sbapt
443228072Sbapt  const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
444228072Sbapt                         *T2BPType = T2->getAs<BlockPointerType>();
445228072Sbapt  if (T1BPType && T2BPType) {
446228072Sbapt    T1 = T1BPType->getPointeeType();
447228072Sbapt    T2 = T2BPType->getPointeeType();
448228072Sbapt    return true;
449228072Sbapt  }
450228072Sbapt
451228072Sbapt  return false;
452228072Sbapt}
453228072Sbapt
454228072Sbapt/// CastsAwayConstness - Check if the pointer conversion from SrcType to
455228072Sbapt/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
456228072Sbapt/// the cast checkers.  Both arguments must denote pointer (possibly to member)
457228072Sbapt/// types.
458228072Sbapt///
459228072Sbapt/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
460228072Sbapt///
461228072Sbapt/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
462228072Sbaptstatic bool
463228072SbaptCastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
464228072Sbapt                   bool CheckCVR, bool CheckObjCLifetime) {
465228072Sbapt  // If the only checking we care about is for Objective-C lifetime qualifiers,
466228072Sbapt  // and we're not in ARC mode, there's nothing to check.
467228072Sbapt  if (!CheckCVR && CheckObjCLifetime &&
468228072Sbapt      !Self.Context.getLangOpts().ObjCAutoRefCount)
469228072Sbapt    return false;
470228072Sbapt
471228072Sbapt  // Casting away constness is defined in C++ 5.2.11p8 with reference to
472228072Sbapt  // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
473228072Sbapt  // the rules are non-trivial. So first we construct Tcv *...cv* as described
474228072Sbapt  // in C++ 5.2.11p8.
475228072Sbapt  assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
476228072Sbapt          SrcType->isBlockPointerType()) &&
477228072Sbapt         "Source type is not pointer or pointer to member.");
478228072Sbapt  assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
479228072Sbapt          DestType->isBlockPointerType()) &&
480228072Sbapt         "Destination type is not pointer or pointer to member.");
481228072Sbapt
482228072Sbapt  QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
483228072Sbapt           UnwrappedDestType = Self.Context.getCanonicalType(DestType);
484228072Sbapt  SmallVector<Qualifiers, 8> cv1, cv2;
485228072Sbapt
486228072Sbapt  // Find the qualifiers. We only care about cvr-qualifiers for the
487228072Sbapt  // purpose of this check, because other qualifiers (address spaces,
488228072Sbapt  // Objective-C GC, etc.) are part of the type's identity.
489228072Sbapt  while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
490228072Sbapt    // Determine the relevant qualifiers at this level.
491228072Sbapt    Qualifiers SrcQuals, DestQuals;
492228072Sbapt    Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
493228072Sbapt    Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
494228072Sbapt
495228072Sbapt    Qualifiers RetainedSrcQuals, RetainedDestQuals;
496228072Sbapt    if (CheckCVR) {
497228072Sbapt      RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
498228072Sbapt      RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
499228072Sbapt    }
500228072Sbapt
501228072Sbapt    if (CheckObjCLifetime &&
502228072Sbapt        !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
503228072Sbapt      return true;
504228072Sbapt
505228072Sbapt    cv1.push_back(RetainedSrcQuals);
506228072Sbapt    cv2.push_back(RetainedDestQuals);
507228072Sbapt  }
508228072Sbapt  if (cv1.empty())
509228072Sbapt    return false;
510228072Sbapt
511228072Sbapt  // Construct void pointers with those qualifiers (in reverse order of
512228072Sbapt  // unwrapping, of course).
513228072Sbapt  QualType SrcConstruct = Self.Context.VoidTy;
514228072Sbapt  QualType DestConstruct = Self.Context.VoidTy;
515228072Sbapt  ASTContext &Context = Self.Context;
516228072Sbapt  for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
517228072Sbapt                                                     i2 = cv2.rbegin();
518228072Sbapt       i1 != cv1.rend(); ++i1, ++i2) {
519228072Sbapt    SrcConstruct
520228072Sbapt      = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
521228072Sbapt    DestConstruct
522228072Sbapt      = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
523228072Sbapt  }
524228072Sbapt
525228072Sbapt  // Test if they're compatible.
526228072Sbapt  bool ObjCLifetimeConversion;
527228072Sbapt  return SrcConstruct != DestConstruct &&
528228072Sbapt    !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
529228072Sbapt                                    ObjCLifetimeConversion);
530228072Sbapt}
531228072Sbapt
532228072Sbapt/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
533228072Sbapt/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
534228072Sbapt/// checked downcasts in class hierarchies.
535228072Sbaptvoid CastOperation::CheckDynamicCast() {
536228072Sbapt  if (ValueKind == VK_RValue)
537228072Sbapt    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
538228072Sbapt  else if (isPlaceholder())
539228072Sbapt    SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
540228072Sbapt  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
541228072Sbapt    return;
542228072Sbapt
543228072Sbapt  QualType OrigSrcType = SrcExpr.get()->getType();
544228072Sbapt  QualType DestType = Self.Context.getCanonicalType(this->DestType);
545228072Sbapt
546228072Sbapt  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
547228072Sbapt  //   or "pointer to cv void".
548228072Sbapt
549228072Sbapt  QualType DestPointee;
550228072Sbapt  const PointerType *DestPointer = DestType->getAs<PointerType>();
551228072Sbapt  const ReferenceType *DestReference = 0;
552228072Sbapt  if (DestPointer) {
553228072Sbapt    DestPointee = DestPointer->getPointeeType();
554228072Sbapt  } else if ((DestReference = DestType->getAs<ReferenceType>())) {
555228072Sbapt    DestPointee = DestReference->getPointeeType();
556228072Sbapt  } else {
557228072Sbapt    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
558228072Sbapt      << this->DestType << DestRange;
559228072Sbapt    SrcExpr = ExprError();
560228072Sbapt    return;
561228072Sbapt  }
562228072Sbapt
563228072Sbapt  const RecordType *DestRecord = DestPointee->getAs<RecordType>();
564228072Sbapt  if (DestPointee->isVoidType()) {
565228072Sbapt    assert(DestPointer && "Reference to void is not possible");
566228072Sbapt  } else if (DestRecord) {
567228072Sbapt    if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
568228072Sbapt                                 diag::err_bad_dynamic_cast_incomplete,
569228072Sbapt                                 DestRange)) {
570228072Sbapt      SrcExpr = ExprError();
571228072Sbapt      return;
572228072Sbapt    }
573228072Sbapt  } else {
574228072Sbapt    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
575228072Sbapt      << DestPointee.getUnqualifiedType() << DestRange;
576228072Sbapt    SrcExpr = ExprError();
577228072Sbapt    return;
578228072Sbapt  }
579228072Sbapt
580228072Sbapt  // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
581228072Sbapt  //   complete class type, [...]. If T is an lvalue reference type, v shall be
582228072Sbapt  //   an lvalue of a complete class type, [...]. If T is an rvalue reference
583228072Sbapt  //   type, v shall be an expression having a complete class type, [...]
584228072Sbapt  QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
585228072Sbapt  QualType SrcPointee;
586228072Sbapt  if (DestPointer) {
587228072Sbapt    if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
588228072Sbapt      SrcPointee = SrcPointer->getPointeeType();
589228072Sbapt    } else {
590228072Sbapt      Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
591228072Sbapt        << OrigSrcType << SrcExpr.get()->getSourceRange();
592228072Sbapt      SrcExpr = ExprError();
593228072Sbapt      return;
594228072Sbapt    }
595228072Sbapt  } else if (DestReference->isLValueReferenceType()) {
596228072Sbapt    if (!SrcExpr.get()->isLValue()) {
597228072Sbapt      Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
598228072Sbapt        << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
599228072Sbapt    }
600228072Sbapt    SrcPointee = SrcType;
601228072Sbapt  } else {
602228072Sbapt    SrcPointee = SrcType;
603228072Sbapt  }
604228072Sbapt
605228072Sbapt  const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
606228072Sbapt  if (SrcRecord) {
607228072Sbapt    if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
608228072Sbapt                                 diag::err_bad_dynamic_cast_incomplete,
609228072Sbapt                                 SrcExpr.get())) {
610228072Sbapt      SrcExpr = ExprError();
611228072Sbapt      return;
612228072Sbapt    }
613228072Sbapt  } else {
614228072Sbapt    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
615228072Sbapt      << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
616228072Sbapt    SrcExpr = ExprError();
617228072Sbapt    return;
618228072Sbapt  }
619228072Sbapt
620228072Sbapt  assert((DestPointer || DestReference) &&
621228072Sbapt    "Bad destination non-ptr/ref slipped through.");
622228072Sbapt  assert((DestRecord || DestPointee->isVoidType()) &&
623228072Sbapt    "Bad destination pointee slipped through.");
624228072Sbapt  assert(SrcRecord && "Bad source pointee slipped through.");
625228072Sbapt
626228072Sbapt  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
627228072Sbapt  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
628228072Sbapt    Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
629228072Sbapt      << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
630228072Sbapt    SrcExpr = ExprError();
631228072Sbapt    return;
632228072Sbapt  }
633228072Sbapt
634228072Sbapt  // C++ 5.2.7p3: If the type of v is the same as the required result type,
635228072Sbapt  //   [except for cv].
636228072Sbapt  if (DestRecord == SrcRecord) {
637228072Sbapt    Kind = CK_NoOp;
638228072Sbapt    return;
639228072Sbapt  }
640228072Sbapt
641228072Sbapt  // C++ 5.2.7p5
642228072Sbapt  // Upcasts are resolved statically.
643228072Sbapt  if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
644228072Sbapt    if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
645228072Sbapt                                           OpRange.getBegin(), OpRange,
646228072Sbapt                                           &BasePath)) {
647228072Sbapt      SrcExpr = ExprError();
648228072Sbapt      return;
649228072Sbapt    }
650228072Sbapt
651228072Sbapt    Kind = CK_DerivedToBase;
652228072Sbapt
653228072Sbapt    // If we are casting to or through a virtual base class, we need a
654228072Sbapt    // vtable.
655228072Sbapt    if (Self.BasePathInvolvesVirtualBase(BasePath))
656228072Sbapt      Self.MarkVTableUsed(OpRange.getBegin(),
657228072Sbapt                          cast<CXXRecordDecl>(SrcRecord->getDecl()));
658228072Sbapt    return;
659228072Sbapt  }
660228072Sbapt
661228072Sbapt  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
662228072Sbapt  const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
663228072Sbapt  assert(SrcDecl && "Definition missing");
664228072Sbapt  if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
665228072Sbapt    Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
666228072Sbapt      << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
667228072Sbapt    SrcExpr = ExprError();
668228072Sbapt  }
669228072Sbapt  Self.MarkVTableUsed(OpRange.getBegin(),
670228072Sbapt                      cast<CXXRecordDecl>(SrcRecord->getDecl()));
671228072Sbapt
672228072Sbapt  // dynamic_cast is not available with -fno-rtti.
673228072Sbapt  // As an exception, dynamic_cast to void* is available because it doesn't
674228072Sbapt  // use RTTI.
675228072Sbapt  if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
676228072Sbapt    Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
677228072Sbapt    SrcExpr = ExprError();
678228072Sbapt    return;
679228072Sbapt  }
680228072Sbapt
681228072Sbapt  // Done. Everything else is run-time checks.
682228072Sbapt  Kind = CK_Dynamic;
683228072Sbapt}
684228072Sbapt
685228072Sbapt/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
686228072Sbapt/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
687228072Sbapt/// like this:
688228072Sbapt/// const char *str = "literal";
689228072Sbapt/// legacy_function(const_cast\<char*\>(str));
690228072Sbaptvoid CastOperation::CheckConstCast() {
691228072Sbapt  if (ValueKind == VK_RValue)
692228072Sbapt    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
693228072Sbapt  else if (isPlaceholder())
694228072Sbapt    SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
695228072Sbapt  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
696228072Sbapt    return;
697228072Sbapt
698228072Sbapt  unsigned msg = diag::err_bad_cxx_cast_generic;
699228072Sbapt  if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
700228072Sbapt      && msg != 0) {
701228072Sbapt    Self.Diag(OpRange.getBegin(), msg) << CT_Const
702228072Sbapt      << SrcExpr.get()->getType() << DestType << OpRange;
703228072Sbapt    SrcExpr = ExprError();
704228072Sbapt  }
705228072Sbapt}
706228072Sbapt
707228072Sbapt/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
708228072Sbapt/// or downcast between respective pointers or references.
709228072Sbaptstatic void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
710228072Sbapt                                          QualType DestType,
711228072Sbapt                                          SourceRange OpRange) {
712228072Sbapt  QualType SrcType = SrcExpr->getType();
713228072Sbapt  // When casting from pointer or reference, get pointee type; use original
714228072Sbapt  // type otherwise.
715228072Sbapt  const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
716228072Sbapt  const CXXRecordDecl *SrcRD =
717228072Sbapt    SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
718228072Sbapt
719228072Sbapt  // Examining subobjects for records is only possible if the complete and
720228072Sbapt  // valid definition is available.  Also, template instantiation is not
721228072Sbapt  // allowed here.
722228072Sbapt  if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
723228072Sbapt    return;
724228072Sbapt
725228072Sbapt  const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
726250125Sjkim
727228072Sbapt  if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
728250125Sjkim    return;
729228072Sbapt
730228072Sbapt  enum {
731228072Sbapt    ReinterpretUpcast,
732228072Sbapt    ReinterpretDowncast
733228072Sbapt  } ReinterpretKind;
734228072Sbapt
735228072Sbapt  CXXBasePaths BasePaths;
736228072Sbapt
737228072Sbapt  if (SrcRD->isDerivedFrom(DestRD, BasePaths))
738228072Sbapt    ReinterpretKind = ReinterpretUpcast;
739228072Sbapt  else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
740228072Sbapt    ReinterpretKind = ReinterpretDowncast;
741228072Sbapt  else
742228072Sbapt    return;
743228072Sbapt
744228072Sbapt  bool VirtualBase = true;
745228072Sbapt  bool NonZeroOffset = false;
746228072Sbapt  for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
747228072Sbapt                                          E = BasePaths.end();
748228072Sbapt       I != E; ++I) {
749228072Sbapt    const CXXBasePath &Path = *I;
750228072Sbapt    CharUnits Offset = CharUnits::Zero();
751228072Sbapt    bool IsVirtual = false;
752228072Sbapt    for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
753228072Sbapt         IElem != EElem; ++IElem) {
754228072Sbapt      IsVirtual = IElem->Base->isVirtual();
755228072Sbapt      if (IsVirtual)
756228072Sbapt        break;
757228072Sbapt      const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
758228072Sbapt      assert(BaseRD && "Base type should be a valid unqualified class type");
759228072Sbapt      // Don't check if any base has invalid declaration or has no definition
760228072Sbapt      // since it has no layout info.
761228072Sbapt      const CXXRecordDecl *Class = IElem->Class,
762228072Sbapt                          *ClassDefinition = Class->getDefinition();
763228072Sbapt      if (Class->isInvalidDecl() || !ClassDefinition ||
764228072Sbapt          !ClassDefinition->isCompleteDefinition())
765228072Sbapt        return;
766228072Sbapt
767228072Sbapt      const ASTRecordLayout &DerivedLayout =
768228072Sbapt          Self.Context.getASTRecordLayout(Class);
769228072Sbapt      Offset += DerivedLayout.getBaseClassOffset(BaseRD);
770228072Sbapt    }
771228072Sbapt    if (!IsVirtual) {
772228072Sbapt      // Don't warn if any path is a non-virtually derived base at offset zero.
773228072Sbapt      if (Offset.isZero())
774228072Sbapt        return;
775228072Sbapt      // Offset makes sense only for non-virtual bases.
776228072Sbapt      else
777228072Sbapt        NonZeroOffset = true;
778228072Sbapt    }
779228072Sbapt    VirtualBase = VirtualBase && IsVirtual;
780228072Sbapt  }
781228072Sbapt
782228072Sbapt  (void) NonZeroOffset; // Silence set but not used warning.
783228072Sbapt  assert((VirtualBase || NonZeroOffset) &&
784228072Sbapt         "Should have returned if has non-virtual base with zero offset");
785228072Sbapt
786228072Sbapt  QualType BaseType =
787228072Sbapt      ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
788228072Sbapt  QualType DerivedType =
789228072Sbapt      ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
790228072Sbapt
791228072Sbapt  SourceLocation BeginLoc = OpRange.getBegin();
792228072Sbapt  Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
793228072Sbapt    << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
794228072Sbapt    << OpRange;
795228072Sbapt  Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
796228072Sbapt    << int(ReinterpretKind)
797228072Sbapt    << FixItHint::CreateReplacement(BeginLoc, "static_cast");
798228072Sbapt}
799228072Sbapt
800228072Sbapt/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
801228072Sbapt/// valid.
802228072Sbapt/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
803228072Sbapt/// like this:
804228072Sbapt/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
805228072Sbaptvoid CastOperation::CheckReinterpretCast() {
806228072Sbapt  if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
807228072Sbapt    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
808228072Sbapt  else
809228072Sbapt    checkNonOverloadPlaceholders();
810228072Sbapt  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
811228072Sbapt    return;
812228072Sbapt
813228072Sbapt  unsigned msg = diag::err_bad_cxx_cast_generic;
814228072Sbapt  TryCastResult tcr =
815228072Sbapt    TryReinterpretCast(Self, SrcExpr, DestType,
816228072Sbapt                       /*CStyle*/false, OpRange, msg, Kind);
817228072Sbapt  if (tcr != TC_Success && msg != 0)
818228072Sbapt  {
819228072Sbapt    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
820228072Sbapt      return;
821228072Sbapt    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
822228072Sbapt      //FIXME: &f<int>; is overloaded and resolvable
823228072Sbapt      Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
824228072Sbapt        << OverloadExpr::find(SrcExpr.get()).Expression->getName()
825228072Sbapt        << DestType << OpRange;
826228072Sbapt      Self.NoteAllOverloadCandidates(SrcExpr.get());
827228072Sbapt
828228072Sbapt    } else {
829228072Sbapt      diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
830228072Sbapt                      DestType, /*listInitialization=*/false);
831228072Sbapt    }
832228072Sbapt    SrcExpr = ExprError();
833228072Sbapt  } else if (tcr == TC_Success) {
834228072Sbapt    if (Self.getLangOpts().ObjCAutoRefCount)
835228072Sbapt      checkObjCARCConversion(Sema::CCK_OtherCast);
836228072Sbapt    DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
837228072Sbapt  }
838228072Sbapt}
839228072Sbapt
840228072Sbapt
841228072Sbapt/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
842228072Sbapt/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
843228072Sbapt/// implicit conversions explicit and getting rid of data loss warnings.
844228072Sbaptvoid CastOperation::CheckStaticCast() {
845228072Sbapt  if (isPlaceholder()) {
846228072Sbapt    checkNonOverloadPlaceholders();
847228072Sbapt    if (SrcExpr.isInvalid())
848228072Sbapt      return;
849228072Sbapt  }
850228072Sbapt
851228072Sbapt  // This test is outside everything else because it's the only case where
852228072Sbapt  // a non-lvalue-reference target type does not lead to decay.
853228072Sbapt  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
854228072Sbapt  if (DestType->isVoidType()) {
855228072Sbapt    Kind = CK_ToVoid;
856228072Sbapt
857228072Sbapt    if (claimPlaceholder(BuiltinType::Overload)) {
858228072Sbapt      Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
859228072Sbapt                false, // Decay Function to ptr
860228072Sbapt                true, // Complain
861228072Sbapt                OpRange, DestType, diag::err_bad_static_cast_overload);
862228072Sbapt      if (SrcExpr.isInvalid())
863228072Sbapt        return;
864228072Sbapt    }
865228072Sbapt
866228072Sbapt    SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
867228072Sbapt    return;
868228072Sbapt  }
869228072Sbapt
870228072Sbapt  if (ValueKind == VK_RValue && !DestType->isRecordType() &&
871228072Sbapt      !isPlaceholder(BuiltinType::Overload)) {
872228072Sbapt    SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
873228072Sbapt    if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
874228072Sbapt      return;
875228072Sbapt  }
876228072Sbapt
877228072Sbapt  unsigned msg = diag::err_bad_cxx_cast_generic;
878228072Sbapt  TryCastResult tcr
879228072Sbapt    = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
880228072Sbapt                    Kind, BasePath, /*ListInitialization=*/false);
881228072Sbapt  if (tcr != TC_Success && msg != 0) {
882228072Sbapt    if (SrcExpr.isInvalid())
883228072Sbapt      return;
884228072Sbapt    if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
885228072Sbapt      OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
886228072Sbapt      Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
887228072Sbapt        << oe->getName() << DestType << OpRange
888228072Sbapt        << oe->getQualifierLoc().getSourceRange();
889228072Sbapt      Self.NoteAllOverloadCandidates(SrcExpr.get());
890228072Sbapt    } else {
891228072Sbapt      diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
892228072Sbapt                      /*listInitialization=*/false);
893228072Sbapt    }
894228072Sbapt    SrcExpr = ExprError();
895228072Sbapt  } else if (tcr == TC_Success) {
896228072Sbapt    if (Kind == CK_BitCast)
897228072Sbapt      checkCastAlign();
898228072Sbapt    if (Self.getLangOpts().ObjCAutoRefCount)
899228072Sbapt      checkObjCARCConversion(Sema::CCK_OtherCast);
900228072Sbapt  } else if (Kind == CK_BitCast) {
901228072Sbapt    checkCastAlign();
902228072Sbapt  }
903228072Sbapt}
904228072Sbapt
905228072Sbapt/// TryStaticCast - Check if a static cast can be performed, and do so if
906228072Sbapt/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
907228072Sbapt/// and casting away constness.
908228072Sbaptstatic TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
909228072Sbapt                                   QualType DestType,
910228072Sbapt                                   Sema::CheckedConversionKind CCK,
911228072Sbapt                                   const SourceRange &OpRange, unsigned &msg,
912228072Sbapt                                   CastKind &Kind, CXXCastPath &BasePath,
913228072Sbapt                                   bool ListInitialization) {
914228072Sbapt  // Determine whether we have the semantics of a C-style cast.
915228072Sbapt  bool CStyle
916228072Sbapt    = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
917228072Sbapt
918228072Sbapt  // The order the tests is not entirely arbitrary. There is one conversion
919228072Sbapt  // that can be handled in two different ways. Given:
920228072Sbapt  // struct A {};
921228072Sbapt  // struct B : public A {
922228072Sbapt  //   B(); B(const A&);
923228072Sbapt  // };
924228072Sbapt  // const A &a = B();
925228072Sbapt  // the cast static_cast<const B&>(a) could be seen as either a static
926228072Sbapt  // reference downcast, or an explicit invocation of the user-defined
927228072Sbapt  // conversion using B's conversion constructor.
928228072Sbapt  // DR 427 specifies that the downcast is to be applied here.
929228072Sbapt
930228072Sbapt  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
931228072Sbapt  // Done outside this function.
932228072Sbapt
933228072Sbapt  TryCastResult tcr;
934228072Sbapt
935228072Sbapt  // C++ 5.2.9p5, reference downcast.
936228072Sbapt  // See the function for details.
937228072Sbapt  // DR 427 specifies that this is to be applied before paragraph 2.
938228072Sbapt  tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
939228072Sbapt                                   OpRange, msg, Kind, BasePath);
940228072Sbapt  if (tcr != TC_NotApplicable)
941228072Sbapt    return tcr;
942228072Sbapt
943228072Sbapt  // C++0x [expr.static.cast]p3:
944228072Sbapt  //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
945228072Sbapt  //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
946228072Sbapt  tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
947228072Sbapt                              BasePath, msg);
948228072Sbapt  if (tcr != TC_NotApplicable)
949228072Sbapt    return tcr;
950228072Sbapt
951228072Sbapt  // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
952228072Sbapt  //   [...] if the declaration "T t(e);" is well-formed, [...].
953228072Sbapt  tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
954228072Sbapt                              Kind, ListInitialization);
955228072Sbapt  if (SrcExpr.isInvalid())
956250874Sjkim    return TC_Failed;
957228072Sbapt  if (tcr != TC_NotApplicable)
958228072Sbapt    return tcr;
959228072Sbapt
960228072Sbapt  // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
961228072Sbapt  // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
962228072Sbapt  // conversions, subject to further restrictions.
963228072Sbapt  // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
964228072Sbapt  // of qualification conversions impossible.
965228072Sbapt  // In the CStyle case, the earlier attempt to const_cast should have taken
966228072Sbapt  // care of reverse qualification conversions.
967228072Sbapt
968228072Sbapt  QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
969250125Sjkim
970250125Sjkim  // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
971250125Sjkim  // converted to an integral type. [...] A value of a scoped enumeration type
972250125Sjkim  // can also be explicitly converted to a floating-point type [...].
973228072Sbapt  if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
974228072Sbapt    if (Enum->getDecl()->isScoped()) {
975228072Sbapt      if (DestType->isBooleanType()) {
976228072Sbapt        Kind = CK_IntegralToBoolean;
977228072Sbapt        return TC_Success;
978228072Sbapt      } else if (DestType->isIntegralType(Self.Context)) {
979228072Sbapt        Kind = CK_IntegralCast;
980228072Sbapt        return TC_Success;
981228072Sbapt      } else if (DestType->isRealFloatingType()) {
982228072Sbapt        Kind = CK_IntegralToFloating;
983228072Sbapt        return TC_Success;
984228072Sbapt      }
985228072Sbapt    }
986228072Sbapt  }
987228072Sbapt
988228072Sbapt  // Reverse integral promotion/conversion. All such conversions are themselves
989228072Sbapt  // again integral promotions or conversions and are thus already handled by
990228072Sbapt  // p2 (TryDirectInitialization above).
991228072Sbapt  // (Note: any data loss warnings should be suppressed.)
992228072Sbapt  // The exception is the reverse of enum->integer, i.e. integer->enum (and
993228072Sbapt  // enum->enum). See also C++ 5.2.9p7.
994228072Sbapt  // The same goes for reverse floating point promotion/conversion and
995228072Sbapt  // floating-integral conversions. Again, only floating->enum is relevant.
996228072Sbapt  if (DestType->isEnumeralType()) {
997228072Sbapt    if (SrcType->isIntegralOrEnumerationType()) {
998228072Sbapt      Kind = CK_IntegralCast;
999228072Sbapt      return TC_Success;
1000228072Sbapt    } else if (SrcType->isRealFloatingType())   {
1001228072Sbapt      Kind = CK_FloatingToIntegral;
1002228072Sbapt      return TC_Success;
1003228072Sbapt    }
1004228072Sbapt  }
1005228072Sbapt
1006228072Sbapt  // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1007228072Sbapt  // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1008228072Sbapt  tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1009228072Sbapt                                 Kind, BasePath);
1010228072Sbapt  if (tcr != TC_NotApplicable)
1011228072Sbapt    return tcr;
1012228072Sbapt
1013228072Sbapt  // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1014228072Sbapt  // conversion. C++ 5.2.9p9 has additional information.
1015228072Sbapt  // DR54's access restrictions apply here also.
1016228072Sbapt  tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1017228072Sbapt                                     OpRange, msg, Kind, BasePath);
1018228072Sbapt  if (tcr != TC_NotApplicable)
1019228072Sbapt    return tcr;
1020228072Sbapt
1021228072Sbapt  // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1022228072Sbapt  // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1023228072Sbapt  // just the usual constness stuff.
1024228072Sbapt  if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1025228072Sbapt    QualType SrcPointee = SrcPointer->getPointeeType();
1026228072Sbapt    if (SrcPointee->isVoidType()) {
1027228072Sbapt      if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1028228072Sbapt        QualType DestPointee = DestPointer->getPointeeType();
1029228072Sbapt        if (DestPointee->isIncompleteOrObjectType()) {
1030228072Sbapt          // This is definitely the intended conversion, but it might fail due
1031228072Sbapt          // to a qualifier violation. Note that we permit Objective-C lifetime
1032228072Sbapt          // and GC qualifier mismatches here.
1033228072Sbapt          if (!CStyle) {
1034228072Sbapt            Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1035228072Sbapt            Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1036228072Sbapt            DestPointeeQuals.removeObjCGCAttr();
1037228072Sbapt            DestPointeeQuals.removeObjCLifetime();
1038228072Sbapt            SrcPointeeQuals.removeObjCGCAttr();
1039228072Sbapt            SrcPointeeQuals.removeObjCLifetime();
1040228072Sbapt            if (DestPointeeQuals != SrcPointeeQuals &&
1041228072Sbapt                !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1042228072Sbapt              msg = diag::err_bad_cxx_cast_qualifiers_away;
1043228072Sbapt              return TC_Failed;
1044228072Sbapt            }
1045228072Sbapt          }
1046228072Sbapt          Kind = CK_BitCast;
1047228072Sbapt          return TC_Success;
1048228072Sbapt        }
1049228072Sbapt      }
1050228072Sbapt      else if (DestType->isObjCObjectPointerType()) {
1051228072Sbapt        // allow both c-style cast and static_cast of objective-c pointers as
1052228072Sbapt        // they are pervasive.
1053228072Sbapt        Kind = CK_CPointerToObjCPointerCast;
1054228072Sbapt        return TC_Success;
1055228072Sbapt      }
1056228072Sbapt      else if (CStyle && DestType->isBlockPointerType()) {
1057228072Sbapt        // allow c-style cast of void * to block pointers.
1058228072Sbapt        Kind = CK_AnyPointerToBlockPointerCast;
1059228072Sbapt        return TC_Success;
1060228072Sbapt      }
1061228072Sbapt    }
1062228072Sbapt  }
1063228072Sbapt  // Allow arbitray objective-c pointer conversion with static casts.
1064228072Sbapt  if (SrcType->isObjCObjectPointerType() &&
1065228072Sbapt      DestType->isObjCObjectPointerType()) {
1066228072Sbapt    Kind = CK_BitCast;
1067228072Sbapt    return TC_Success;
1068228072Sbapt  }
1069228072Sbapt
1070228072Sbapt  // We tried everything. Everything! Nothing works! :-(
1071228072Sbapt  return TC_NotApplicable;
1072228072Sbapt}
1073228072Sbapt
1074228072Sbapt/// Tests whether a conversion according to N2844 is valid.
1075228072SbaptTryCastResult
1076228072SbaptTryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1077228072Sbapt                      bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1078228072Sbapt                      unsigned &msg) {
1079228072Sbapt  // C++0x [expr.static.cast]p3:
1080228072Sbapt  //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1081228072Sbapt  //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1082228072Sbapt  const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1083228072Sbapt  if (!R)
1084228072Sbapt    return TC_NotApplicable;
1085228072Sbapt
1086228072Sbapt  if (!SrcExpr->isGLValue())
1087228072Sbapt    return TC_NotApplicable;
1088228072Sbapt
1089228072Sbapt  // 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.
1126TryCastResult
1127TryStaticReferenceDowncast(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.
1161TryCastResult
1162TryStaticPointerDowncast(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.
1195TryCastResult
1196TryStaticDowncast(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///
1310TryCastResult
1311TryStaticMemberPointerUpcast(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 [...].
1421TryCastResult
1422TryStaticImplicitCast(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.
1474static 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.
1592void 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
1644static 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
1661static 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
1687static 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
1978void 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.
2105static 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.
2140void 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
2332ExprResult 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
2355ExprResult 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}
2375