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