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