clang  8.0.0svn
SemaCast.cpp
Go to the documentation of this file.
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 
18 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Lex/Preprocessor.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include <set>
29 using namespace clang;
30 
31 
32 
34  TC_NotApplicable, ///< The cast method is not applicable.
35  TC_Success, ///< The cast method is appropriate and successful.
36  TC_Extension, ///< The cast method is appropriate and accepted as a
37  ///< language extension.
38  TC_Failed ///< The cast method is appropriate, but failed. A
39  ///< diagnostic has been emitted.
40 };
41 
42 static bool isValidCast(TryCastResult TCR) {
43  return TCR == TC_Success || TCR == TC_Extension;
44 }
45 
46 enum CastType {
47  CT_Const, ///< const_cast
48  CT_Static, ///< static_cast
49  CT_Reinterpret, ///< reinterpret_cast
50  CT_Dynamic, ///< dynamic_cast
51  CT_CStyle, ///< (Type)expr
52  CT_Functional ///< Type(expr)
53 };
54 
55 namespace {
56  struct CastOperation {
57  CastOperation(Sema &S, QualType destType, ExprResult src)
58  : Self(S), SrcExpr(src), DestType(destType),
59  ResultType(destType.getNonLValueExprType(S.Context)),
60  ValueKind(Expr::getValueKindForType(destType)),
61  Kind(CK_Dependent), IsARCUnbridgedCast(false) {
62 
63  if (const BuiltinType *placeholder =
64  src.get()->getType()->getAsPlaceholderType()) {
65  PlaceholderKind = placeholder->getKind();
66  } else {
67  PlaceholderKind = (BuiltinType::Kind) 0;
68  }
69  }
70 
71  Sema &Self;
72  ExprResult SrcExpr;
73  QualType DestType;
74  QualType ResultType;
75  ExprValueKind ValueKind;
76  CastKind Kind;
77  BuiltinType::Kind PlaceholderKind;
78  CXXCastPath BasePath;
79  bool IsARCUnbridgedCast;
80 
81  SourceRange OpRange;
82  SourceRange DestRange;
83 
84  // Top-level semantics-checking routines.
85  void CheckConstCast();
86  void CheckReinterpretCast();
87  void CheckStaticCast();
88  void CheckDynamicCast();
89  void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
90  void CheckCStyleCast();
91 
92  void updatePartOfExplicitCastFlags(CastExpr *CE) {
93  // Walk down from the CE to the OrigSrcExpr, and mark all immediate
94  // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
95  // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
96  for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
97  ICE->setIsPartOfExplicitCast(true);
98  }
99 
100  /// Complete an apparently-successful cast operation that yields
101  /// the given expression.
102  ExprResult complete(CastExpr *castExpr) {
103  // If this is an unbridged cast, wrap the result in an implicit
104  // cast that yields the unbridged-cast placeholder type.
105  if (IsARCUnbridgedCast) {
106  castExpr = ImplicitCastExpr::Create(Self.Context,
108  CK_Dependent, castExpr, nullptr,
109  castExpr->getValueKind());
110  }
111  updatePartOfExplicitCastFlags(castExpr);
112  return castExpr;
113  }
114 
115  // Internal convenience methods.
116 
117  /// Try to handle the given placeholder expression kind. Return
118  /// true if the source expression has the appropriate placeholder
119  /// kind. A placeholder can only be claimed once.
120  bool claimPlaceholder(BuiltinType::Kind K) {
121  if (PlaceholderKind != K) return false;
122 
123  PlaceholderKind = (BuiltinType::Kind) 0;
124  return true;
125  }
126 
127  bool isPlaceholder() const {
128  return PlaceholderKind != 0;
129  }
130  bool isPlaceholder(BuiltinType::Kind K) const {
131  return PlaceholderKind == K;
132  }
133 
134  // Language specific cast restrictions for address spaces.
135  void checkAddressSpaceCast(QualType SrcType, QualType DestType);
136 
137  void checkCastAlign() {
138  Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
139  }
140 
141  void checkObjCConversion(Sema::CheckedConversionKind CCK) {
143 
144  Expr *src = SrcExpr.get();
145  if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
147  IsARCUnbridgedCast = true;
148  SrcExpr = src;
149  }
150 
151  /// Check for and handle non-overload placeholder expressions.
152  void checkNonOverloadPlaceholders() {
153  if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
154  return;
155 
156  SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
157  if (SrcExpr.isInvalid())
158  return;
159  PlaceholderKind = (BuiltinType::Kind) 0;
160  }
161  };
162 }
163 
164 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
165  QualType DestType);
166 
167 // The Try functions attempt a specific way of casting. If they succeed, they
168 // return TC_Success. If their way of casting is not appropriate for the given
169 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
170 // to emit if no other way succeeds. If their way of casting is appropriate but
171 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
172 // they emit a specialized diagnostic.
173 // All diagnostics returned by these functions must expect the same three
174 // arguments:
175 // %0: Cast Type (a value from the CastType enumeration)
176 // %1: Source Type
177 // %2: Destination Type
178 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
179  QualType DestType, bool CStyle,
180  CastKind &Kind,
181  CXXCastPath &BasePath,
182  unsigned &msg);
183 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
184  QualType DestType, bool CStyle,
185  SourceRange OpRange,
186  unsigned &msg,
187  CastKind &Kind,
188  CXXCastPath &BasePath);
190  QualType DestType, bool CStyle,
191  SourceRange OpRange,
192  unsigned &msg,
193  CastKind &Kind,
194  CXXCastPath &BasePath);
195 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
196  CanQualType DestType, bool CStyle,
197  SourceRange OpRange,
198  QualType OrigSrcType,
199  QualType OrigDestType, unsigned &msg,
200  CastKind &Kind,
201  CXXCastPath &BasePath);
203  QualType SrcType,
204  QualType DestType,bool CStyle,
205  SourceRange OpRange,
206  unsigned &msg,
207  CastKind &Kind,
208  CXXCastPath &BasePath);
209 
210 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
211  QualType DestType,
213  SourceRange OpRange,
214  unsigned &msg, CastKind &Kind,
215  bool ListInitialization);
216 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
217  QualType DestType,
219  SourceRange OpRange,
220  unsigned &msg, CastKind &Kind,
221  CXXCastPath &BasePath,
222  bool ListInitialization);
223 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
224  QualType DestType, bool CStyle,
225  unsigned &msg);
226 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
227  QualType DestType, bool CStyle,
228  SourceRange OpRange,
229  unsigned &msg,
230  CastKind &Kind);
231 
232 
233 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
236  SourceLocation LAngleBracketLoc, Declarator &D,
237  SourceLocation RAngleBracketLoc,
238  SourceLocation LParenLoc, Expr *E,
239  SourceLocation RParenLoc) {
240 
241  assert(!D.isInvalidType());
242 
243  TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
244  if (D.isInvalidType())
245  return ExprError();
246 
247  if (getLangOpts().CPlusPlus) {
248  // Check that there are no default arguments (C++ only).
249  CheckExtraCXXDefaultArguments(D);
250  }
251 
252  return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
253  SourceRange(LAngleBracketLoc, RAngleBracketLoc),
254  SourceRange(LParenLoc, RParenLoc));
255 }
256 
259  TypeSourceInfo *DestTInfo, Expr *E,
260  SourceRange AngleBrackets, SourceRange Parens) {
261  ExprResult Ex = E;
262  QualType DestType = DestTInfo->getType();
263 
264  // If the type is dependent, we won't do the semantic analysis now.
265  bool TypeDependent =
266  DestType->isDependentType() || Ex.get()->isTypeDependent();
267 
268  CastOperation Op(*this, DestType, E);
269  Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
270  Op.DestRange = AngleBrackets;
271 
272  switch (Kind) {
273  default: llvm_unreachable("Unknown C++ cast!");
274 
275  case tok::kw_const_cast:
276  if (!TypeDependent) {
277  Op.CheckConstCast();
278  if (Op.SrcExpr.isInvalid())
279  return ExprError();
280  DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
281  }
282  return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
283  Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
284  OpLoc, Parens.getEnd(),
285  AngleBrackets));
286 
287  case tok::kw_dynamic_cast: {
288  // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
289  if (getLangOpts().OpenCLCPlusPlus) {
290  return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
291  << "dynamic_cast");
292  }
293 
294  if (!TypeDependent) {
295  Op.CheckDynamicCast();
296  if (Op.SrcExpr.isInvalid())
297  return ExprError();
298  }
299  return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
300  Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
301  &Op.BasePath, DestTInfo,
302  OpLoc, Parens.getEnd(),
303  AngleBrackets));
304  }
305  case tok::kw_reinterpret_cast: {
306  if (!TypeDependent) {
307  Op.CheckReinterpretCast();
308  if (Op.SrcExpr.isInvalid())
309  return ExprError();
310  DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
311  }
312  return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
313  Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
314  nullptr, DestTInfo, OpLoc,
315  Parens.getEnd(),
316  AngleBrackets));
317  }
318  case tok::kw_static_cast: {
319  if (!TypeDependent) {
320  Op.CheckStaticCast();
321  if (Op.SrcExpr.isInvalid())
322  return ExprError();
323  DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
324  }
325 
326  return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
327  Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
328  &Op.BasePath, DestTInfo,
329  OpLoc, Parens.getEnd(),
330  AngleBrackets));
331  }
332  }
333 }
334 
335 /// Try to diagnose a failed overloaded cast. Returns true if
336 /// diagnostics were emitted.
338  SourceRange range, Expr *src,
339  QualType destType,
340  bool listInitialization) {
341  switch (CT) {
342  // These cast kinds don't consider user-defined conversions.
343  case CT_Const:
344  case CT_Reinterpret:
345  case CT_Dynamic:
346  return false;
347 
348  // These do.
349  case CT_Static:
350  case CT_CStyle:
351  case CT_Functional:
352  break;
353  }
354 
355  QualType srcType = src->getType();
356  if (!destType->isRecordType() && !srcType->isRecordType())
357  return false;
358 
360  InitializationKind initKind
362  range, listInitialization)
364  listInitialization)
365  : InitializationKind::CreateCast(/*type range?*/ range);
366  InitializationSequence sequence(S, entity, initKind, src);
367 
368  assert(sequence.Failed() && "initialization succeeded on second try?");
369  switch (sequence.getFailureKind()) {
370  default: return false;
371 
374  break;
375  }
376 
377  OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
378 
379  unsigned msg = 0;
381 
382  switch (sequence.getFailedOverloadResult()) {
383  case OR_Success: llvm_unreachable("successful failed overload");
385  if (candidates.empty())
386  msg = diag::err_ovl_no_conversion_in_cast;
387  else
388  msg = diag::err_ovl_no_viable_conversion_in_cast;
389  howManyCandidates = OCD_AllCandidates;
390  break;
391 
392  case OR_Ambiguous:
393  msg = diag::err_ovl_ambiguous_conversion_in_cast;
394  howManyCandidates = OCD_ViableCandidates;
395  break;
396 
397  case OR_Deleted:
398  msg = diag::err_ovl_deleted_conversion_in_cast;
399  howManyCandidates = OCD_ViableCandidates;
400  break;
401  }
402 
403  S.Diag(range.getBegin(), msg)
404  << CT << srcType << destType
405  << range << src->getSourceRange();
406 
407  candidates.NoteCandidates(S, howManyCandidates, src);
408 
409  return true;
410 }
411 
412 /// Diagnose a failed cast.
413 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
414  SourceRange opRange, Expr *src, QualType destType,
415  bool listInitialization) {
416  if (msg == diag::err_bad_cxx_cast_generic &&
417  tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
418  listInitialization))
419  return;
420 
421  S.Diag(opRange.getBegin(), msg) << castType
422  << src->getType() << destType << opRange << src->getSourceRange();
423 
424  // Detect if both types are (ptr to) class, and note any incompleteness.
425  int DifferentPtrness = 0;
426  QualType From = destType;
427  if (auto Ptr = From->getAs<PointerType>()) {
428  From = Ptr->getPointeeType();
429  DifferentPtrness++;
430  }
431  QualType To = src->getType();
432  if (auto Ptr = To->getAs<PointerType>()) {
433  To = Ptr->getPointeeType();
434  DifferentPtrness--;
435  }
436  if (!DifferentPtrness) {
437  auto RecFrom = From->getAs<RecordType>();
438  auto RecTo = To->getAs<RecordType>();
439  if (RecFrom && RecTo) {
440  auto DeclFrom = RecFrom->getAsCXXRecordDecl();
441  if (!DeclFrom->isCompleteDefinition())
442  S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
443  << DeclFrom->getDeclName();
444  auto DeclTo = RecTo->getAsCXXRecordDecl();
445  if (!DeclTo->isCompleteDefinition())
446  S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
447  << DeclTo->getDeclName();
448  }
449  }
450 }
451 
452 namespace {
453 /// The kind of unwrapping we did when determining whether a conversion casts
454 /// away constness.
456  /// The conversion does not cast away constness.
457  CACK_None = 0,
458  /// We unwrapped similar types.
459  CACK_Similar = 1,
460  /// We unwrapped dissimilar types with similar representations (eg, a pointer
461  /// versus an Objective-C object pointer).
462  CACK_SimilarKind = 2,
463  /// We unwrapped representationally-unrelated types, such as a pointer versus
464  /// a pointer-to-member.
465  CACK_Incoherent = 3,
466 };
467 }
468 
469 /// Unwrap one level of types for CastsAwayConstness.
470 ///
471 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
472 /// both types, provided that they're both pointer-like or array-like. Unlike
473 /// the Sema function, doesn't care if the unwrapped pieces are related.
474 ///
475 /// This function may remove additional levels as necessary for correctness:
476 /// the resulting T1 is unwrapped sufficiently that it is never an array type,
477 /// so that its qualifiers can be directly compared to those of T2 (which will
478 /// have the combined set of qualifiers from all indermediate levels of T2),
479 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
480 /// with those from T2.
483  enum { None, Ptr, MemPtr, BlockPtr, Array };
484  auto Classify = [](QualType T) {
485  if (T->isAnyPointerType()) return Ptr;
486  if (T->isMemberPointerType()) return MemPtr;
487  if (T->isBlockPointerType()) return BlockPtr;
488  // We somewhat-arbitrarily don't look through VLA types here. This is at
489  // least consistent with the behavior of UnwrapSimilarTypes.
490  if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
491  return None;
492  };
493 
494  auto Unwrap = [&](QualType T) {
495  if (auto *AT = Context.getAsArrayType(T))
496  return AT->getElementType();
497  return T->getPointeeType();
498  };
499 
501 
502  if (T2->isReferenceType()) {
503  // Special case: if the destination type is a reference type, unwrap it as
504  // the first level. (The source will have been an lvalue expression in this
505  // case, so there is no corresponding "reference to" in T1 to remove.) This
506  // simulates removing a "pointer to" from both sides.
507  T2 = T2->getPointeeType();
508  Kind = CastAwayConstnessKind::CACK_Similar;
509  } else if (Context.UnwrapSimilarTypes(T1, T2)) {
510  Kind = CastAwayConstnessKind::CACK_Similar;
511  } else {
512  // Try unwrapping mismatching levels.
513  int T1Class = Classify(T1);
514  if (T1Class == None)
515  return CastAwayConstnessKind::CACK_None;
516 
517  int T2Class = Classify(T2);
518  if (T2Class == None)
519  return CastAwayConstnessKind::CACK_None;
520 
521  T1 = Unwrap(T1);
522  T2 = Unwrap(T2);
523  Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
524  : CastAwayConstnessKind::CACK_Incoherent;
525  }
526 
527  // We've unwrapped at least one level. If the resulting T1 is a (possibly
528  // multidimensional) array type, any qualifier on any matching layer of
529  // T2 is considered to correspond to T1. Decompose down to the element
530  // type of T1 so that we can compare properly.
531  while (true) {
532  Context.UnwrapSimilarArrayTypes(T1, T2);
533 
534  if (Classify(T1) != Array)
535  break;
536 
537  auto T2Class = Classify(T2);
538  if (T2Class == None)
539  break;
540 
541  if (T2Class != Array)
542  Kind = CastAwayConstnessKind::CACK_Incoherent;
543  else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
544  Kind = CastAwayConstnessKind::CACK_SimilarKind;
545 
546  T1 = Unwrap(T1);
547  T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
548  }
549 
550  return Kind;
551 }
552 
553 /// Check if the pointer conversion from SrcType to DestType casts away
554 /// constness as defined in C++ [expr.const.cast]. This is used by the cast
555 /// checkers. Both arguments must denote pointer (possibly to member) types.
556 ///
557 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
558 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
560 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
561  bool CheckCVR, bool CheckObjCLifetime,
562  QualType *TheOffendingSrcType = nullptr,
563  QualType *TheOffendingDestType = nullptr,
564  Qualifiers *CastAwayQualifiers = nullptr) {
565  // If the only checking we care about is for Objective-C lifetime qualifiers,
566  // and we're not in ObjC mode, there's nothing to check.
567  if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
568  return CastAwayConstnessKind::CACK_None;
569 
570  if (!DestType->isReferenceType()) {
571  assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
572  SrcType->isBlockPointerType()) &&
573  "Source type is not pointer or pointer to member.");
574  assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
575  DestType->isBlockPointerType()) &&
576  "Destination type is not pointer or pointer to member.");
577  }
578 
579  QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
580  UnwrappedDestType = Self.Context.getCanonicalType(DestType);
581 
582  // Find the qualifiers. We only care about cvr-qualifiers for the
583  // purpose of this check, because other qualifiers (address spaces,
584  // Objective-C GC, etc.) are part of the type's identity.
585  QualType PrevUnwrappedSrcType = UnwrappedSrcType;
586  QualType PrevUnwrappedDestType = UnwrappedDestType;
587  auto WorstKind = CastAwayConstnessKind::CACK_Similar;
588  bool AllConstSoFar = true;
589  while (auto Kind = unwrapCastAwayConstnessLevel(
590  Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
591  // Track the worst kind of unwrap we needed to do before we found a
592  // problem.
593  if (Kind > WorstKind)
594  WorstKind = Kind;
595 
596  // Determine the relevant qualifiers at this level.
597  Qualifiers SrcQuals, DestQuals;
598  Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
599  Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
600 
601  // We do not meaningfully track object const-ness of Objective-C object
602  // types. Remove const from the source type if either the source or
603  // the destination is an Objective-C object type.
604  if (UnwrappedSrcType->isObjCObjectType() ||
605  UnwrappedDestType->isObjCObjectType())
606  SrcQuals.removeConst();
607 
608  if (CheckCVR) {
609  Qualifiers SrcCvrQuals =
611  Qualifiers DestCvrQuals =
613 
614  if (SrcCvrQuals != DestCvrQuals) {
615  if (CastAwayQualifiers)
616  *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
617 
618  // If we removed a cvr-qualifier, this is casting away 'constness'.
619  if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
620  if (TheOffendingSrcType)
621  *TheOffendingSrcType = PrevUnwrappedSrcType;
622  if (TheOffendingDestType)
623  *TheOffendingDestType = PrevUnwrappedDestType;
624  return WorstKind;
625  }
626 
627  // If any prior level was not 'const', this is also casting away
628  // 'constness'. We noted the outermost type missing a 'const' already.
629  if (!AllConstSoFar)
630  return WorstKind;
631  }
632  }
633 
634  if (CheckObjCLifetime &&
635  !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
636  return WorstKind;
637 
638  // If we found our first non-const-qualified type, this may be the place
639  // where things start to go wrong.
640  if (AllConstSoFar && !DestQuals.hasConst()) {
641  AllConstSoFar = false;
642  if (TheOffendingSrcType)
643  *TheOffendingSrcType = PrevUnwrappedSrcType;
644  if (TheOffendingDestType)
645  *TheOffendingDestType = PrevUnwrappedDestType;
646  }
647 
648  PrevUnwrappedSrcType = UnwrappedSrcType;
649  PrevUnwrappedDestType = UnwrappedDestType;
650  }
651 
652  return CastAwayConstnessKind::CACK_None;
653 }
654 
656  unsigned &DiagID) {
657  switch (CACK) {
658  case CastAwayConstnessKind::CACK_None:
659  llvm_unreachable("did not cast away constness");
660 
661  case CastAwayConstnessKind::CACK_Similar:
662  // FIXME: Accept these as an extension too?
663  case CastAwayConstnessKind::CACK_SimilarKind:
664  DiagID = diag::err_bad_cxx_cast_qualifiers_away;
665  return TC_Failed;
666 
667  case CastAwayConstnessKind::CACK_Incoherent:
668  DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
669  return TC_Extension;
670  }
671 
672  llvm_unreachable("unexpected cast away constness kind");
673 }
674 
675 /// CheckDynamicCast - Check that a dynamic_cast<DestType>(SrcExpr) is valid.
676 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
677 /// checked downcasts in class hierarchies.
678 void CastOperation::CheckDynamicCast() {
679  if (ValueKind == VK_RValue)
680  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
681  else if (isPlaceholder())
682  SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
683  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
684  return;
685 
686  QualType OrigSrcType = SrcExpr.get()->getType();
687  QualType DestType = Self.Context.getCanonicalType(this->DestType);
688 
689  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
690  // or "pointer to cv void".
691 
692  QualType DestPointee;
693  const PointerType *DestPointer = DestType->getAs<PointerType>();
694  const ReferenceType *DestReference = nullptr;
695  if (DestPointer) {
696  DestPointee = DestPointer->getPointeeType();
697  } else if ((DestReference = DestType->getAs<ReferenceType>())) {
698  DestPointee = DestReference->getPointeeType();
699  } else {
700  Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
701  << this->DestType << DestRange;
702  SrcExpr = ExprError();
703  return;
704  }
705 
706  const RecordType *DestRecord = DestPointee->getAs<RecordType>();
707  if (DestPointee->isVoidType()) {
708  assert(DestPointer && "Reference to void is not possible");
709  } else if (DestRecord) {
710  if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
711  diag::err_bad_dynamic_cast_incomplete,
712  DestRange)) {
713  SrcExpr = ExprError();
714  return;
715  }
716  } else {
717  Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
718  << DestPointee.getUnqualifiedType() << DestRange;
719  SrcExpr = ExprError();
720  return;
721  }
722 
723  // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
724  // complete class type, [...]. If T is an lvalue reference type, v shall be
725  // an lvalue of a complete class type, [...]. If T is an rvalue reference
726  // type, v shall be an expression having a complete class type, [...]
727  QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
728  QualType SrcPointee;
729  if (DestPointer) {
730  if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
731  SrcPointee = SrcPointer->getPointeeType();
732  } else {
733  Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
734  << OrigSrcType << SrcExpr.get()->getSourceRange();
735  SrcExpr = ExprError();
736  return;
737  }
738  } else if (DestReference->isLValueReferenceType()) {
739  if (!SrcExpr.get()->isLValue()) {
740  Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
741  << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
742  }
743  SrcPointee = SrcType;
744  } else {
745  // If we're dynamic_casting from a prvalue to an rvalue reference, we need
746  // to materialize the prvalue before we bind the reference to it.
747  if (SrcExpr.get()->isRValue())
748  SrcExpr = Self.CreateMaterializeTemporaryExpr(
749  SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
750  SrcPointee = SrcType;
751  }
752 
753  const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
754  if (SrcRecord) {
755  if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
756  diag::err_bad_dynamic_cast_incomplete,
757  SrcExpr.get())) {
758  SrcExpr = ExprError();
759  return;
760  }
761  } else {
762  Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
763  << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
764  SrcExpr = ExprError();
765  return;
766  }
767 
768  assert((DestPointer || DestReference) &&
769  "Bad destination non-ptr/ref slipped through.");
770  assert((DestRecord || DestPointee->isVoidType()) &&
771  "Bad destination pointee slipped through.");
772  assert(SrcRecord && "Bad source pointee slipped through.");
773 
774  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
775  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
776  Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
777  << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
778  SrcExpr = ExprError();
779  return;
780  }
781 
782  // C++ 5.2.7p3: If the type of v is the same as the required result type,
783  // [except for cv].
784  if (DestRecord == SrcRecord) {
785  Kind = CK_NoOp;
786  return;
787  }
788 
789  // C++ 5.2.7p5
790  // Upcasts are resolved statically.
791  if (DestRecord &&
792  Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
793  if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
794  OpRange.getBegin(), OpRange,
795  &BasePath)) {
796  SrcExpr = ExprError();
797  return;
798  }
799 
800  Kind = CK_DerivedToBase;
801  return;
802  }
803 
804  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
805  const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
806  assert(SrcDecl && "Definition missing");
807  if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
808  Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
809  << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
810  SrcExpr = ExprError();
811  }
812 
813  // dynamic_cast is not available with -fno-rtti.
814  // As an exception, dynamic_cast to void* is available because it doesn't
815  // use RTTI.
816  if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
817  Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
818  SrcExpr = ExprError();
819  return;
820  }
821 
822  // Done. Everything else is run-time checks.
823  Kind = CK_Dynamic;
824 }
825 
826 /// CheckConstCast - Check that a const_cast<DestType>(SrcExpr) is valid.
827 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
828 /// like this:
829 /// const char *str = "literal";
830 /// legacy_function(const_cast<char*>(str));
831 void CastOperation::CheckConstCast() {
832  if (ValueKind == VK_RValue)
833  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
834  else if (isPlaceholder())
835  SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
836  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
837  return;
838 
839  unsigned msg = diag::err_bad_cxx_cast_generic;
840  auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
841  if (TCR != TC_Success && msg != 0) {
842  Self.Diag(OpRange.getBegin(), msg) << CT_Const
843  << SrcExpr.get()->getType() << DestType << OpRange;
844  }
845  if (!isValidCast(TCR))
846  SrcExpr = ExprError();
847 }
848 
849 /// Check that a reinterpret_cast<DestType>(SrcExpr) is not used as upcast
850 /// or downcast between respective pointers or references.
851 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
852  QualType DestType,
853  SourceRange OpRange) {
854  QualType SrcType = SrcExpr->getType();
855  // When casting from pointer or reference, get pointee type; use original
856  // type otherwise.
857  const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
858  const CXXRecordDecl *SrcRD =
859  SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
860 
861  // Examining subobjects for records is only possible if the complete and
862  // valid definition is available. Also, template instantiation is not
863  // allowed here.
864  if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
865  return;
866 
867  const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
868 
869  if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
870  return;
871 
872  enum {
873  ReinterpretUpcast,
874  ReinterpretDowncast
875  } ReinterpretKind;
876 
877  CXXBasePaths BasePaths;
878 
879  if (SrcRD->isDerivedFrom(DestRD, BasePaths))
880  ReinterpretKind = ReinterpretUpcast;
881  else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
882  ReinterpretKind = ReinterpretDowncast;
883  else
884  return;
885 
886  bool VirtualBase = true;
887  bool NonZeroOffset = false;
888  for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
889  E = BasePaths.end();
890  I != E; ++I) {
891  const CXXBasePath &Path = *I;
893  bool IsVirtual = false;
894  for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
895  IElem != EElem; ++IElem) {
896  IsVirtual = IElem->Base->isVirtual();
897  if (IsVirtual)
898  break;
899  const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
900  assert(BaseRD && "Base type should be a valid unqualified class type");
901  // Don't check if any base has invalid declaration or has no definition
902  // since it has no layout info.
903  const CXXRecordDecl *Class = IElem->Class,
904  *ClassDefinition = Class->getDefinition();
905  if (Class->isInvalidDecl() || !ClassDefinition ||
906  !ClassDefinition->isCompleteDefinition())
907  return;
908 
909  const ASTRecordLayout &DerivedLayout =
910  Self.Context.getASTRecordLayout(Class);
911  Offset += DerivedLayout.getBaseClassOffset(BaseRD);
912  }
913  if (!IsVirtual) {
914  // Don't warn if any path is a non-virtually derived base at offset zero.
915  if (Offset.isZero())
916  return;
917  // Offset makes sense only for non-virtual bases.
918  else
919  NonZeroOffset = true;
920  }
921  VirtualBase = VirtualBase && IsVirtual;
922  }
923 
924  (void) NonZeroOffset; // Silence set but not used warning.
925  assert((VirtualBase || NonZeroOffset) &&
926  "Should have returned if has non-virtual base with zero offset");
927 
928  QualType BaseType =
929  ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
930  QualType DerivedType =
931  ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
932 
933  SourceLocation BeginLoc = OpRange.getBegin();
934  Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
935  << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
936  << OpRange;
937  Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
938  << int(ReinterpretKind)
939  << FixItHint::CreateReplacement(BeginLoc, "static_cast");
940 }
941 
942 /// CheckReinterpretCast - Check that a reinterpret_cast<DestType>(SrcExpr) is
943 /// valid.
944 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
945 /// like this:
946 /// char *bytes = reinterpret_cast<char*>(int_ptr);
947 void CastOperation::CheckReinterpretCast() {
948  if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
949  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
950  else
951  checkNonOverloadPlaceholders();
952  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
953  return;
954 
955  unsigned msg = diag::err_bad_cxx_cast_generic;
956  TryCastResult tcr =
957  TryReinterpretCast(Self, SrcExpr, DestType,
958  /*CStyle*/false, OpRange, msg, Kind);
959  if (tcr != TC_Success && msg != 0) {
960  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
961  return;
962  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
963  //FIXME: &f<int>; is overloaded and resolvable
964  Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
965  << OverloadExpr::find(SrcExpr.get()).Expression->getName()
966  << DestType << OpRange;
967  Self.NoteAllOverloadCandidates(SrcExpr.get());
968 
969  } else {
970  diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
971  DestType, /*listInitialization=*/false);
972  }
973  }
974 
975  if (isValidCast(tcr)) {
977  checkObjCConversion(Sema::CCK_OtherCast);
978  DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
979  } else {
980  SrcExpr = ExprError();
981  }
982 }
983 
984 
985 /// CheckStaticCast - Check that a static_cast<DestType>(SrcExpr) is valid.
986 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
987 /// implicit conversions explicit and getting rid of data loss warnings.
988 void CastOperation::CheckStaticCast() {
989  if (isPlaceholder()) {
990  checkNonOverloadPlaceholders();
991  if (SrcExpr.isInvalid())
992  return;
993  }
994 
995  // This test is outside everything else because it's the only case where
996  // a non-lvalue-reference target type does not lead to decay.
997  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
998  if (DestType->isVoidType()) {
999  Kind = CK_ToVoid;
1000 
1001  if (claimPlaceholder(BuiltinType::Overload)) {
1003  false, // Decay Function to ptr
1004  true, // Complain
1005  OpRange, DestType, diag::err_bad_static_cast_overload);
1006  if (SrcExpr.isInvalid())
1007  return;
1008  }
1009 
1010  SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
1011  return;
1012  }
1013 
1014  if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1015  !isPlaceholder(BuiltinType::Overload)) {
1016  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1017  if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1018  return;
1019  }
1020 
1021  unsigned msg = diag::err_bad_cxx_cast_generic;
1022  TryCastResult tcr
1023  = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
1024  Kind, BasePath, /*ListInitialization=*/false);
1025  if (tcr != TC_Success && msg != 0) {
1026  if (SrcExpr.isInvalid())
1027  return;
1028  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1029  OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
1030  Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
1031  << oe->getName() << DestType << OpRange
1032  << oe->getQualifierLoc().getSourceRange();
1033  Self.NoteAllOverloadCandidates(SrcExpr.get());
1034  } else {
1035  diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1036  /*listInitialization=*/false);
1037  }
1038  }
1039 
1040  if (isValidCast(tcr)) {
1041  if (Kind == CK_BitCast)
1042  checkCastAlign();
1044  checkObjCConversion(Sema::CCK_OtherCast);
1045  } else {
1046  SrcExpr = ExprError();
1047  }
1048 }
1049 
1050 static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1051  auto *SrcPtrType = SrcType->getAs<PointerType>();
1052  if (!SrcPtrType)
1053  return false;
1054  auto *DestPtrType = DestType->getAs<PointerType>();
1055  if (!DestPtrType)
1056  return false;
1057  return SrcPtrType->getPointeeType().getAddressSpace() !=
1058  DestPtrType->getPointeeType().getAddressSpace();
1059 }
1060 
1061 /// TryStaticCast - Check if a static cast can be performed, and do so if
1062 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1063 /// and casting away constness.
1065  QualType DestType,
1067  SourceRange OpRange, unsigned &msg,
1068  CastKind &Kind, CXXCastPath &BasePath,
1069  bool ListInitialization) {
1070  // Determine whether we have the semantics of a C-style cast.
1071  bool CStyle
1072  = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1073 
1074  // The order the tests is not entirely arbitrary. There is one conversion
1075  // that can be handled in two different ways. Given:
1076  // struct A {};
1077  // struct B : public A {
1078  // B(); B(const A&);
1079  // };
1080  // const A &a = B();
1081  // the cast static_cast<const B&>(a) could be seen as either a static
1082  // reference downcast, or an explicit invocation of the user-defined
1083  // conversion using B's conversion constructor.
1084  // DR 427 specifies that the downcast is to be applied here.
1085 
1086  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1087  // Done outside this function.
1088 
1089  TryCastResult tcr;
1090 
1091  // C++ 5.2.9p5, reference downcast.
1092  // See the function for details.
1093  // DR 427 specifies that this is to be applied before paragraph 2.
1094  tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1095  OpRange, msg, Kind, BasePath);
1096  if (tcr != TC_NotApplicable)
1097  return tcr;
1098 
1099  // C++11 [expr.static.cast]p3:
1100  // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1101  // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1102  tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
1103  BasePath, msg);
1104  if (tcr != TC_NotApplicable)
1105  return tcr;
1106 
1107  // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1108  // [...] if the declaration "T t(e);" is well-formed, [...].
1109  tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1110  Kind, ListInitialization);
1111  if (SrcExpr.isInvalid())
1112  return TC_Failed;
1113  if (tcr != TC_NotApplicable)
1114  return tcr;
1115 
1116  // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1117  // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1118  // conversions, subject to further restrictions.
1119  // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1120  // of qualification conversions impossible.
1121  // In the CStyle case, the earlier attempt to const_cast should have taken
1122  // care of reverse qualification conversions.
1123 
1124  QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1125 
1126  // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1127  // converted to an integral type. [...] A value of a scoped enumeration type
1128  // can also be explicitly converted to a floating-point type [...].
1129  if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1130  if (Enum->getDecl()->isScoped()) {
1131  if (DestType->isBooleanType()) {
1132  Kind = CK_IntegralToBoolean;
1133  return TC_Success;
1134  } else if (DestType->isIntegralType(Self.Context)) {
1135  Kind = CK_IntegralCast;
1136  return TC_Success;
1137  } else if (DestType->isRealFloatingType()) {
1138  Kind = CK_IntegralToFloating;
1139  return TC_Success;
1140  }
1141  }
1142  }
1143 
1144  // Reverse integral promotion/conversion. All such conversions are themselves
1145  // again integral promotions or conversions and are thus already handled by
1146  // p2 (TryDirectInitialization above).
1147  // (Note: any data loss warnings should be suppressed.)
1148  // The exception is the reverse of enum->integer, i.e. integer->enum (and
1149  // enum->enum). See also C++ 5.2.9p7.
1150  // The same goes for reverse floating point promotion/conversion and
1151  // floating-integral conversions. Again, only floating->enum is relevant.
1152  if (DestType->isEnumeralType()) {
1153  if (SrcType->isIntegralOrEnumerationType()) {
1154  Kind = CK_IntegralCast;
1155  return TC_Success;
1156  } else if (SrcType->isRealFloatingType()) {
1157  Kind = CK_FloatingToIntegral;
1158  return TC_Success;
1159  }
1160  }
1161 
1162  // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1163  // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1164  tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1165  Kind, BasePath);
1166  if (tcr != TC_NotApplicable)
1167  return tcr;
1168 
1169  // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1170  // conversion. C++ 5.2.9p9 has additional information.
1171  // DR54's access restrictions apply here also.
1172  tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1173  OpRange, msg, Kind, BasePath);
1174  if (tcr != TC_NotApplicable)
1175  return tcr;
1176 
1177  // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1178  // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1179  // just the usual constness stuff.
1180  if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1181  QualType SrcPointee = SrcPointer->getPointeeType();
1182  if (SrcPointee->isVoidType()) {
1183  if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1184  QualType DestPointee = DestPointer->getPointeeType();
1185  if (DestPointee->isIncompleteOrObjectType()) {
1186  // This is definitely the intended conversion, but it might fail due
1187  // to a qualifier violation. Note that we permit Objective-C lifetime
1188  // and GC qualifier mismatches here.
1189  if (!CStyle) {
1190  Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1191  Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1192  DestPointeeQuals.removeObjCGCAttr();
1193  DestPointeeQuals.removeObjCLifetime();
1194  SrcPointeeQuals.removeObjCGCAttr();
1195  SrcPointeeQuals.removeObjCLifetime();
1196  if (DestPointeeQuals != SrcPointeeQuals &&
1197  !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1198  msg = diag::err_bad_cxx_cast_qualifiers_away;
1199  return TC_Failed;
1200  }
1201  }
1202  Kind = IsAddressSpaceConversion(SrcType, DestType)
1203  ? CK_AddressSpaceConversion
1204  : CK_BitCast;
1205  return TC_Success;
1206  }
1207 
1208  // Microsoft permits static_cast from 'pointer-to-void' to
1209  // 'pointer-to-function'.
1210  if (!CStyle && Self.getLangOpts().MSVCCompat &&
1211  DestPointee->isFunctionType()) {
1212  Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1213  Kind = CK_BitCast;
1214  return TC_Success;
1215  }
1216  }
1217  else if (DestType->isObjCObjectPointerType()) {
1218  // allow both c-style cast and static_cast of objective-c pointers as
1219  // they are pervasive.
1220  Kind = CK_CPointerToObjCPointerCast;
1221  return TC_Success;
1222  }
1223  else if (CStyle && DestType->isBlockPointerType()) {
1224  // allow c-style cast of void * to block pointers.
1225  Kind = CK_AnyPointerToBlockPointerCast;
1226  return TC_Success;
1227  }
1228  }
1229  }
1230  // Allow arbitrary objective-c pointer conversion with static casts.
1231  if (SrcType->isObjCObjectPointerType() &&
1232  DestType->isObjCObjectPointerType()) {
1233  Kind = CK_BitCast;
1234  return TC_Success;
1235  }
1236  // Allow ns-pointer to cf-pointer conversion in either direction
1237  // with static casts.
1238  if (!CStyle &&
1239  Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1240  return TC_Success;
1241 
1242  // See if it looks like the user is trying to convert between
1243  // related record types, and select a better diagnostic if so.
1244  if (auto SrcPointer = SrcType->getAs<PointerType>())
1245  if (auto DestPointer = DestType->getAs<PointerType>())
1246  if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1247  DestPointer->getPointeeType()->getAs<RecordType>())
1248  msg = diag::err_bad_cxx_cast_unrelated_class;
1249 
1250  // We tried everything. Everything! Nothing works! :-(
1251  return TC_NotApplicable;
1252 }
1253 
1254 /// Tests whether a conversion according to N2844 is valid.
1256  QualType DestType, bool CStyle,
1257  CastKind &Kind, CXXCastPath &BasePath,
1258  unsigned &msg) {
1259  // C++11 [expr.static.cast]p3:
1260  // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1261  // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1262  const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1263  if (!R)
1264  return TC_NotApplicable;
1265 
1266  if (!SrcExpr->isGLValue())
1267  return TC_NotApplicable;
1268 
1269  // Because we try the reference downcast before this function, from now on
1270  // this is the only cast possibility, so we issue an error if we fail now.
1271  // FIXME: Should allow casting away constness if CStyle.
1272  bool DerivedToBase;
1273  bool ObjCConversion;
1274  bool ObjCLifetimeConversion;
1275  QualType FromType = SrcExpr->getType();
1276  QualType ToType = R->getPointeeType();
1277  if (CStyle) {
1278  FromType = FromType.getUnqualifiedType();
1279  ToType = ToType.getUnqualifiedType();
1280  }
1281 
1283  SrcExpr->getBeginLoc(), ToType, FromType, DerivedToBase, ObjCConversion,
1284  ObjCLifetimeConversion);
1285  if (RefResult != Sema::Ref_Compatible) {
1286  if (CStyle || RefResult == Sema::Ref_Incompatible)
1287  return TC_NotApplicable;
1288  // Diagnose types which are reference-related but not compatible here since
1289  // we can provide better diagnostics. In these cases forwarding to
1290  // [expr.static.cast]p4 should never result in a well-formed cast.
1291  msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1292  : diag::err_bad_rvalue_to_rvalue_cast;
1293  return TC_Failed;
1294  }
1295 
1296  if (DerivedToBase) {
1297  Kind = CK_DerivedToBase;
1298  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1299  /*DetectVirtual=*/true);
1300  if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
1301  R->getPointeeType(), Paths))
1302  return TC_NotApplicable;
1303 
1304  Self.BuildBasePathArray(Paths, BasePath);
1305  } else
1306  Kind = CK_NoOp;
1307 
1308  return TC_Success;
1309 }
1310 
1311 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1313 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1314  bool CStyle, SourceRange OpRange,
1315  unsigned &msg, CastKind &Kind,
1316  CXXCastPath &BasePath) {
1317  // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1318  // cast to type "reference to cv2 D", where D is a class derived from B,
1319  // if a valid standard conversion from "pointer to D" to "pointer to B"
1320  // exists, cv2 >= cv1, and B is not a virtual base class of D.
1321  // In addition, DR54 clarifies that the base must be accessible in the
1322  // current context. Although the wording of DR54 only applies to the pointer
1323  // variant of this rule, the intent is clearly for it to apply to the this
1324  // conversion as well.
1325 
1326  const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1327  if (!DestReference) {
1328  return TC_NotApplicable;
1329  }
1330  bool RValueRef = DestReference->isRValueReferenceType();
1331  if (!RValueRef && !SrcExpr->isLValue()) {
1332  // We know the left side is an lvalue reference, so we can suggest a reason.
1333  msg = diag::err_bad_cxx_cast_rvalue;
1334  return TC_NotApplicable;
1335  }
1336 
1337  QualType DestPointee = DestReference->getPointeeType();
1338 
1339  // FIXME: If the source is a prvalue, we should issue a warning (because the
1340  // cast always has undefined behavior), and for AST consistency, we should
1341  // materialize a temporary.
1342  return TryStaticDowncast(Self,
1343  Self.Context.getCanonicalType(SrcExpr->getType()),
1344  Self.Context.getCanonicalType(DestPointee), CStyle,
1345  OpRange, SrcExpr->getType(), DestType, msg, Kind,
1346  BasePath);
1347 }
1348 
1349 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1352  bool CStyle, SourceRange OpRange,
1353  unsigned &msg, CastKind &Kind,
1354  CXXCastPath &BasePath) {
1355  // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1356  // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1357  // is a class derived from B, if a valid standard conversion from "pointer
1358  // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1359  // class of D.
1360  // In addition, DR54 clarifies that the base must be accessible in the
1361  // current context.
1362 
1363  const PointerType *DestPointer = DestType->getAs<PointerType>();
1364  if (!DestPointer) {
1365  return TC_NotApplicable;
1366  }
1367 
1368  const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1369  if (!SrcPointer) {
1370  msg = diag::err_bad_static_cast_pointer_nonpointer;
1371  return TC_NotApplicable;
1372  }
1373 
1374  return TryStaticDowncast(Self,
1375  Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1376  Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1377  CStyle, OpRange, SrcType, DestType, msg, Kind,
1378  BasePath);
1379 }
1380 
1381 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1382 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1383 /// DestType is possible and allowed.
1386  bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1387  QualType OrigDestType, unsigned &msg,
1388  CastKind &Kind, CXXCastPath &BasePath) {
1389  // We can only work with complete types. But don't complain if it doesn't work
1390  if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1391  !Self.isCompleteType(OpRange.getBegin(), DestType))
1392  return TC_NotApplicable;
1393 
1394  // Downcast can only happen in class hierarchies, so we need classes.
1395  if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1396  return TC_NotApplicable;
1397  }
1398 
1399  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1400  /*DetectVirtual=*/true);
1401  if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1402  return TC_NotApplicable;
1403  }
1404 
1405  // Target type does derive from source type. Now we're serious. If an error
1406  // appears now, it's not ignored.
1407  // This may not be entirely in line with the standard. Take for example:
1408  // struct A {};
1409  // struct B : virtual A {
1410  // B(A&);
1411  // };
1412  //
1413  // void f()
1414  // {
1415  // (void)static_cast<const B&>(*((A*)0));
1416  // }
1417  // As far as the standard is concerned, p5 does not apply (A is virtual), so
1418  // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1419  // However, both GCC and Comeau reject this example, and accepting it would
1420  // mean more complex code if we're to preserve the nice error message.
1421  // FIXME: Being 100% compliant here would be nice to have.
1422 
1423  // Must preserve cv, as always, unless we're in C-style mode.
1424  if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1425  msg = diag::err_bad_cxx_cast_qualifiers_away;
1426  return TC_Failed;
1427  }
1428 
1429  if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1430  // This code is analoguous to that in CheckDerivedToBaseConversion, except
1431  // that it builds the paths in reverse order.
1432  // To sum up: record all paths to the base and build a nice string from
1433  // them. Use it to spice up the error message.
1434  if (!Paths.isRecordingPaths()) {
1435  Paths.clear();
1436  Paths.setRecordingPaths(true);
1437  Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1438  }
1439  std::string PathDisplayStr;
1440  std::set<unsigned> DisplayedPaths;
1441  for (clang::CXXBasePath &Path : Paths) {
1442  if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1443  // We haven't displayed a path to this particular base
1444  // class subobject yet.
1445  PathDisplayStr += "\n ";
1446  for (CXXBasePathElement &PE : llvm::reverse(Path))
1447  PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1448  PathDisplayStr += QualType(DestType).getAsString();
1449  }
1450  }
1451 
1452  Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1453  << QualType(SrcType).getUnqualifiedType()
1454  << QualType(DestType).getUnqualifiedType()
1455  << PathDisplayStr << OpRange;
1456  msg = 0;
1457  return TC_Failed;
1458  }
1459 
1460  if (Paths.getDetectedVirtual() != nullptr) {
1461  QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1462  Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1463  << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1464  msg = 0;
1465  return TC_Failed;
1466  }
1467 
1468  if (!CStyle) {
1469  switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1470  SrcType, DestType,
1471  Paths.front(),
1472  diag::err_downcast_from_inaccessible_base)) {
1473  case Sema::AR_accessible:
1474  case Sema::AR_delayed: // be optimistic
1475  case Sema::AR_dependent: // be optimistic
1476  break;
1477 
1478  case Sema::AR_inaccessible:
1479  msg = 0;
1480  return TC_Failed;
1481  }
1482  }
1483 
1484  Self.BuildBasePathArray(Paths, BasePath);
1485  Kind = CK_BaseToDerived;
1486  return TC_Success;
1487 }
1488 
1489 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1490 /// C++ 5.2.9p9 is valid:
1491 ///
1492 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1493 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1494 /// where B is a base class of D [...].
1495 ///
1498  QualType DestType, bool CStyle,
1499  SourceRange OpRange,
1500  unsigned &msg, CastKind &Kind,
1501  CXXCastPath &BasePath) {
1502  const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1503  if (!DestMemPtr)
1504  return TC_NotApplicable;
1505 
1506  bool WasOverloadedFunction = false;
1507  DeclAccessPair FoundOverload;
1508  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1509  if (FunctionDecl *Fn
1510  = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1511  FoundOverload)) {
1512  CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1513  SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1514  Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1515  WasOverloadedFunction = true;
1516  }
1517  }
1518 
1519  const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1520  if (!SrcMemPtr) {
1521  msg = diag::err_bad_static_cast_member_pointer_nonmp;
1522  return TC_NotApplicable;
1523  }
1524 
1525  // Lock down the inheritance model right now in MS ABI, whether or not the
1526  // pointee types are the same.
1527  if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1528  (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1529  (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1530  }
1531 
1532  // T == T, modulo cv
1533  if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1534  DestMemPtr->getPointeeType()))
1535  return TC_NotApplicable;
1536 
1537  // B base of D
1538  QualType SrcClass(SrcMemPtr->getClass(), 0);
1539  QualType DestClass(DestMemPtr->getClass(), 0);
1540  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1541  /*DetectVirtual=*/true);
1542  if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1543  return TC_NotApplicable;
1544 
1545  // B is a base of D. But is it an allowed base? If not, it's a hard error.
1546  if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1547  Paths.clear();
1548  Paths.setRecordingPaths(true);
1549  bool StillOkay =
1550  Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1551  assert(StillOkay);
1552  (void)StillOkay;
1553  std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1554  Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1555  << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1556  msg = 0;
1557  return TC_Failed;
1558  }
1559 
1560  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1561  Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1562  << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1563  msg = 0;
1564  return TC_Failed;
1565  }
1566 
1567  if (!CStyle) {
1568  switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1569  DestClass, SrcClass,
1570  Paths.front(),
1571  diag::err_upcast_to_inaccessible_base)) {
1572  case Sema::AR_accessible:
1573  case Sema::AR_delayed:
1574  case Sema::AR_dependent:
1575  // Optimistically assume that the delayed and dependent cases
1576  // will work out.
1577  break;
1578 
1579  case Sema::AR_inaccessible:
1580  msg = 0;
1581  return TC_Failed;
1582  }
1583  }
1584 
1585  if (WasOverloadedFunction) {
1586  // Resolve the address of the overloaded function again, this time
1587  // allowing complaints if something goes wrong.
1589  DestType,
1590  true,
1591  FoundOverload);
1592  if (!Fn) {
1593  msg = 0;
1594  return TC_Failed;
1595  }
1596 
1597  SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1598  if (!SrcExpr.isUsable()) {
1599  msg = 0;
1600  return TC_Failed;
1601  }
1602  }
1603 
1604  Self.BuildBasePathArray(Paths, BasePath);
1605  Kind = CK_DerivedToBaseMemberPointer;
1606  return TC_Success;
1607 }
1608 
1609 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1610 /// is valid:
1611 ///
1612 /// An expression e can be explicitly converted to a type T using a
1613 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1615 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1617  SourceRange OpRange, unsigned &msg,
1618  CastKind &Kind, bool ListInitialization) {
1619  if (DestType->isRecordType()) {
1620  if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1621  diag::err_bad_dynamic_cast_incomplete) ||
1622  Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1623  diag::err_allocation_of_abstract_type)) {
1624  msg = 0;
1625  return TC_Failed;
1626  }
1627  }
1628 
1630  InitializationKind InitKind
1631  = (CCK == Sema::CCK_CStyleCast)
1632  ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1633  ListInitialization)
1634  : (CCK == Sema::CCK_FunctionalCast)
1635  ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1636  : InitializationKind::CreateCast(OpRange);
1637  Expr *SrcExprRaw = SrcExpr.get();
1638  // FIXME: Per DR242, we should check for an implicit conversion sequence
1639  // or for a constructor that could be invoked by direct-initialization
1640  // here, not for an initialization sequence.
1641  InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1642 
1643  // At this point of CheckStaticCast, if the destination is a reference,
1644  // or the expression is an overload expression this has to work.
1645  // There is no other way that works.
1646  // On the other hand, if we're checking a C-style cast, we've still got
1647  // the reinterpret_cast way.
1648  bool CStyle
1649  = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1650  if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1651  return TC_NotApplicable;
1652 
1653  ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1654  if (Result.isInvalid()) {
1655  msg = 0;
1656  return TC_Failed;
1657  }
1658 
1659  if (InitSeq.isConstructorInitialization())
1660  Kind = CK_ConstructorConversion;
1661  else
1662  Kind = CK_NoOp;
1663 
1664  SrcExpr = Result;
1665  return TC_Success;
1666 }
1667 
1668 /// TryConstCast - See if a const_cast from source to destination is allowed,
1669 /// and perform it if it is.
1671  QualType DestType, bool CStyle,
1672  unsigned &msg) {
1673  DestType = Self.Context.getCanonicalType(DestType);
1674  QualType SrcType = SrcExpr.get()->getType();
1675  bool NeedToMaterializeTemporary = false;
1676 
1677  if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1678  // C++11 5.2.11p4:
1679  // if a pointer to T1 can be explicitly converted to the type "pointer to
1680  // T2" using a const_cast, then the following conversions can also be
1681  // made:
1682  // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1683  // type T2 using the cast const_cast<T2&>;
1684  // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1685  // type T2 using the cast const_cast<T2&&>; and
1686  // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1687  // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1688 
1689  if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1690  // Cannot const_cast non-lvalue to lvalue reference type. But if this
1691  // is C-style, static_cast might find a way, so we simply suggest a
1692  // message and tell the parent to keep searching.
1693  msg = diag::err_bad_cxx_cast_rvalue;
1694  return TC_NotApplicable;
1695  }
1696 
1697  if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1698  if (!SrcType->isRecordType()) {
1699  // Cannot const_cast non-class prvalue to rvalue reference type. But if
1700  // this is C-style, static_cast can do this.
1701  msg = diag::err_bad_cxx_cast_rvalue;
1702  return TC_NotApplicable;
1703  }
1704 
1705  // Materialize the class prvalue so that the const_cast can bind a
1706  // reference to it.
1707  NeedToMaterializeTemporary = true;
1708  }
1709 
1710  // It's not completely clear under the standard whether we can
1711  // const_cast bit-field gl-values. Doing so would not be
1712  // intrinsically complicated, but for now, we say no for
1713  // consistency with other compilers and await the word of the
1714  // committee.
1715  if (SrcExpr.get()->refersToBitField()) {
1716  msg = diag::err_bad_cxx_cast_bitfield;
1717  return TC_NotApplicable;
1718  }
1719 
1720  DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1721  SrcType = Self.Context.getPointerType(SrcType);
1722  }
1723 
1724  // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1725  // the rules for const_cast are the same as those used for pointers.
1726 
1727  if (!DestType->isPointerType() &&
1728  !DestType->isMemberPointerType() &&
1729  !DestType->isObjCObjectPointerType()) {
1730  // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1731  // was a reference type, we converted it to a pointer above.
1732  // The status of rvalue references isn't entirely clear, but it looks like
1733  // conversion to them is simply invalid.
1734  // C++ 5.2.11p3: For two pointer types [...]
1735  if (!CStyle)
1736  msg = diag::err_bad_const_cast_dest;
1737  return TC_NotApplicable;
1738  }
1739  if (DestType->isFunctionPointerType() ||
1740  DestType->isMemberFunctionPointerType()) {
1741  // Cannot cast direct function pointers.
1742  // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1743  // T is the ultimate pointee of source and target type.
1744  if (!CStyle)
1745  msg = diag::err_bad_const_cast_dest;
1746  return TC_NotApplicable;
1747  }
1748 
1749  // C++ [expr.const.cast]p3:
1750  // "For two similar types T1 and T2, [...]"
1751  //
1752  // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1753  // type qualifiers. (Likewise, we ignore other changes when determining
1754  // whether a cast casts away constness.)
1755  if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
1756  return TC_NotApplicable;
1757 
1758  if (NeedToMaterializeTemporary)
1759  // This is a const_cast from a class prvalue to an rvalue reference type.
1760  // Materialize a temporary to store the result of the conversion.
1761  SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1762  SrcExpr.get(),
1763  /*IsLValueReference*/ false);
1764 
1765  return TC_Success;
1766 }
1767 
1768 // Checks for undefined behavior in reinterpret_cast.
1769 // The cases that is checked for is:
1770 // *reinterpret_cast<T*>(&a)
1771 // reinterpret_cast<T&>(a)
1772 // where accessing 'a' as type 'T' will result in undefined behavior.
1774  bool IsDereference,
1775  SourceRange Range) {
1776  unsigned DiagID = IsDereference ?
1777  diag::warn_pointer_indirection_from_incompatible_type :
1778  diag::warn_undefined_reinterpret_cast;
1779 
1780  if (Diags.isIgnored(DiagID, Range.getBegin()))
1781  return;
1782 
1783  QualType SrcTy, DestTy;
1784  if (IsDereference) {
1785  if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1786  return;
1787  }
1788  SrcTy = SrcType->getPointeeType();
1789  DestTy = DestType->getPointeeType();
1790  } else {
1791  if (!DestType->getAs<ReferenceType>()) {
1792  return;
1793  }
1794  SrcTy = SrcType;
1795  DestTy = DestType->getPointeeType();
1796  }
1797 
1798  // Cast is compatible if the types are the same.
1799  if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1800  return;
1801  }
1802  // or one of the types is a char or void type
1803  if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1804  SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1805  return;
1806  }
1807  // or one of the types is a tag type.
1808  if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1809  return;
1810  }
1811 
1812  // FIXME: Scoped enums?
1813  if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1814  (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1815  if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1816  return;
1817  }
1818  }
1819 
1820  Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1821 }
1822 
1823 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1824  QualType DestType) {
1825  QualType SrcType = SrcExpr.get()->getType();
1826  if (Self.Context.hasSameType(SrcType, DestType))
1827  return;
1828  if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1829  if (SrcPtrTy->isObjCSelType()) {
1830  QualType DT = DestType;
1831  if (isa<PointerType>(DestType))
1832  DT = DestType->getPointeeType();
1833  if (!DT.getUnqualifiedType()->isVoidType())
1834  Self.Diag(SrcExpr.get()->getExprLoc(),
1835  diag::warn_cast_pointer_from_sel)
1836  << SrcType << DestType << SrcExpr.get()->getSourceRange();
1837  }
1838 }
1839 
1840 /// Diagnose casts that change the calling convention of a pointer to a function
1841 /// defined in the current TU.
1842 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1843  QualType DstType, SourceRange OpRange) {
1844  // Check if this cast would change the calling convention of a function
1845  // pointer type.
1846  QualType SrcType = SrcExpr.get()->getType();
1847  if (Self.Context.hasSameType(SrcType, DstType) ||
1848  !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1849  return;
1850  const auto *SrcFTy =
1851  SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1852  const auto *DstFTy =
1853  DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1854  CallingConv SrcCC = SrcFTy->getCallConv();
1855  CallingConv DstCC = DstFTy->getCallConv();
1856  if (SrcCC == DstCC)
1857  return;
1858 
1859  // We have a calling convention cast. Check if the source is a pointer to a
1860  // known, specific function that has already been defined.
1861  Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1862  if (auto *UO = dyn_cast<UnaryOperator>(Src))
1863  if (UO->getOpcode() == UO_AddrOf)
1864  Src = UO->getSubExpr()->IgnoreParenImpCasts();
1865  auto *DRE = dyn_cast<DeclRefExpr>(Src);
1866  if (!DRE)
1867  return;
1868  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1869  if (!FD)
1870  return;
1871 
1872  // Only warn if we are casting from the default convention to a non-default
1873  // convention. This can happen when the programmer forgot to apply the calling
1874  // convention to the function declaration and then inserted this cast to
1875  // satisfy the type system.
1877  FD->isVariadic(), FD->isCXXInstanceMember());
1878  if (DstCC == DefaultCC || SrcCC != DefaultCC)
1879  return;
1880 
1881  // Diagnose this cast, as it is probably bad.
1882  StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1883  StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1884  Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1885  << SrcCCName << DstCCName << OpRange;
1886 
1887  // The checks above are cheaper than checking if the diagnostic is enabled.
1888  // However, it's worth checking if the warning is enabled before we construct
1889  // a fixit.
1890  if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1891  return;
1892 
1893  // Try to suggest a fixit to change the calling convention of the function
1894  // whose address was taken. Try to use the latest macro for the convention.
1895  // For example, users probably want to write "WINAPI" instead of "__stdcall"
1896  // to match the Windows header declarations.
1897  SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
1898  Preprocessor &PP = Self.getPreprocessor();
1899  SmallVector<TokenValue, 6> AttrTokens;
1900  SmallString<64> CCAttrText;
1901  llvm::raw_svector_ostream OS(CCAttrText);
1902  if (Self.getLangOpts().MicrosoftExt) {
1903  // __stdcall or __vectorcall
1904  OS << "__" << DstCCName;
1905  IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1906  AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1907  ? TokenValue(II->getTokenID())
1908  : TokenValue(II));
1909  } else {
1910  // __attribute__((stdcall)) or __attribute__((vectorcall))
1911  OS << "__attribute__((" << DstCCName << "))";
1912  AttrTokens.push_back(tok::kw___attribute);
1913  AttrTokens.push_back(tok::l_paren);
1914  AttrTokens.push_back(tok::l_paren);
1915  IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1916  AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1917  ? TokenValue(II->getTokenID())
1918  : TokenValue(II));
1919  AttrTokens.push_back(tok::r_paren);
1920  AttrTokens.push_back(tok::r_paren);
1921  }
1922  StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1923  if (!AttrSpelling.empty())
1924  CCAttrText = AttrSpelling;
1925  OS << ' ';
1926  Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1927  << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1928 }
1929 
1930 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1931  const Expr *SrcExpr, QualType DestType,
1932  Sema &Self) {
1933  QualType SrcType = SrcExpr->getType();
1934 
1935  // Not warning on reinterpret_cast, boolean, constant expressions, etc
1936  // are not explicit design choices, but consistent with GCC's behavior.
1937  // Feel free to modify them if you've reason/evidence for an alternative.
1938  if (CStyle && SrcType->isIntegralType(Self.Context)
1939  && !SrcType->isBooleanType()
1940  && !SrcType->isEnumeralType()
1941  && !SrcExpr->isIntegerConstantExpr(Self.Context)
1942  && Self.Context.getTypeSize(DestType) >
1943  Self.Context.getTypeSize(SrcType)) {
1944  // Separate between casts to void* and non-void* pointers.
1945  // Some APIs use (abuse) void* for something like a user context,
1946  // and often that value is an integer even if it isn't a pointer itself.
1947  // Having a separate warning flag allows users to control the warning
1948  // for their workflow.
1949  unsigned Diag = DestType->isVoidPointerType() ?
1950  diag::warn_int_to_void_pointer_cast
1951  : diag::warn_int_to_pointer_cast;
1952  Self.Diag(Loc, Diag) << SrcType << DestType;
1953  }
1954 }
1955 
1956 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1957  ExprResult &Result) {
1958  // We can only fix an overloaded reinterpret_cast if
1959  // - it is a template with explicit arguments that resolves to an lvalue
1960  // unambiguously, or
1961  // - it is the only function in an overload set that may have its address
1962  // taken.
1963 
1964  Expr *E = Result.get();
1965  // TODO: what if this fails because of DiagnoseUseOfDecl or something
1966  // like it?
1968  Result,
1969  Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1970  ) &&
1971  Result.isUsable())
1972  return true;
1973 
1974  // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1975  // preserves Result.
1976  Result = E;
1978  Result, /*DoFunctionPointerConversion=*/true))
1979  return false;
1980  return Result.isUsable();
1981 }
1982 
1984  QualType DestType, bool CStyle,
1985  SourceRange OpRange,
1986  unsigned &msg,
1987  CastKind &Kind) {
1988  bool IsLValueCast = false;
1989 
1990  DestType = Self.Context.getCanonicalType(DestType);
1991  QualType SrcType = SrcExpr.get()->getType();
1992 
1993  // Is the source an overloaded name? (i.e. &foo)
1994  // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
1995  if (SrcType == Self.Context.OverloadTy) {
1996  ExprResult FixedExpr = SrcExpr;
1997  if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
1998  return TC_NotApplicable;
1999 
2000  assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2001  SrcExpr = FixedExpr;
2002  SrcType = SrcExpr.get()->getType();
2003  }
2004 
2005  if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2006  if (!SrcExpr.get()->isGLValue()) {
2007  // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2008  // similar comment in const_cast.
2009  msg = diag::err_bad_cxx_cast_rvalue;
2010  return TC_NotApplicable;
2011  }
2012 
2013  if (!CStyle) {
2014  Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2015  /*isDereference=*/false, OpRange);
2016  }
2017 
2018  // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2019  // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2020  // built-in & and * operators.
2021 
2022  const char *inappropriate = nullptr;
2023  switch (SrcExpr.get()->getObjectKind()) {
2024  case OK_Ordinary:
2025  break;
2026  case OK_BitField:
2027  msg = diag::err_bad_cxx_cast_bitfield;
2028  return TC_NotApplicable;
2029  // FIXME: Use a specific diagnostic for the rest of these cases.
2030  case OK_VectorComponent: inappropriate = "vector element"; break;
2031  case OK_ObjCProperty: inappropriate = "property expression"; break;
2032  case OK_ObjCSubscript: inappropriate = "container subscripting expression";
2033  break;
2034  }
2035  if (inappropriate) {
2036  Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2037  << inappropriate << DestType
2038  << OpRange << SrcExpr.get()->getSourceRange();
2039  msg = 0; SrcExpr = ExprError();
2040  return TC_NotApplicable;
2041  }
2042 
2043  // This code does this transformation for the checked types.
2044  DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2045  SrcType = Self.Context.getPointerType(SrcType);
2046 
2047  IsLValueCast = true;
2048  }
2049 
2050  // Canonicalize source for comparison.
2051  SrcType = Self.Context.getCanonicalType(SrcType);
2052 
2053  const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2054  *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2055  if (DestMemPtr && SrcMemPtr) {
2056  // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2057  // can be explicitly converted to an rvalue of type "pointer to member
2058  // of Y of type T2" if T1 and T2 are both function types or both object
2059  // types.
2060  if (DestMemPtr->isMemberFunctionPointer() !=
2061  SrcMemPtr->isMemberFunctionPointer())
2062  return TC_NotApplicable;
2063 
2064  if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2065  // We need to determine the inheritance model that the class will use if
2066  // haven't yet.
2067  (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2068  (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2069  }
2070 
2071  // Don't allow casting between member pointers of different sizes.
2072  if (Self.Context.getTypeSize(DestMemPtr) !=
2073  Self.Context.getTypeSize(SrcMemPtr)) {
2074  msg = diag::err_bad_cxx_cast_member_pointer_size;
2075  return TC_Failed;
2076  }
2077 
2078  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2079  // constness.
2080  // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2081  // we accept it.
2082  if (auto CACK =
2083  CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2084  /*CheckObjCLifetime=*/CStyle))
2085  return getCastAwayConstnessCastKind(CACK, msg);
2086 
2087  // A valid member pointer cast.
2088  assert(!IsLValueCast);
2089  Kind = CK_ReinterpretMemberPointer;
2090  return TC_Success;
2091  }
2092 
2093  // See below for the enumeral issue.
2094  if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2095  // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2096  // type large enough to hold it. A value of std::nullptr_t can be
2097  // converted to an integral type; the conversion has the same meaning
2098  // and validity as a conversion of (void*)0 to the integral type.
2099  if (Self.Context.getTypeSize(SrcType) >
2100  Self.Context.getTypeSize(DestType)) {
2101  msg = diag::err_bad_reinterpret_cast_small_int;
2102  return TC_Failed;
2103  }
2104  Kind = CK_PointerToIntegral;
2105  return TC_Success;
2106  }
2107 
2108  // Allow reinterpret_casts between vectors of the same size and
2109  // between vectors and integers of the same size.
2110  bool destIsVector = DestType->isVectorType();
2111  bool srcIsVector = SrcType->isVectorType();
2112  if (srcIsVector || destIsVector) {
2113  // The non-vector type, if any, must have integral type. This is
2114  // the same rule that C vector casts use; note, however, that enum
2115  // types are not integral in C++.
2116  if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2117  (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2118  return TC_NotApplicable;
2119 
2120  // The size we want to consider is eltCount * eltSize.
2121  // That's exactly what the lax-conversion rules will check.
2122  if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2123  Kind = CK_BitCast;
2124  return TC_Success;
2125  }
2126 
2127  // Otherwise, pick a reasonable diagnostic.
2128  if (!destIsVector)
2129  msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2130  else if (!srcIsVector)
2131  msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2132  else
2133  msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2134 
2135  return TC_Failed;
2136  }
2137 
2138  if (SrcType == DestType) {
2139  // C++ 5.2.10p2 has a note that mentions that, subject to all other
2140  // restrictions, a cast to the same type is allowed so long as it does not
2141  // cast away constness. In C++98, the intent was not entirely clear here,
2142  // since all other paragraphs explicitly forbid casts to the same type.
2143  // C++11 clarifies this case with p2.
2144  //
2145  // The only allowed types are: integral, enumeration, pointer, or
2146  // pointer-to-member types. We also won't restrict Obj-C pointers either.
2147  Kind = CK_NoOp;
2149  if (SrcType->isIntegralOrEnumerationType() ||
2150  SrcType->isAnyPointerType() ||
2151  SrcType->isMemberPointerType() ||
2152  SrcType->isBlockPointerType()) {
2153  Result = TC_Success;
2154  }
2155  return Result;
2156  }
2157 
2158  bool destIsPtr = DestType->isAnyPointerType() ||
2159  DestType->isBlockPointerType();
2160  bool srcIsPtr = SrcType->isAnyPointerType() ||
2161  SrcType->isBlockPointerType();
2162  if (!destIsPtr && !srcIsPtr) {
2163  // Except for std::nullptr_t->integer and lvalue->reference, which are
2164  // handled above, at least one of the two arguments must be a pointer.
2165  return TC_NotApplicable;
2166  }
2167 
2168  if (DestType->isIntegralType(Self.Context)) {
2169  assert(srcIsPtr && "One type must be a pointer");
2170  // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2171  // type large enough to hold it; except in Microsoft mode, where the
2172  // integral type size doesn't matter (except we don't allow bool).
2173  bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2174  !DestType->isBooleanType();
2175  if ((Self.Context.getTypeSize(SrcType) >
2176  Self.Context.getTypeSize(DestType)) &&
2177  !MicrosoftException) {
2178  msg = diag::err_bad_reinterpret_cast_small_int;
2179  return TC_Failed;
2180  }
2181  Kind = CK_PointerToIntegral;
2182  return TC_Success;
2183  }
2184 
2185  if (SrcType->isIntegralOrEnumerationType()) {
2186  assert(destIsPtr && "One type must be a pointer");
2187  checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2188  Self);
2189  // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2190  // converted to a pointer.
2191  // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2192  // necessarily converted to a null pointer value.]
2193  Kind = CK_IntegralToPointer;
2194  return TC_Success;
2195  }
2196 
2197  if (!destIsPtr || !srcIsPtr) {
2198  // With the valid non-pointer conversions out of the way, we can be even
2199  // more stringent.
2200  return TC_NotApplicable;
2201  }
2202 
2203  // Cannot convert between block pointers and Objective-C object pointers.
2204  if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2205  (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2206  return TC_NotApplicable;
2207 
2208  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2209  // The C-style cast operator can.
2210  TryCastResult SuccessResult = TC_Success;
2211  if (auto CACK =
2212  CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2213  /*CheckObjCLifetime=*/CStyle))
2214  SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2215 
2216  if (IsLValueCast) {
2217  Kind = CK_LValueBitCast;
2218  } else if (DestType->isObjCObjectPointerType()) {
2219  Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2220  } else if (DestType->isBlockPointerType()) {
2221  if (!SrcType->isBlockPointerType()) {
2222  Kind = CK_AnyPointerToBlockPointerCast;
2223  } else {
2224  Kind = CK_BitCast;
2225  }
2226  } else if (IsAddressSpaceConversion(SrcType, DestType)) {
2227  Kind = CK_AddressSpaceConversion;
2228  } else {
2229  Kind = CK_BitCast;
2230  }
2231 
2232  // Any pointer can be cast to an Objective-C pointer type with a C-style
2233  // cast.
2234  if (CStyle && DestType->isObjCObjectPointerType()) {
2235  return SuccessResult;
2236  }
2237  if (CStyle)
2238  DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2239 
2240  DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2241 
2242  // Not casting away constness, so the only remaining check is for compatible
2243  // pointer categories.
2244 
2245  if (SrcType->isFunctionPointerType()) {
2246  if (DestType->isFunctionPointerType()) {
2247  // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2248  // a pointer to a function of a different type.
2249  return SuccessResult;
2250  }
2251 
2252  // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2253  // an object type or vice versa is conditionally-supported.
2254  // Compilers support it in C++03 too, though, because it's necessary for
2255  // casting the return value of dlsym() and GetProcAddress().
2256  // FIXME: Conditionally-supported behavior should be configurable in the
2257  // TargetInfo or similar.
2258  Self.Diag(OpRange.getBegin(),
2259  Self.getLangOpts().CPlusPlus11 ?
2260  diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2261  << OpRange;
2262  return SuccessResult;
2263  }
2264 
2265  if (DestType->isFunctionPointerType()) {
2266  // See above.
2267  Self.Diag(OpRange.getBegin(),
2268  Self.getLangOpts().CPlusPlus11 ?
2269  diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2270  << OpRange;
2271  return SuccessResult;
2272  }
2273 
2274  // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2275  // a pointer to an object of different type.
2276  // Void pointers are not specified, but supported by every compiler out there.
2277  // So we finish by allowing everything that remains - it's got to be two
2278  // object pointers.
2279  return SuccessResult;
2280 }
2281 
2282 void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2283  // In OpenCL only conversions between pointers to objects in overlapping
2284  // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2285  // with any named one, except for constant.
2286  if (Self.getLangOpts().OpenCL) {
2287  auto SrcPtrType = SrcType->getAs<PointerType>();
2288  if (!SrcPtrType)
2289  return;
2290  auto DestPtrType = DestType->getAs<PointerType>();
2291  if (!DestPtrType)
2292  return;
2293  if (!DestPtrType->isAddressSpaceOverlapping(*SrcPtrType)) {
2294  Self.Diag(OpRange.getBegin(),
2295  diag::err_typecheck_incompatible_address_space)
2296  << SrcType << DestType << Sema::AA_Casting
2297  << SrcExpr.get()->getSourceRange();
2298  SrcExpr = ExprError();
2299  }
2300  }
2301 }
2302 
2303 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2304  bool ListInitialization) {
2305  assert(Self.getLangOpts().CPlusPlus);
2306 
2307  // Handle placeholders.
2308  if (isPlaceholder()) {
2309  // C-style casts can resolve __unknown_any types.
2310  if (claimPlaceholder(BuiltinType::UnknownAny)) {
2311  SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2312  SrcExpr.get(), Kind,
2313  ValueKind, BasePath);
2314  return;
2315  }
2316 
2317  checkNonOverloadPlaceholders();
2318  if (SrcExpr.isInvalid())
2319  return;
2320  }
2321 
2322  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2323  // This test is outside everything else because it's the only case where
2324  // a non-lvalue-reference target type does not lead to decay.
2325  if (DestType->isVoidType()) {
2326  Kind = CK_ToVoid;
2327 
2328  if (claimPlaceholder(BuiltinType::Overload)) {
2330  SrcExpr, /* Decay Function to ptr */ false,
2331  /* Complain */ true, DestRange, DestType,
2332  diag::err_bad_cstyle_cast_overload);
2333  if (SrcExpr.isInvalid())
2334  return;
2335  }
2336 
2337  SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2338  return;
2339  }
2340 
2341  // If the type is dependent, we won't do any other semantic analysis now.
2342  if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2343  SrcExpr.get()->isValueDependent()) {
2344  assert(Kind == CK_Dependent);
2345  return;
2346  }
2347 
2348  if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2349  !isPlaceholder(BuiltinType::Overload)) {
2350  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2351  if (SrcExpr.isInvalid())
2352  return;
2353  }
2354 
2355  // AltiVec vector initialization with a single literal.
2356  if (const VectorType *vecTy = DestType->getAs<VectorType>())
2357  if (vecTy->getVectorKind() == VectorType::AltiVecVector
2358  && (SrcExpr.get()->getType()->isIntegerType()
2359  || SrcExpr.get()->getType()->isFloatingType())) {
2360  Kind = CK_VectorSplat;
2361  SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2362  return;
2363  }
2364 
2365  // C++ [expr.cast]p5: The conversions performed by
2366  // - a const_cast,
2367  // - a static_cast,
2368  // - a static_cast followed by a const_cast,
2369  // - a reinterpret_cast, or
2370  // - a reinterpret_cast followed by a const_cast,
2371  // can be performed using the cast notation of explicit type conversion.
2372  // [...] If a conversion can be interpreted in more than one of the ways
2373  // listed above, the interpretation that appears first in the list is used,
2374  // even if a cast resulting from that interpretation is ill-formed.
2375  // In plain language, this means trying a const_cast ...
2376  unsigned msg = diag::err_bad_cxx_cast_generic;
2377  TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2378  /*CStyle*/true, msg);
2379  if (SrcExpr.isInvalid())
2380  return;
2381  if (isValidCast(tcr))
2382  Kind = CK_NoOp;
2383 
2385  = FunctionalStyle? Sema::CCK_FunctionalCast
2387  if (tcr == TC_NotApplicable) {
2388  // ... or if that is not possible, a static_cast, ignoring const, ...
2389  tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
2390  msg, Kind, BasePath, ListInitialization);
2391  if (SrcExpr.isInvalid())
2392  return;
2393 
2394  if (tcr == TC_NotApplicable) {
2395  // ... and finally a reinterpret_cast, ignoring const.
2396  tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2397  OpRange, msg, Kind);
2398  if (SrcExpr.isInvalid())
2399  return;
2400  }
2401  }
2402 
2404  isValidCast(tcr))
2405  checkObjCConversion(CCK);
2406 
2407  if (tcr != TC_Success && msg != 0) {
2408  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2409  DeclAccessPair Found;
2411  DestType,
2412  /*Complain*/ true,
2413  Found);
2414  if (Fn) {
2415  // If DestType is a function type (not to be confused with the function
2416  // pointer type), it will be possible to resolve the function address,
2417  // but the type cast should be considered as failure.
2418  OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2419  Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2420  << OE->getName() << DestType << OpRange
2421  << OE->getQualifierLoc().getSourceRange();
2422  Self.NoteAllOverloadCandidates(SrcExpr.get());
2423  }
2424  } else {
2425  diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2426  OpRange, SrcExpr.get(), DestType, ListInitialization);
2427  }
2428  }
2429 
2430  checkAddressSpaceCast(SrcExpr.get()->getType(), DestType);
2431 
2432  if (isValidCast(tcr)) {
2433  if (Kind == CK_BitCast)
2434  checkCastAlign();
2435  } else {
2436  SrcExpr = ExprError();
2437  }
2438 }
2439 
2440 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2441 /// non-matching type. Such as enum function call to int, int call to
2442 /// pointer; etc. Cast to 'void' is an exception.
2443 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2444  QualType DestType) {
2445  if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2446  SrcExpr.get()->getExprLoc()))
2447  return;
2448 
2449  if (!isa<CallExpr>(SrcExpr.get()))
2450  return;
2451 
2452  QualType SrcType = SrcExpr.get()->getType();
2453  if (DestType.getUnqualifiedType()->isVoidType())
2454  return;
2455  if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2456  && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2457  return;
2458  if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2459  (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2460  (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2461  return;
2462  if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2463  return;
2464  if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2465  return;
2466  if (SrcType->isComplexType() && DestType->isComplexType())
2467  return;
2468  if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2469  return;
2470 
2471  Self.Diag(SrcExpr.get()->getExprLoc(),
2472  diag::warn_bad_function_cast)
2473  << SrcType << DestType << SrcExpr.get()->getSourceRange();
2474 }
2475 
2476 /// Check the semantics of a C-style cast operation, in C.
2477 void CastOperation::CheckCStyleCast() {
2478  assert(!Self.getLangOpts().CPlusPlus);
2479 
2480  // C-style casts can resolve __unknown_any types.
2481  if (claimPlaceholder(BuiltinType::UnknownAny)) {
2482  SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2483  SrcExpr.get(), Kind,
2484  ValueKind, BasePath);
2485  return;
2486  }
2487 
2488  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2489  // type needs to be scalar.
2490  if (DestType->isVoidType()) {
2491  // We don't necessarily do lvalue-to-rvalue conversions on this.
2492  SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2493  if (SrcExpr.isInvalid())
2494  return;
2495 
2496  // Cast to void allows any expr type.
2497  Kind = CK_ToVoid;
2498  return;
2499  }
2500 
2501  // Overloads are allowed with C extensions, so we need to support them.
2502  if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2503  DeclAccessPair DAP;
2505  SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2506  SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2507  else
2508  return;
2509  assert(SrcExpr.isUsable());
2510  }
2511  SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2512  if (SrcExpr.isInvalid())
2513  return;
2514  QualType SrcType = SrcExpr.get()->getType();
2515 
2516  assert(!SrcType->isPlaceholderType());
2517 
2518  checkAddressSpaceCast(SrcType, DestType);
2519  if (SrcExpr.isInvalid())
2520  return;
2521 
2522  if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2523  diag::err_typecheck_cast_to_incomplete)) {
2524  SrcExpr = ExprError();
2525  return;
2526  }
2527 
2528  if (!DestType->isScalarType() && !DestType->isVectorType()) {
2529  const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2530 
2531  if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2532  // GCC struct/union extension: allow cast to self.
2533  Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2534  << DestType << SrcExpr.get()->getSourceRange();
2535  Kind = CK_NoOp;
2536  return;
2537  }
2538 
2539  // GCC's cast to union extension.
2540  if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2541  RecordDecl *RD = DestRecordTy->getDecl();
2542  if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2543  Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2544  << SrcExpr.get()->getSourceRange();
2545  Kind = CK_ToUnion;
2546  return;
2547  } else {
2548  Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2549  << SrcType << SrcExpr.get()->getSourceRange();
2550  SrcExpr = ExprError();
2551  return;
2552  }
2553  }
2554 
2555  // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2556  if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2558  if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2559  llvm::APSInt CastInt = Result.Val.getInt();
2560  if (0 == CastInt) {
2561  Kind = CK_ZeroToOCLOpaqueType;
2562  return;
2563  }
2564  Self.Diag(OpRange.getBegin(),
2565  diag::err_opencl_cast_non_zero_to_event_t)
2566  << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2567  SrcExpr = ExprError();
2568  return;
2569  }
2570  }
2571 
2572  // Reject any other conversions to non-scalar types.
2573  Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2574  << DestType << SrcExpr.get()->getSourceRange();
2575  SrcExpr = ExprError();
2576  return;
2577  }
2578 
2579  // The type we're casting to is known to be a scalar or vector.
2580 
2581  // Require the operand to be a scalar or vector.
2582  if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2583  Self.Diag(SrcExpr.get()->getExprLoc(),
2584  diag::err_typecheck_expect_scalar_operand)
2585  << SrcType << SrcExpr.get()->getSourceRange();
2586  SrcExpr = ExprError();
2587  return;
2588  }
2589 
2590  if (DestType->isExtVectorType()) {
2591  SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2592  return;
2593  }
2594 
2595  if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2596  if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2597  (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2598  Kind = CK_VectorSplat;
2599  SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2600  } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2601  SrcExpr = ExprError();
2602  }
2603  return;
2604  }
2605 
2606  if (SrcType->isVectorType()) {
2607  if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2608  SrcExpr = ExprError();
2609  return;
2610  }
2611 
2612  // The source and target types are both scalars, i.e.
2613  // - arithmetic types (fundamental, enum, and complex)
2614  // - all kinds of pointers
2615  // Note that member pointers were filtered out with C++, above.
2616 
2617  if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2618  Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2619  SrcExpr = ExprError();
2620  return;
2621  }
2622 
2623  // If either type is a pointer, the other type has to be either an
2624  // integer or a pointer.
2625  if (!DestType->isArithmeticType()) {
2626  if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2627  Self.Diag(SrcExpr.get()->getExprLoc(),
2628  diag::err_cast_pointer_from_non_pointer_int)
2629  << SrcType << SrcExpr.get()->getSourceRange();
2630  SrcExpr = ExprError();
2631  return;
2632  }
2633  checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2634  DestType, Self);
2635  } else if (!SrcType->isArithmeticType()) {
2636  if (!DestType->isIntegralType(Self.Context) &&
2637  DestType->isArithmeticType()) {
2638  Self.Diag(SrcExpr.get()->getBeginLoc(),
2639  diag::err_cast_pointer_to_non_pointer_int)
2640  << DestType << SrcExpr.get()->getSourceRange();
2641  SrcExpr = ExprError();
2642  return;
2643  }
2644  }
2645 
2646  if (Self.getLangOpts().OpenCL &&
2647  !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
2648  if (DestType->isHalfType()) {
2649  Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
2650  << DestType << SrcExpr.get()->getSourceRange();
2651  SrcExpr = ExprError();
2652  return;
2653  }
2654  }
2655 
2656  // ARC imposes extra restrictions on casts.
2658  checkObjCConversion(Sema::CCK_CStyleCast);
2659  if (SrcExpr.isInvalid())
2660  return;
2661 
2662  const PointerType *CastPtr = DestType->getAs<PointerType>();
2663  if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
2664  if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2665  Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2666  Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2667  if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2668  ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2669  !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2670  Self.Diag(SrcExpr.get()->getBeginLoc(),
2671  diag::err_typecheck_incompatible_ownership)
2672  << SrcType << DestType << Sema::AA_Casting
2673  << SrcExpr.get()->getSourceRange();
2674  return;
2675  }
2676  }
2677  }
2678  else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2679  Self.Diag(SrcExpr.get()->getBeginLoc(),
2680  diag::err_arc_convesion_of_weak_unavailable)
2681  << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2682  SrcExpr = ExprError();
2683  return;
2684  }
2685  }
2686 
2687  DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2688  DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2689  DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2690  Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2691  if (SrcExpr.isInvalid())
2692  return;
2693 
2694  if (Kind == CK_BitCast)
2695  checkCastAlign();
2696 }
2697 
2698 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2699 /// const, volatile or both.
2700 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2701  QualType DestType) {
2702  if (SrcExpr.isInvalid())
2703  return;
2704 
2705  QualType SrcType = SrcExpr.get()->getType();
2706  if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2707  DestType->isLValueReferenceType()))
2708  return;
2709 
2710  QualType TheOffendingSrcType, TheOffendingDestType;
2711  Qualifiers CastAwayQualifiers;
2712  if (CastsAwayConstness(Self, SrcType, DestType, true, false,
2713  &TheOffendingSrcType, &TheOffendingDestType,
2714  &CastAwayQualifiers) !=
2715  CastAwayConstnessKind::CACK_Similar)
2716  return;
2717 
2718  // FIXME: 'restrict' is not properly handled here.
2719  int qualifiers = -1;
2720  if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2721  qualifiers = 0;
2722  } else if (CastAwayQualifiers.hasConst()) {
2723  qualifiers = 1;
2724  } else if (CastAwayQualifiers.hasVolatile()) {
2725  qualifiers = 2;
2726  }
2727  // This is a variant of int **x; const int **y = (const int **)x;
2728  if (qualifiers == -1)
2729  Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
2730  << SrcType << DestType;
2731  else
2732  Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
2733  << TheOffendingSrcType << TheOffendingDestType << qualifiers;
2734 }
2735 
2737  TypeSourceInfo *CastTypeInfo,
2738  SourceLocation RPLoc,
2739  Expr *CastExpr) {
2740  CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2741  Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2742  Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
2743 
2744  if (getLangOpts().CPlusPlus) {
2745  Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2746  isa<InitListExpr>(CastExpr));
2747  } else {
2748  Op.CheckCStyleCast();
2749  }
2750 
2751  if (Op.SrcExpr.isInvalid())
2752  return ExprError();
2753 
2754  // -Wcast-qual
2755  DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2756 
2757  return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2758  Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
2759  &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
2760 }
2761 
2763  QualType Type,
2764  SourceLocation LPLoc,
2765  Expr *CastExpr,
2766  SourceLocation RPLoc) {
2767  assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
2768  CastOperation Op(*this, Type, CastExpr);
2769  Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2770  Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
2771 
2772  Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
2773  if (Op.SrcExpr.isInvalid())
2774  return ExprError();
2775 
2776  auto *SubExpr = Op.SrcExpr.get();
2777  if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2778  SubExpr = BindExpr->getSubExpr();
2779  if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
2780  ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
2781 
2782  return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2783  Op.ValueKind, CastTypeInfo, Op.Kind,
2784  Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
2785 }
Defines the clang::ASTContext interface.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Represents a function declaration or definition.
Definition: Decl.h:1739
static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType)
Definition: SemaCast.cpp:1050
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2543
QualType getPointeeType() const
Definition: Type.h:2556
A (possibly-)qualified type.
Definition: Type.h:642
bool isBlockPointerType() const
Definition: Type.h:6290
bool isMemberPointerType() const
Definition: Type.h:6313
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
A cast other than a C-style cast.
Definition: Sema.h:9378
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
bool isArithmeticType() const
Definition: Type.cpp:1952
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3361
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:233
static CXXDynamicCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:582
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
bool isRecordType() const
Definition: Type.h:6355
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1302
static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath, bool ListInitialization)
TryStaticCast - Check if a static cast can be performed, and do so if possible.
Definition: SemaCast.cpp:1064
bool isExtVectorType() const
Definition: Type.h:6371
The cast method is appropriate and successful.
Definition: SemaCast.cpp:35
FailureKind getFailureKind() const
Determine why initialization failed.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1046
The base class of the type hierarchy.
Definition: Type.h:1415
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:395
Overloading for a user-defined conversion failed.
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
Ambiguous candidates found.
Definition: Overload.h:60
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:689
A container of type source information.
Definition: Decl.h:86
static CXXFunctionalCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, TypeSourceInfo *Written, CastKind Kind, Expr *Op, const CXXCastPath *Path, SourceLocation LPLoc, SourceLocation RPLoc)
Definition: ExprCXX.cpp:686
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
static_cast
Definition: SemaCast.cpp:48
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3178
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1884
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:6241
An Objective-C array/dictionary subscripting which reads an object or writes at the subscripted array...
Definition: Specifiers.h:141
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1748
void removeObjCLifetime()
Definition: Type.h:336
DiagnosticsEngine & Diags
Definition: Sema.h:322
bool isEnumeralType() const
Definition: Type.h:6359
static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr, QualType DstType, SourceRange OpRange)
Diagnose casts that change the calling convention of a pointer to a function defined in the current T...
Definition: SemaCast.cpp:1842
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6716
void clear()
Clear the base-paths results.
CastAwayConstnessKind
The kind of unwrapping we did when determining whether a conversion casts away constness.
Definition: SemaCast.cpp:455
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:2671
bool isInvalidDecl() const
Definition: DeclBase.h:542
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1226
Defines the clang::Expr interface and subclasses for C++ expressions.
The collection of all-type qualifiers we support.
Definition: Type.h:141
bool isRecordingPaths() const
Whether we are recording paths.
bool UnwrapSimilarTypes(QualType &T1, QualType &T2)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
Expr * FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
Represents a struct/union/class.
Definition: Decl.h:3602
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
void setRecordingPaths(bool RP)
Specify whether we should be recording paths or not.
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:132
(Type)expr
Definition: SemaCast.cpp:51
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:286
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3935
The cast method is not applicable.
Definition: SemaCast.cpp:34
A C-style cast.
Definition: Sema.h:9374
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3783
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
TryCastResult
Definition: SemaCast.cpp:33
static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK, unsigned &DiagID)
Definition: SemaCast.cpp:655
void removeConst()
Definition: Type.h:262
bool isReferenceType() const
Definition: Type.h:6294
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible...
Definition: Sema.h:9754
Expr * getSubExpr()
Definition: Expr.h:2997
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:6212
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6630
OverloadCandidateDisplayKind
Definition: Overload.h:66
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
bool isInvalidType() const
Definition: DeclSpec.h:2426
bool isGLValue() const
Definition: Expr.h:252
static bool isValidCast(TryCastResult TCR)
Definition: SemaCast.cpp:42
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1648
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2744
PtrTy get() const
Definition: Ownership.h:174
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
Succeeded, but refers to a deleted function.
Definition: Overload.h:63
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:9760
OverloadCandidateSet & getFailedCandidateSet()
Retrieve a reference to the candidate set when overload resolution fails.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
const Type * getClass() const
Definition: Type.h:2796
bool isRValueReferenceType() const
Definition: Type.h:6302
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:9370
static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind)
Definition: SemaCast.cpp:1983
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:7273
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6058
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2932
static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr, QualType DestType)
DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either const, volatile or both...
Definition: SemaCast.cpp:2700
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang&#39;s AST.
const LangOptions & getLangOpts() const
Definition: Sema.h:1225
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:641
bool isScalarType() const
Definition: Type.h:6615
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:507
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:5969
static CastAwayConstnessKind unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2)
Unwrap one level of types for CastsAwayConstness.
Definition: SemaCast.cpp:482
bool hasConst() const
Definition: Type.h:258
bool isHalfType() const
Definition: Type.h:6536
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
A functional-style cast.
Definition: Sema.h:9376
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:486
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:481
CastKind
CastKind - The kind of operation required for a conversion.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1798
bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2)
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, bool CStyle, unsigned &msg)
TryConstCast - See if a const_cast from source to destination is allowed, and perform it if it is...
Definition: SemaCast.cpp:1670
bool isEnabled(llvm::StringRef Ext) const
Definition: OpenCLOptions.h:39
unsigned Offset
Definition: Format.cpp:1631
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:39
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:136
bool isEventT() const
Definition: Type.h:6440
This represents one expression.
Definition: Expr.h:106
static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType, SourceRange opRange, Expr *src, QualType destType, bool listInitialization)
Diagnose a failed cast.
Definition: SemaCast.cpp:413
QualType getPointeeType() const
Definition: Type.h:2700
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
static InitializationKind CreateFunctionalCast(SourceRange TypeRange, bool InitList)
Create a direct initialization for a functional cast.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2628
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to...
Definition: Type.cpp:1598
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6779
OverloadingResult getFailedOverloadResult() const
Get the overloading result, for when the initialization sequence failed due to a bad overload...
The cast method is appropriate and accepted as a language extension.
Definition: SemaCast.cpp:36
Defines the clang::Preprocessor interface.
bool isNullPtrType() const
Definition: Type.h:6555
static CXXStaticCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:553
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:769
Overload resolution succeeded.
Definition: Overload.h:54
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:258
Stores token information for comparing actual tokens with predefined values.
Definition: Preprocessor.h:86
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:16696
static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, Sema::CheckedConversionKind CCK, SourceRange OpRange, unsigned &msg, CastKind &Kind, bool ListInitialization)
TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2 is valid: ...
Definition: SemaCast.cpp:1615
bool isConstructorInitialization() const
Determine whether this initialization is direct call to a constructor.
Definition: SemaInit.cpp:3338
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition: Sema.h:9751
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7586
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1844
QualType getType() const
Definition: Expr.h:128
static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath)
TryStaticMemberPointerUpcast - Tests whether a conversion according to C++ 5.2.9p9 is valid: ...
Definition: SemaCast.cpp:1497
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConverion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
Type(expr)
Definition: SemaCast.cpp:52
bool isAtLeastAsQualifiedAs(CanQual< T > Other) const
Determines whether this canonical type is at least as qualified as the Other canonical type...
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
Preprocessor & getPreprocessor() const
Definition: Sema.h:1231
Represents a GCC generic vector type.
Definition: Type.h:3174
static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath)
Tests whether a conversion according to C++ 5.2.9p5 is valid.
Definition: SemaCast.cpp:1313
bool isUsable() const
Definition: Ownership.h:171
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind)
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1395
The result type of a method or function.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:236
bool isKeyword(const LangOptions &LangOpts) const
Return true if this token is a keyword in the specified language.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:301
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6091
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:2736
bool isVoidPointerType() const
Definition: Type.cpp:469
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector...
Definition: SemaExpr.cpp:6206
RecordDecl * getDecl() const
Definition: Type.h:4366
static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType, bool CStyle, SourceRange OpRange, QualType OrigSrcType, QualType OrigDestType, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath)
TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and TryStaticPointerDowncast.
Definition: SemaCast.cpp:1385
CanQualType OverloadTy
Definition: ASTContext.h:1044
static CXXConstCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:672
Kind
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2564
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
ASTContext & getASTContext() const
Definition: Sema.h:1232
Encodes a location in the source.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4382
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:5954
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6174
static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType, bool CStyle, SourceRange OpRange, unsigned &msg, CastKind &Kind, CXXCastPath &BasePath)
Tests whether a conversion according to C++ 5.2.9p8 is valid.
Definition: SemaCast.cpp:1351
static const FieldDecl * getTargetFieldForToUnionCast(QualType unionType, QualType opType)
Definition: Expr.cpp:1778
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1759
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
paths_iterator begin()
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc)
ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast&#39;s.
Definition: SemaCast.cpp:235
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Represents a canonical, potentially-qualified type.
Definition: CanonicalType.h:66
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
Describes the kind of initialization being performed, along with location information for tokens rela...
const_cast
Definition: SemaCast.cpp:47
bool isMemberFunctionPointerType() const
Definition: Type.h:6317
bool isObjCObjectPointerType() const
Definition: Type.h:6379
bool isAnyPointerType() const
Definition: Type.h:6286
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3066
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:249
Overloading for initialization by constructor failed.
is AltiVec vector
Definition: Type.h:3181
Requests that all candidates be shown.
Definition: Overload.h:69
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1823
bool isVectorType() const
Definition: Type.h:6367
void removeObjCGCAttr()
Definition: Type.h:313
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:837
reinterpret_cast
Definition: SemaCast.cpp:49
static InitializationKind CreateCast(SourceRange TypeRange)
Create a direct initialization due to a cast that isn&#39;t a C-style or functional cast.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2292
static CXXReinterpretCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:645
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed...
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:16604
A POD class for pairing a NamedDecl* with an access specifier.
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6504
dynamic_cast
Definition: SemaCast.cpp:50
Represents an element in a path from a derived class to a base class.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
std::list< CXXBasePath >::const_iterator const_paths_iterator
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:1773
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
The cast method is appropriate, but failed.
Definition: SemaCast.cpp:38
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:975
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
bool isBooleanType() const
Definition: Type.h:6643
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6261
static void checkIntToPointerCast(bool CStyle, SourceLocation Loc, const Expr *SrcExpr, QualType DestType, Sema &Self)
Definition: SemaCast.cpp:1930
Requests that only viable candidates be shown.
Definition: Overload.h:72
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2762
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr, QualType DestType)
Definition: SemaCast.cpp:1823
static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType, ExprResult &Result)
Definition: SemaCast.cpp:1956
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2655
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression&#39;s result is syntactically ignored, perform any conversions that are required.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:151
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4356
static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT, SourceRange range, Expr *src, QualType destType, bool listInitialization)
Try to diagnose a failed overloaded cast.
Definition: SemaCast.cpp:337
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6564
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:6294
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:1823
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isFunctionType() const
Definition: Type.h:6278
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7231
CXXBasePath & front()
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2679
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2268
static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType, bool CStyle, CastKind &Kind, CXXCastPath &BasePath, unsigned &msg)
Tests whether a conversion according to N2844 is valid.
Definition: SemaCast.cpp:1255
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2806
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:129
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2069
bool isObjCObjectType() const
Definition: Type.h:6383
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:834
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2252
bool isLValueReferenceType() const
Definition: Type.h:6298
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:2762
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:238
bool Failed() const
Determine whether the initialization sequence is invalid.
CallingConv getCallConv() const
Definition: Type.h:3627
Describes the sequence of initializations required to initialize a given object or reference with a s...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6138
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition: Type.h:2786
bool isVoidType() const
Definition: Type.h:6530
static CastAwayConstnessKind CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType, bool CheckCVR, bool CheckObjCLifetime, QualType *TheOffendingSrcType=nullptr, QualType *TheOffendingDestType=nullptr, Qualifiers *CastAwayQualifiers=nullptr)
Check if the pointer conversion from SrcType to DestType casts away constness as defined in C++ [expr...
Definition: SemaCast.cpp:560
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6085
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2397
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
Defines the clang::TargetInfo interface.
bool isComplexIntegerType() const
Definition: Type.cpp:487
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
unsigned getCVRQualifiers() const
Definition: Type.h:280
ExprResult ExprError()
Definition: Ownership.h:283
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:234
bool hasVolatile() const
Definition: Type.h:265
static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr, QualType DestType)
DiagnoseBadFunctionCast - Warn whenever a function call is cast to a non-matching type...
Definition: SemaCast.cpp:2443
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2085
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1042
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:816
bool isUnion() const
Definition: Decl.h:3261
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:2683
bool isPointerType() const
Definition: Type.h:6282
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
No viable function found.
Definition: Overload.h:57
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:2822
bool isFloatingType() const
Definition: Type.cpp:1921
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:320
paths_iterator end()
APSInt & getInt()
Definition: APValue.h:252
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:6306
SourceLocation getBegin() const
const LangOptions & getLangOpts() const
Definition: ASTContext.h:706
void NoteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr *> Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1867
CastType
Definition: SemaCast.cpp:46
QualType getPointeeType() const
Definition: Type.h:2782
static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr, QualType DestType, SourceRange OpRange)
Check that a reinterpret_cast<DestType>(SrcExpr) is not used as upcast or downcast between respective...
Definition: SemaCast.cpp:851
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:125