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