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