1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for cast expressions, including
10 //  1) C-style casts like '(int) x'
11 //  2) C++ functional casts like 'int(x)'
12 //  3) C++ named casts like 'static_cast<int>(x)'
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/Sema/SemaInternal.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Sema/Initialization.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include <set>
29 using namespace clang;
30 
31 
32 
33 enum TryCastResult {
34   TC_NotApplicable, ///< The cast method is not applicable.
35   TC_Success,       ///< The cast method is appropriate and successful.
36   TC_Extension,     ///< The cast method is appropriate and accepted as a
37                     ///< language extension.
38   TC_Failed         ///< The cast method is appropriate, but failed. A
39                     ///< diagnostic has been emitted.
40 };
41 
isValidCast(TryCastResult TCR)42 static bool isValidCast(TryCastResult TCR) {
43   return TCR == TC_Success || TCR == TC_Extension;
44 }
45 
46 enum CastType {
47   CT_Const,       ///< const_cast
48   CT_Static,      ///< static_cast
49   CT_Reinterpret, ///< reinterpret_cast
50   CT_Dynamic,     ///< dynamic_cast
51   CT_CStyle,      ///< (Type)expr
52   CT_Functional,  ///< Type(expr)
53   CT_Addrspace    ///< addrspace_cast
54 };
55 
56 namespace {
57   struct CastOperation {
CastOperation__anon8d89a18e0111::CastOperation58     CastOperation(Sema &S, QualType destType, ExprResult src)
59       : Self(S), SrcExpr(src), DestType(destType),
60         ResultType(destType.getNonLValueExprType(S.Context)),
61         ValueKind(Expr::getValueKindForType(destType)),
62         Kind(CK_Dependent), IsARCUnbridgedCast(false) {
63 
64       if (const BuiltinType *placeholder =
65             src.get()->getType()->getAsPlaceholderType()) {
66         PlaceholderKind = placeholder->getKind();
67       } else {
68         PlaceholderKind = (BuiltinType::Kind) 0;
69       }
70     }
71 
72     Sema &Self;
73     ExprResult SrcExpr;
74     QualType DestType;
75     QualType ResultType;
76     ExprValueKind ValueKind;
77     CastKind Kind;
78     BuiltinType::Kind PlaceholderKind;
79     CXXCastPath BasePath;
80     bool IsARCUnbridgedCast;
81     bool IsCheriFromCap = false;
82     bool IsCheriAddrOffset = false;
83 
84     SourceRange OpRange;
85     SourceRange DestRange;
86 
87     // Top-level semantics-checking routines.
88     void CheckConstCast();
89     void CheckReinterpretCast();
90     void CheckStaticCast();
91     void CheckDynamicCast();
92     void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
93     void CheckCStyleCast();
94     void CheckCheriCast();
95     void CheckCapabilityConversions();
96     void CheckBuiltinBitCast();
97     void CheckAddrspaceCast();
98 
updatePartOfExplicitCastFlags__anon8d89a18e0111::CastOperation99     void updatePartOfExplicitCastFlags(CastExpr *CE) {
100       // Walk down from the CE to the OrigSrcExpr, and mark all immediate
101       // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
102       // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
103       for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
104         ICE->setIsPartOfExplicitCast(true);
105     }
106 
107     /// Complete an apparently-successful cast operation that yields
108     /// the given expression.
complete__anon8d89a18e0111::CastOperation109     ExprResult complete(CastExpr *castExpr) {
110       if (!isa<CXXConstructExpr>(SrcExpr.get())) {
111         CastKind CK = checkCapabilityToIntCast();
112         // Make sure that the types actually match:
113         if (CK == CK_CHERICapabilityToPointer && DestType->isReferenceType()) {
114           // return ExprError();
115         }
116       }
117       const QualType CastTy = castExpr->getType();
118 #ifndef NDEBUG
119       if (CastTy->isIntCapType()) {
120         assert(CastTy == CastExpr::provenanceCheckedTy(
121                              CastTy, Self.Context, castExpr->getSubExpr()) &&
122                "checkProvenance not called?");
123       }
124 #endif
125       // For C-style casts from uintptr_t -> void* flag the void* argument
126       // as not carrying provenance if the source type does not carry provenance
127       // exclude intcap_t in this check here since those cases are handled
128       // implicitly by *CastExpr::Create.
129       // We have to special-case the pointer type instead of being able to
130       // include it in the ::Create checks since we need a non-const ASTContext&
131       if (CastTy->isCHERICapabilityType(Self.Context,
132                                         /*IncludeIntCap=*/false)) {
133         const QualType ExprTy = castExpr->getSubExpr()->getType();
134         // Casts from integer pointer->capability pointer can result in a tagged
135         // value in in hybrid mode.
136         bool ExprCanCarryProvenance =
137             ExprTy->isCHERICapabilityType(Self.Context) ||
138             ExprTy->isPointerType();
139         // If the source type does not carry provenance, the result can't
140         // either.
141         if (ExprTy->hasAttr(attr::CHERINoProvenance))
142           ExprCanCarryProvenance = false;
143         if (!CastTy->hasAttr(attr::CHERINoProvenance) &&
144             !ExprCanCarryProvenance) {
145           castExpr->setType(Self.Context.getAttributedType(
146                                 attr::CHERINoProvenance, CastTy, CastTy),
147                             /* ProvenanceChecked=*/true);
148         }
149       }
150 
151       // If this is an unbridged cast, wrap the result in an implicit
152       // cast that yields the unbridged-cast placeholder type.
153       if (IsARCUnbridgedCast) {
154         castExpr = ImplicitCastExpr::Create(Self.Context,
155                                             Self.Context.ARCUnbridgedCastTy,
156                                             CK_Dependent, castExpr, nullptr,
157                                             castExpr->getValueKind());
158       }
159       updatePartOfExplicitCastFlags(castExpr);
160       return castExpr;
161     }
162 
163     // Internal convenience methods.
164 
165     /// Try to handle the given placeholder expression kind.  Return
166     /// true if the source expression has the appropriate placeholder
167     /// kind.  A placeholder can only be claimed once.
claimPlaceholder__anon8d89a18e0111::CastOperation168     bool claimPlaceholder(BuiltinType::Kind K) {
169       if (PlaceholderKind != K) return false;
170 
171       PlaceholderKind = (BuiltinType::Kind) 0;
172       return true;
173     }
174 
isPlaceholder__anon8d89a18e0111::CastOperation175     bool isPlaceholder() const {
176       return PlaceholderKind != 0;
177     }
isPlaceholder__anon8d89a18e0111::CastOperation178     bool isPlaceholder(BuiltinType::Kind K) const {
179       return PlaceholderKind == K;
180     }
181 
182     // Language specific cast restrictions for address spaces.
183     void checkAddressSpaceCast(QualType SrcType, QualType DestType);
184 
185     // Warn about not using __cheri_fromcap/__cheri_tocap
186     CastKind checkCapabilityToIntCast();
187 
checkCastAlign__anon8d89a18e0111::CastOperation188     void checkCastAlign() {
189       Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
190     }
191 
checkObjCConversion__anon8d89a18e0111::CastOperation192     void checkObjCConversion(Sema::CheckedConversionKind CCK) {
193       assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
194 
195       Expr *src = SrcExpr.get();
196       if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
197           Sema::ACR_unbridged)
198         IsARCUnbridgedCast = true;
199       SrcExpr = src;
200     }
201 
202     /// Check for and handle non-overload placeholder expressions.
checkNonOverloadPlaceholders__anon8d89a18e0111::CastOperation203     void checkNonOverloadPlaceholders() {
204       if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
205         return;
206 
207       SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
208       if (SrcExpr.isInvalid())
209         return;
210       PlaceholderKind = (BuiltinType::Kind) 0;
211     }
212   };
213 
CheckNoDeref(Sema & S,const QualType FromType,const QualType ToType,SourceLocation OpLoc)214   void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,
215                     SourceLocation OpLoc) {
216     if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {
217       if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
218         if (const auto *DestType = dyn_cast<PointerType>(ToType)) {
219           if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) {
220             S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer);
221           }
222         }
223       }
224     }
225   }
226 
227   struct CheckNoDerefRAII {
CheckNoDerefRAII__anon8d89a18e0111::CheckNoDerefRAII228     CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
~CheckNoDerefRAII__anon8d89a18e0111::CheckNoDerefRAII229     ~CheckNoDerefRAII() {
230       if (!Op.SrcExpr.isInvalid())
231         CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,
232                      Op.OpRange.getBegin());
233     }
234 
235     CastOperation &Op;
236   };
237 }
238 
239 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
240                              QualType DestType);
241 
242 // The Try functions attempt a specific way of casting. If they succeed, they
243 // return TC_Success. If their way of casting is not appropriate for the given
244 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
245 // to emit if no other way succeeds. If their way of casting is appropriate but
246 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
247 // they emit a specialized diagnostic.
248 // All diagnostics returned by these functions must expect the same three
249 // arguments:
250 // %0: Cast Type (a value from the CastType enumeration)
251 // %1: Source Type
252 // %2: Destination Type
253 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
254                                            QualType DestType, bool CStyle,
255                                            CastKind &Kind,
256                                            CXXCastPath &BasePath,
257                                            unsigned &msg);
258 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
259                                                QualType DestType, bool CStyle,
260                                                SourceRange OpRange,
261                                                unsigned &msg,
262                                                CastKind &Kind,
263                                                CXXCastPath &BasePath);
264 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
265                                               QualType DestType, bool CStyle,
266                                               SourceRange OpRange,
267                                               unsigned &msg,
268                                               CastKind &Kind,
269                                               CXXCastPath &BasePath);
270 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
271                                        CanQualType DestType, bool CStyle,
272                                        SourceRange OpRange,
273                                        QualType OrigSrcType,
274                                        QualType OrigDestType, unsigned &msg,
275                                        CastKind &Kind,
276                                        CXXCastPath &BasePath);
277 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
278                                                QualType SrcType,
279                                                QualType DestType,bool CStyle,
280                                                SourceRange OpRange,
281                                                unsigned &msg,
282                                                CastKind &Kind,
283                                                CXXCastPath &BasePath);
284 
285 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
286                                            QualType DestType,
287                                            Sema::CheckedConversionKind CCK,
288                                            SourceRange OpRange,
289                                            unsigned &msg, CastKind &Kind,
290                                            bool ListInitialization);
291 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
292                                    QualType DestType,
293                                    Sema::CheckedConversionKind CCK,
294                                    SourceRange OpRange,
295                                    unsigned &msg, CastKind &Kind,
296                                    CXXCastPath &BasePath,
297                                    bool ListInitialization);
298 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
299                                   QualType DestType, bool CStyle,
300                                   unsigned &msg);
301 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
302                                         QualType DestType, bool CStyle,
303                                         SourceRange OpRange, unsigned &msg,
304                                         CastKind &Kind);
305 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
306                                          QualType DestType, bool CStyle,
307                                          unsigned &msg, CastKind &Kind);
308 
309 /// ActOnCXXNamedCast - Parse
310 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
311 ExprResult
ActOnCXXNamedCast(SourceLocation OpLoc,tok::TokenKind Kind,SourceLocation LAngleBracketLoc,Declarator & D,SourceLocation RAngleBracketLoc,SourceLocation LParenLoc,Expr * E,SourceLocation RParenLoc)312 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
313                         SourceLocation LAngleBracketLoc, Declarator &D,
314                         SourceLocation RAngleBracketLoc,
315                         SourceLocation LParenLoc, Expr *E,
316                         SourceLocation RParenLoc) {
317 
318   assert(!D.isInvalidType());
319 
320   TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
321   if (D.isInvalidType())
322     return ExprError();
323 
324   if (getLangOpts().CPlusPlus) {
325     // Check that there are no default arguments (C++ only).
326     CheckExtraCXXDefaultArguments(D);
327   }
328 
329   return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
330                            SourceRange(LAngleBracketLoc, RAngleBracketLoc),
331                            SourceRange(LParenLoc, RParenLoc));
332 }
333 
334 ExprResult
BuildCXXNamedCast(SourceLocation OpLoc,tok::TokenKind Kind,TypeSourceInfo * DestTInfo,Expr * E,SourceRange AngleBrackets,SourceRange Parens)335 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
336                         TypeSourceInfo *DestTInfo, Expr *E,
337                         SourceRange AngleBrackets, SourceRange Parens) {
338   ExprResult Ex = E;
339   QualType DestType = DestTInfo->getType();
340 
341   // If the type is dependent, we won't do the semantic analysis now.
342   bool TypeDependent =
343       DestType->isDependentType() || Ex.get()->isTypeDependent();
344 
345   CastOperation Op(*this, DestType, E);
346   Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
347   Op.DestRange = AngleBrackets;
348 
349   switch (Kind) {
350   default: llvm_unreachable("Unknown C++ cast!");
351 
352   case tok::kw_addrspace_cast:
353     if (!TypeDependent) {
354       Op.CheckAddrspaceCast();
355       if (Op.SrcExpr.isInvalid())
356         return ExprError();
357     }
358     return Op.complete(CXXAddrspaceCastExpr::Create(
359         Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
360         DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));
361 
362   case tok::kw_const_cast:
363     if (!TypeDependent) {
364       Op.CheckConstCast();
365       if (Op.SrcExpr.isInvalid())
366         return ExprError();
367       DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
368       Op.Kind = CK_NoOp;
369     }
370     return Op.complete(CXXConstCastExpr::Create(
371         Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
372         DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));
373 
374   case tok::kw_dynamic_cast: {
375     // dynamic_cast is not supported in C++ for OpenCL.
376     if (getLangOpts().OpenCLCPlusPlus) {
377       return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
378                        << "dynamic_cast");
379     }
380 
381     if (!TypeDependent) {
382       Op.CheckDynamicCast();
383       if (Op.SrcExpr.isInvalid())
384         return ExprError();
385     }
386     return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
387                                     Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
388                                                   &Op.BasePath, DestTInfo,
389                                                   OpLoc, Parens.getEnd(),
390                                                   AngleBrackets));
391   }
392   case tok::kw_reinterpret_cast: {
393     if (!TypeDependent) {
394       Op.CheckReinterpretCast();
395       if (Op.SrcExpr.isInvalid())
396         return ExprError();
397       DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
398     }
399     return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
400                                     Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
401                                                       nullptr, DestTInfo, OpLoc,
402                                                       Parens.getEnd(),
403                                                       AngleBrackets));
404   }
405   case tok::kw_static_cast: {
406     if (!TypeDependent) {
407       Op.CheckStaticCast();
408       if (Op.SrcExpr.isInvalid())
409         return ExprError();
410       DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
411     }
412 
413     return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
414                                    Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
415                                                  &Op.BasePath, DestTInfo,
416                                                  OpLoc, Parens.getEnd(),
417                                                  AngleBrackets));
418   }
419   }
420 }
421 
ActOnBuiltinBitCastExpr(SourceLocation KWLoc,Declarator & D,ExprResult Operand,SourceLocation RParenLoc)422 ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
423                                          ExprResult Operand,
424                                          SourceLocation RParenLoc) {
425   assert(!D.isInvalidType());
426 
427   TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
428   if (D.isInvalidType())
429     return ExprError();
430 
431   return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
432 }
433 
BuildBuiltinBitCastExpr(SourceLocation KWLoc,TypeSourceInfo * TSI,Expr * Operand,SourceLocation RParenLoc)434 ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
435                                          TypeSourceInfo *TSI, Expr *Operand,
436                                          SourceLocation RParenLoc) {
437   CastOperation Op(*this, TSI->getType(), Operand);
438   Op.OpRange = SourceRange(KWLoc, RParenLoc);
439   TypeLoc TL = TSI->getTypeLoc();
440   Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
441 
442   if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
443     Op.CheckBuiltinBitCast();
444     if (Op.SrcExpr.isInvalid())
445       return ExprError();
446   }
447 
448   BuiltinBitCastExpr *BCE = new (Context)
449       BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
450                          TSI, KWLoc, RParenLoc, Context);
451   return Op.complete(BCE);
452 }
453 
454 /// Try to diagnose a failed overloaded cast.  Returns true if
455 /// diagnostics were emitted.
tryDiagnoseOverloadedCast(Sema & S,CastType CT,SourceRange range,Expr * src,QualType destType,bool listInitialization)456 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
457                                       SourceRange range, Expr *src,
458                                       QualType destType,
459                                       bool listInitialization) {
460   switch (CT) {
461   // These cast kinds don't consider user-defined conversions.
462   case CT_Const:
463   case CT_Reinterpret:
464   case CT_Dynamic:
465   case CT_Addrspace:
466     return false;
467 
468   // These do.
469   case CT_Static:
470   case CT_CStyle:
471   case CT_Functional:
472     break;
473   }
474 
475   QualType srcType = src->getType();
476   if (!destType->isRecordType() && !srcType->isRecordType())
477     return false;
478 
479   InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
480   InitializationKind initKind
481     = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
482                                                       range, listInitialization)
483     : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
484                                                              listInitialization)
485     : InitializationKind::CreateCast(/*type range?*/ range);
486   InitializationSequence sequence(S, entity, initKind, src);
487 
488   assert(sequence.Failed() && "initialization succeeded on second try?");
489   switch (sequence.getFailureKind()) {
490   default: return false;
491 
492   case InitializationSequence::FK_ConstructorOverloadFailed:
493   case InitializationSequence::FK_UserConversionOverloadFailed:
494     break;
495   }
496 
497   OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
498 
499   unsigned msg = 0;
500   OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
501 
502   switch (sequence.getFailedOverloadResult()) {
503   case OR_Success: llvm_unreachable("successful failed overload");
504   case OR_No_Viable_Function:
505     if (candidates.empty())
506       msg = diag::err_ovl_no_conversion_in_cast;
507     else
508       msg = diag::err_ovl_no_viable_conversion_in_cast;
509     howManyCandidates = OCD_AllCandidates;
510     break;
511 
512   case OR_Ambiguous:
513     msg = diag::err_ovl_ambiguous_conversion_in_cast;
514     howManyCandidates = OCD_AmbiguousCandidates;
515     break;
516 
517   case OR_Deleted:
518     msg = diag::err_ovl_deleted_conversion_in_cast;
519     howManyCandidates = OCD_ViableCandidates;
520     break;
521   }
522 
523   candidates.NoteCandidates(
524       PartialDiagnosticAt(range.getBegin(),
525                           S.PDiag(msg) << CT << srcType << destType << range
526                                        << src->getSourceRange()),
527       S, howManyCandidates, src);
528 
529   return true;
530 }
531 
532 /// Diagnose a failed cast.
diagnoseBadCast(Sema & S,unsigned msg,CastType castType,SourceRange opRange,Expr * src,QualType destType,bool listInitialization)533 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
534                             SourceRange opRange, Expr *src, QualType destType,
535                             bool listInitialization) {
536   if (msg == diag::err_bad_cxx_cast_generic &&
537       tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
538                                 listInitialization))
539     return;
540 
541   S.Diag(opRange.getBegin(), msg) << castType
542     << src->getType() << destType << opRange << src->getSourceRange();
543 
544   // Detect if both types are (ptr to) class, and note any incompleteness.
545   int DifferentPtrness = 0;
546   QualType From = destType;
547   if (auto Ptr = From->getAs<PointerType>()) {
548     From = Ptr->getPointeeType();
549     DifferentPtrness++;
550   }
551   QualType To = src->getType();
552   if (auto Ptr = To->getAs<PointerType>()) {
553     To = Ptr->getPointeeType();
554     DifferentPtrness--;
555   }
556   if (!DifferentPtrness) {
557     auto RecFrom = From->getAs<RecordType>();
558     auto RecTo = To->getAs<RecordType>();
559     if (RecFrom && RecTo) {
560       auto DeclFrom = RecFrom->getAsCXXRecordDecl();
561       if (!DeclFrom->isCompleteDefinition())
562         S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
563           << DeclFrom->getDeclName();
564       auto DeclTo = RecTo->getAsCXXRecordDecl();
565       if (!DeclTo->isCompleteDefinition())
566         S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
567           << DeclTo->getDeclName();
568     }
569   }
570 }
571 
572 namespace {
573 /// The kind of unwrapping we did when determining whether a conversion casts
574 /// away constness.
575 enum CastAwayConstnessKind {
576   /// The conversion does not cast away constness.
577   CACK_None = 0,
578   /// We unwrapped similar types.
579   CACK_Similar = 1,
580   /// We unwrapped dissimilar types with similar representations (eg, a pointer
581   /// versus an Objective-C object pointer).
582   CACK_SimilarKind = 2,
583   /// We unwrapped representationally-unrelated types, such as a pointer versus
584   /// a pointer-to-member.
585   CACK_Incoherent = 3,
586 };
587 }
588 
589 /// Unwrap one level of types for CastsAwayConstness.
590 ///
591 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
592 /// both types, provided that they're both pointer-like or array-like. Unlike
593 /// the Sema function, doesn't care if the unwrapped pieces are related.
594 ///
595 /// This function may remove additional levels as necessary for correctness:
596 /// the resulting T1 is unwrapped sufficiently that it is never an array type,
597 /// so that its qualifiers can be directly compared to those of T2 (which will
598 /// have the combined set of qualifiers from all indermediate levels of T2),
599 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
600 /// with those from T2.
601 static CastAwayConstnessKind
unwrapCastAwayConstnessLevel(ASTContext & Context,QualType & T1,QualType & T2)602 unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
603   enum { None, Ptr, MemPtr, BlockPtr, Array };
604   auto Classify = [](QualType T) {
605     if (T->isAnyPointerType()) return Ptr;
606     if (T->isMemberPointerType()) return MemPtr;
607     if (T->isBlockPointerType()) return BlockPtr;
608     // We somewhat-arbitrarily don't look through VLA types here. This is at
609     // least consistent with the behavior of UnwrapSimilarTypes.
610     if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
611     return None;
612   };
613 
614   auto Unwrap = [&](QualType T) {
615     if (auto *AT = Context.getAsArrayType(T))
616       return AT->getElementType();
617     return T->getPointeeType();
618   };
619 
620   CastAwayConstnessKind Kind;
621 
622   if (T2->isReferenceType()) {
623     // Special case: if the destination type is a reference type, unwrap it as
624     // the first level. (The source will have been an lvalue expression in this
625     // case, so there is no corresponding "reference to" in T1 to remove.) This
626     // simulates removing a "pointer to" from both sides.
627     T2 = T2->getPointeeType();
628     Kind = CastAwayConstnessKind::CACK_Similar;
629   } else if (Context.UnwrapSimilarTypes(T1, T2)) {
630     Kind = CastAwayConstnessKind::CACK_Similar;
631   } else {
632     // Try unwrapping mismatching levels.
633     int T1Class = Classify(T1);
634     if (T1Class == None)
635       return CastAwayConstnessKind::CACK_None;
636 
637     int T2Class = Classify(T2);
638     if (T2Class == None)
639       return CastAwayConstnessKind::CACK_None;
640 
641     T1 = Unwrap(T1);
642     T2 = Unwrap(T2);
643     Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
644                               : CastAwayConstnessKind::CACK_Incoherent;
645   }
646 
647   // We've unwrapped at least one level. If the resulting T1 is a (possibly
648   // multidimensional) array type, any qualifier on any matching layer of
649   // T2 is considered to correspond to T1. Decompose down to the element
650   // type of T1 so that we can compare properly.
651   while (true) {
652     Context.UnwrapSimilarArrayTypes(T1, T2);
653 
654     if (Classify(T1) != Array)
655       break;
656 
657     auto T2Class = Classify(T2);
658     if (T2Class == None)
659       break;
660 
661     if (T2Class != Array)
662       Kind = CastAwayConstnessKind::CACK_Incoherent;
663     else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
664       Kind = CastAwayConstnessKind::CACK_SimilarKind;
665 
666     T1 = Unwrap(T1);
667     T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
668   }
669 
670   return Kind;
671 }
672 
673 /// Check if the pointer conversion from SrcType to DestType casts away
674 /// constness as defined in C++ [expr.const.cast]. This is used by the cast
675 /// checkers. Both arguments must denote pointer (possibly to member) types.
676 ///
677 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
678 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
679 static CastAwayConstnessKind
CastsAwayConstness(Sema & Self,QualType SrcType,QualType DestType,bool CheckCVR,bool CheckObjCLifetime,QualType * TheOffendingSrcType=nullptr,QualType * TheOffendingDestType=nullptr,Qualifiers * CastAwayQualifiers=nullptr)680 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
681                    bool CheckCVR, bool CheckObjCLifetime,
682                    QualType *TheOffendingSrcType = nullptr,
683                    QualType *TheOffendingDestType = nullptr,
684                    Qualifiers *CastAwayQualifiers = nullptr) {
685   // If the only checking we care about is for Objective-C lifetime qualifiers,
686   // and we're not in ObjC mode, there's nothing to check.
687   if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
688     return CastAwayConstnessKind::CACK_None;
689 
690   if (!DestType->isReferenceType()) {
691     assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
692             SrcType->isBlockPointerType()) &&
693            "Source type is not pointer or pointer to member.");
694     assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
695             DestType->isBlockPointerType()) &&
696            "Destination type is not pointer or pointer to member.");
697   }
698 
699   QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
700            UnwrappedDestType = Self.Context.getCanonicalType(DestType);
701 
702   // Find the qualifiers. We only care about cvr-qualifiers for the
703   // purpose of this check, because other qualifiers (address spaces,
704   // Objective-C GC, etc.) are part of the type's identity.
705   QualType PrevUnwrappedSrcType = UnwrappedSrcType;
706   QualType PrevUnwrappedDestType = UnwrappedDestType;
707   auto WorstKind = CastAwayConstnessKind::CACK_Similar;
708   bool AllConstSoFar = true;
709   while (auto Kind = unwrapCastAwayConstnessLevel(
710              Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
711     // Track the worst kind of unwrap we needed to do before we found a
712     // problem.
713     if (Kind > WorstKind)
714       WorstKind = Kind;
715 
716     // Determine the relevant qualifiers at this level.
717     Qualifiers SrcQuals, DestQuals;
718     Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
719     Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
720 
721     // We do not meaningfully track object const-ness of Objective-C object
722     // types. Remove const from the source type if either the source or
723     // the destination is an Objective-C object type.
724     if (UnwrappedSrcType->isObjCObjectType() ||
725         UnwrappedDestType->isObjCObjectType())
726       SrcQuals.removeConst();
727 
728     if (CheckCVR) {
729       Qualifiers SrcCvrQuals =
730           Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
731       Qualifiers DestCvrQuals =
732           Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
733 
734       if (SrcCvrQuals != DestCvrQuals) {
735         if (CastAwayQualifiers)
736           *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
737 
738         // If we removed a cvr-qualifier, this is casting away 'constness'.
739         if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
740           if (TheOffendingSrcType)
741             *TheOffendingSrcType = PrevUnwrappedSrcType;
742           if (TheOffendingDestType)
743             *TheOffendingDestType = PrevUnwrappedDestType;
744           return WorstKind;
745         }
746 
747         // If any prior level was not 'const', this is also casting away
748         // 'constness'. We noted the outermost type missing a 'const' already.
749         if (!AllConstSoFar)
750           return WorstKind;
751       }
752     }
753 
754     if (CheckObjCLifetime &&
755         !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
756       return WorstKind;
757 
758     // If we found our first non-const-qualified type, this may be the place
759     // where things start to go wrong.
760     if (AllConstSoFar && !DestQuals.hasConst()) {
761       AllConstSoFar = false;
762       if (TheOffendingSrcType)
763         *TheOffendingSrcType = PrevUnwrappedSrcType;
764       if (TheOffendingDestType)
765         *TheOffendingDestType = PrevUnwrappedDestType;
766     }
767 
768     PrevUnwrappedSrcType = UnwrappedSrcType;
769     PrevUnwrappedDestType = UnwrappedDestType;
770   }
771 
772   return CastAwayConstnessKind::CACK_None;
773 }
774 
getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,unsigned & DiagID)775 static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
776                                                   unsigned &DiagID) {
777   switch (CACK) {
778   case CastAwayConstnessKind::CACK_None:
779     llvm_unreachable("did not cast away constness");
780 
781   case CastAwayConstnessKind::CACK_Similar:
782     // FIXME: Accept these as an extension too?
783   case CastAwayConstnessKind::CACK_SimilarKind:
784     DiagID = diag::err_bad_cxx_cast_qualifiers_away;
785     return TC_Failed;
786 
787   case CastAwayConstnessKind::CACK_Incoherent:
788     DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
789     return TC_Extension;
790   }
791 
792   llvm_unreachable("unexpected cast away constness kind");
793 }
794 
IsBadCheriReferenceCast(const ReferenceType * Dest,Expr * SrcExpr,ASTContext & Ctx)795 static bool IsBadCheriReferenceCast(const ReferenceType *Dest, Expr *SrcExpr,
796                                     ASTContext &Ctx) {
797   bool SrcIsCapRef = Ctx.getTargetInfo().areAllPointersCapabilities();
798   if (auto SrcRef = SrcExpr->getRealReferenceType(Ctx)->getAs<ReferenceType>())
799     SrcIsCapRef = SrcRef->isCHERICapability();
800   return Dest->isCHERICapability() != SrcIsCapRef;
801 }
802 
803 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
804 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
805 /// checked downcasts in class hierarchies.
CheckDynamicCast()806 void CastOperation::CheckDynamicCast() {
807   CheckNoDerefRAII NoderefCheck(*this);
808 
809   if (ValueKind == VK_RValue)
810     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
811   else if (isPlaceholder())
812     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
813   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
814     return;
815 
816   QualType OrigSrcType = SrcExpr.get()->getType();
817   QualType DestType = Self.Context.getCanonicalType(this->DestType);
818 
819   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
820   //   or "pointer to cv void".
821 
822   QualType DestPointee;
823   const PointerType *DestPointer = DestType->getAs<PointerType>();
824   const ReferenceType *DestReference = nullptr;
825   if (DestPointer) {
826     DestPointee = DestPointer->getPointeeType();
827   } else if ((DestReference = DestType->getAs<ReferenceType>())) {
828     DestPointee = DestReference->getPointeeType();
829   } else {
830     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
831         << this->DestType << DestRange;
832     SrcExpr = ExprError();
833     return;
834   }
835 
836   const RecordType *DestRecord = DestPointee->getAs<RecordType>();
837   if (DestPointee->isVoidType()) {
838     assert(DestPointer && "Reference to void is not possible");
839   } else if (DestRecord) {
840     if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
841                                  diag::err_bad_cast_incomplete,
842                                  DestRange)) {
843       SrcExpr = ExprError();
844       return;
845     }
846   } else {
847     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
848       << DestPointee.getUnqualifiedType() << DestRange;
849     SrcExpr = ExprError();
850     return;
851   }
852 
853   // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
854   //   complete class type, [...]. If T is an lvalue reference type, v shall be
855   //   an lvalue of a complete class type, [...]. If T is an rvalue reference
856   //   type, v shall be an expression having a complete class type, [...]
857   QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
858   QualType SrcPointee;
859   if (DestPointer) {
860     if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
861       SrcPointee = SrcPointer->getPointeeType();
862     } else {
863       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
864           << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();
865       SrcExpr = ExprError();
866       return;
867     }
868   } else if (DestReference->isLValueReferenceType()) {
869     if (!SrcExpr.get()->isLValue()) {
870       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
871         << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
872     }
873     SrcPointee = SrcType;
874   } else {
875     // If we're dynamic_casting from a prvalue to an rvalue reference, we need
876     // to materialize the prvalue before we bind the reference to it.
877     if (SrcExpr.get()->isRValue())
878       SrcExpr = Self.CreateMaterializeTemporaryExpr(
879           SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
880     SrcPointee = SrcType;
881   }
882 
883   const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
884   if (SrcRecord) {
885     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
886                                  diag::err_bad_cast_incomplete,
887                                  SrcExpr.get())) {
888       SrcExpr = ExprError();
889       return;
890     }
891   } else {
892     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
893       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
894     SrcExpr = ExprError();
895     return;
896   }
897 
898   assert((DestPointer || DestReference) &&
899     "Bad destination non-ptr/ref slipped through.");
900   assert((DestRecord || DestPointee->isVoidType()) &&
901     "Bad destination pointee slipped through.");
902   assert(SrcRecord && "Bad source pointee slipped through.");
903 
904   // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
905   if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
906     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
907       << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
908     SrcExpr = ExprError();
909     return;
910   }
911 
912   // Check that the dynamic cast doesn't change the capability qualifier
913   if (DestReference && IsBadCheriReferenceCast(DestReference, SrcExpr.get(),
914                                                Self.getASTContext())) {
915     Self.Diag(OpRange.getBegin(),
916               diag::err_bad_cxx_reference_cast_capability_qualifier)
917         << CT_Dynamic << 0 << DestType;
918     SrcExpr = ExprError();
919     return;
920   }
921   if (!DestReference && SrcType->isCHERICapabilityType(Self.Context) !=
922                             DestType->isCHERICapabilityType(Self.Context)) {
923     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_capability_qualifier)
924         << CT_Dynamic << SrcType << DestType;
925     SrcExpr = ExprError();
926     return;
927   }
928 
929   // C++ 5.2.7p3: If the type of v is the same as the required result type,
930   //   [except for cv].
931   if (DestRecord == SrcRecord) {
932     Kind = CK_NoOp;
933     return;
934   }
935 
936   // C++ 5.2.7p5
937   // Upcasts are resolved statically.
938   if (DestRecord &&
939       Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
940     if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
941                                            OpRange.getBegin(), OpRange,
942                                            &BasePath)) {
943       SrcExpr = ExprError();
944       return;
945     }
946 
947     Kind = CK_DerivedToBase;
948     return;
949   }
950 
951   // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
952   const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
953   assert(SrcDecl && "Definition missing");
954   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
955     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
956       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
957     SrcExpr = ExprError();
958   }
959 
960   // dynamic_cast is not available with -fno-rtti.
961   // As an exception, dynamic_cast to void* is available because it doesn't
962   // use RTTI.
963   if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
964     Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
965     SrcExpr = ExprError();
966     return;
967   }
968 
969   // Done. Everything else is run-time checks.
970   Kind = CK_Dynamic;
971 }
972 
973 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
974 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
975 /// like this:
976 /// const char *str = "literal";
977 /// legacy_function(const_cast\<char*\>(str));
CheckConstCast()978 void CastOperation::CheckConstCast() {
979   CheckNoDerefRAII NoderefCheck(*this);
980 
981   if (ValueKind == VK_RValue)
982     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
983   else if (isPlaceholder())
984     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
985   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
986     return;
987 
988   unsigned msg = diag::err_bad_cxx_cast_generic;
989   auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
990   if (TCR != TC_Success && msg != 0) {
991     Self.Diag(OpRange.getBegin(), msg) << CT_Const
992       << SrcExpr.get()->getType() << DestType << OpRange;
993   }
994   if (!isValidCast(TCR))
995     SrcExpr = ExprError();
996 }
997 
CheckAddrspaceCast()998 void CastOperation::CheckAddrspaceCast() {
999   unsigned msg = diag::err_bad_cxx_cast_generic;
1000   auto TCR =
1001       TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);
1002   if (TCR != TC_Success && msg != 0) {
1003     Self.Diag(OpRange.getBegin(), msg)
1004         << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;
1005   }
1006   if (!isValidCast(TCR))
1007     SrcExpr = ExprError();
1008 }
1009 
1010 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
1011 /// or downcast between respective pointers or references.
DiagnoseReinterpretUpDownCast(Sema & Self,const Expr * SrcExpr,QualType DestType,SourceRange OpRange)1012 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
1013                                           QualType DestType,
1014                                           SourceRange OpRange) {
1015   QualType SrcType = SrcExpr->getType();
1016   // When casting from pointer or reference, get pointee type; use original
1017   // type otherwise.
1018   const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
1019   const CXXRecordDecl *SrcRD =
1020     SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
1021 
1022   // Examining subobjects for records is only possible if the complete and
1023   // valid definition is available.  Also, template instantiation is not
1024   // allowed here.
1025   if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
1026     return;
1027 
1028   const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
1029 
1030   if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
1031     return;
1032 
1033   enum {
1034     ReinterpretUpcast,
1035     ReinterpretDowncast
1036   } ReinterpretKind;
1037 
1038   CXXBasePaths BasePaths;
1039 
1040   if (SrcRD->isDerivedFrom(DestRD, BasePaths))
1041     ReinterpretKind = ReinterpretUpcast;
1042   else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
1043     ReinterpretKind = ReinterpretDowncast;
1044   else
1045     return;
1046 
1047   bool VirtualBase = true;
1048   bool NonZeroOffset = false;
1049   for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
1050                                           E = BasePaths.end();
1051        I != E; ++I) {
1052     const CXXBasePath &Path = *I;
1053     CharUnits Offset = CharUnits::Zero();
1054     bool IsVirtual = false;
1055     for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
1056          IElem != EElem; ++IElem) {
1057       IsVirtual = IElem->Base->isVirtual();
1058       if (IsVirtual)
1059         break;
1060       const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
1061       assert(BaseRD && "Base type should be a valid unqualified class type");
1062       // Don't check if any base has invalid declaration or has no definition
1063       // since it has no layout info.
1064       const CXXRecordDecl *Class = IElem->Class,
1065                           *ClassDefinition = Class->getDefinition();
1066       if (Class->isInvalidDecl() || !ClassDefinition ||
1067           !ClassDefinition->isCompleteDefinition())
1068         return;
1069 
1070       const ASTRecordLayout &DerivedLayout =
1071           Self.Context.getASTRecordLayout(Class);
1072       Offset += DerivedLayout.getBaseClassOffset(BaseRD);
1073     }
1074     if (!IsVirtual) {
1075       // Don't warn if any path is a non-virtually derived base at offset zero.
1076       if (Offset.isZero())
1077         return;
1078       // Offset makes sense only for non-virtual bases.
1079       else
1080         NonZeroOffset = true;
1081     }
1082     VirtualBase = VirtualBase && IsVirtual;
1083   }
1084 
1085   (void) NonZeroOffset; // Silence set but not used warning.
1086   assert((VirtualBase || NonZeroOffset) &&
1087          "Should have returned if has non-virtual base with zero offset");
1088 
1089   QualType BaseType =
1090       ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
1091   QualType DerivedType =
1092       ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
1093 
1094   SourceLocation BeginLoc = OpRange.getBegin();
1095   Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
1096     << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
1097     << OpRange;
1098   Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
1099     << int(ReinterpretKind)
1100     << FixItHint::CreateReplacement(BeginLoc, "static_cast");
1101 }
1102 
1103 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
1104 /// valid.
1105 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
1106 /// like this:
1107 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
CheckReinterpretCast()1108 void CastOperation::CheckReinterpretCast() {
1109   if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
1110     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1111   else
1112     checkNonOverloadPlaceholders();
1113   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1114     return;
1115 
1116   unsigned msg = diag::err_bad_cxx_cast_generic;
1117   TryCastResult tcr =
1118     TryReinterpretCast(Self, SrcExpr, DestType,
1119                        /*CStyle*/false, OpRange, msg, Kind);
1120   if (tcr != TC_Success && msg != 0) {
1121     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1122       return;
1123     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1124       //FIXME: &f<int>; is overloaded and resolvable
1125       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
1126         << OverloadExpr::find(SrcExpr.get()).Expression->getName()
1127         << DestType << OpRange;
1128       Self.NoteAllOverloadCandidates(SrcExpr.get());
1129 
1130     } else {
1131       diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
1132                       DestType, /*listInitialization=*/false);
1133     }
1134   }
1135 
1136   if (isValidCast(tcr)) {
1137     if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1138       checkObjCConversion(Sema::CCK_OtherCast);
1139     DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
1140   } else {
1141     SrcExpr = ExprError();
1142   }
1143   // Check that we don't incorrectly convert T* <-> T* __capability
1144   CheckCapabilityConversions();
1145 }
1146 
1147 
1148 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1149 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1150 /// implicit conversions explicit and getting rid of data loss warnings.
CheckStaticCast()1151 void CastOperation::CheckStaticCast() {
1152   CheckNoDerefRAII NoderefCheck(*this);
1153 
1154   if (isPlaceholder()) {
1155     checkNonOverloadPlaceholders();
1156     if (SrcExpr.isInvalid())
1157       return;
1158   }
1159 
1160   // This test is outside everything else because it's the only case where
1161   // a non-lvalue-reference target type does not lead to decay.
1162   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1163   if (DestType->isVoidType()) {
1164     Kind = CK_ToVoid;
1165 
1166     if (claimPlaceholder(BuiltinType::Overload)) {
1167       Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1168                 false, // Decay Function to ptr
1169                 true, // Complain
1170                 OpRange, DestType, diag::err_bad_static_cast_overload);
1171       if (SrcExpr.isInvalid())
1172         return;
1173     }
1174 
1175     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
1176     return;
1177   }
1178 
1179   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1180       !isPlaceholder(BuiltinType::Overload)) {
1181     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1182     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1183       return;
1184   }
1185 
1186   unsigned msg = diag::err_bad_cxx_cast_generic;
1187   TryCastResult tcr
1188     = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
1189                     Kind, BasePath, /*ListInitialization=*/false);
1190   if (tcr != TC_Success && msg != 0) {
1191     if (SrcExpr.isInvalid())
1192       return;
1193     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1194       OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
1195       Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
1196         << oe->getName() << DestType << OpRange
1197         << oe->getQualifierLoc().getSourceRange();
1198       Self.NoteAllOverloadCandidates(SrcExpr.get());
1199     } else {
1200       diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1201                       /*listInitialization=*/false);
1202     }
1203   }
1204 
1205   if (isValidCast(tcr)) {
1206     if (Kind == CK_BitCast)
1207       checkCastAlign();
1208     if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1209       checkObjCConversion(Sema::CCK_OtherCast);
1210   } else {
1211     SrcExpr = ExprError();
1212   }
1213 }
1214 
IsAddressSpaceConversion(QualType SrcType,QualType DestType)1215 static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1216   auto *SrcPtrType = SrcType->getAs<PointerType>();
1217   if (!SrcPtrType)
1218     return false;
1219   auto *DestPtrType = DestType->getAs<PointerType>();
1220   if (!DestPtrType)
1221     return false;
1222   return SrcPtrType->getPointeeType().getAddressSpace() !=
1223          DestPtrType->getPointeeType().getAddressSpace();
1224 }
1225 
1226 /// TryStaticCast - Check if a static cast can be performed, and do so if
1227 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1228 /// and casting away constness.
TryStaticCast(Sema & Self,ExprResult & SrcExpr,QualType DestType,Sema::CheckedConversionKind CCK,SourceRange OpRange,unsigned & msg,CastKind & Kind,CXXCastPath & BasePath,bool ListInitialization)1229 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
1230                                    QualType DestType,
1231                                    Sema::CheckedConversionKind CCK,
1232                                    SourceRange OpRange, unsigned &msg,
1233                                    CastKind &Kind, CXXCastPath &BasePath,
1234                                    bool ListInitialization) {
1235   // Determine whether we have the semantics of a C-style cast.
1236   bool CStyle
1237     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1238 
1239   // The order the tests is not entirely arbitrary. There is one conversion
1240   // that can be handled in two different ways. Given:
1241   // struct A {};
1242   // struct B : public A {
1243   //   B(); B(const A&);
1244   // };
1245   // const A &a = B();
1246   // the cast static_cast<const B&>(a) could be seen as either a static
1247   // reference downcast, or an explicit invocation of the user-defined
1248   // conversion using B's conversion constructor.
1249   // DR 427 specifies that the downcast is to be applied here.
1250 
1251   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1252   // Done outside this function.
1253 
1254   TryCastResult tcr;
1255 
1256   // C++ 5.2.9p5, reference downcast.
1257   // See the function for details.
1258   // DR 427 specifies that this is to be applied before paragraph 2.
1259   tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1260                                    OpRange, msg, Kind, BasePath);
1261   if (tcr != TC_NotApplicable)
1262     return tcr;
1263 
1264   // C++11 [expr.static.cast]p3:
1265   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1266   //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1267   tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
1268                               BasePath, msg);
1269   if (tcr != TC_NotApplicable)
1270     return tcr;
1271 
1272   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1273   //   [...] if the declaration "T t(e);" is well-formed, [...].
1274   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1275                               Kind, ListInitialization);
1276   if (SrcExpr.isInvalid())
1277     return TC_Failed;
1278   if (tcr != TC_NotApplicable)
1279     return tcr;
1280 
1281   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1282   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1283   // conversions, subject to further restrictions.
1284   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1285   // of qualification conversions impossible.
1286   // In the CStyle case, the earlier attempt to const_cast should have taken
1287   // care of reverse qualification conversions.
1288 
1289   QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1290 
1291   // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1292   // converted to an integral type. [...] A value of a scoped enumeration type
1293   // can also be explicitly converted to a floating-point type [...].
1294   if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1295     if (Enum->getDecl()->isScoped()) {
1296       if (DestType->isBooleanType()) {
1297         Kind = CK_IntegralToBoolean;
1298         return TC_Success;
1299       } else if (DestType->isIntegralType(Self.Context)) {
1300         Kind = CK_IntegralCast;
1301         return TC_Success;
1302       } else if (DestType->isRealFloatingType()) {
1303         Kind = CK_IntegralToFloating;
1304         return TC_Success;
1305       }
1306     }
1307   }
1308 
1309   // Reverse integral promotion/conversion. All such conversions are themselves
1310   // again integral promotions or conversions and are thus already handled by
1311   // p2 (TryDirectInitialization above).
1312   // (Note: any data loss warnings should be suppressed.)
1313   // The exception is the reverse of enum->integer, i.e. integer->enum (and
1314   // enum->enum). See also C++ 5.2.9p7.
1315   // The same goes for reverse floating point promotion/conversion and
1316   // floating-integral conversions. Again, only floating->enum is relevant.
1317   if (DestType->isEnumeralType()) {
1318     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1319                                  diag::err_bad_cast_incomplete)) {
1320       SrcExpr = ExprError();
1321       return TC_Failed;
1322     }
1323     if (SrcType->isIntegralOrEnumerationType()) {
1324       Kind = CK_IntegralCast;
1325       return TC_Success;
1326     } else if (SrcType->isRealFloatingType())   {
1327       Kind = CK_FloatingToIntegral;
1328       return TC_Success;
1329     }
1330   }
1331 
1332   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1333   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1334   tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1335                                  Kind, BasePath);
1336   if (tcr != TC_NotApplicable)
1337     return tcr;
1338 
1339   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1340   // conversion. C++ 5.2.9p9 has additional information.
1341   // DR54's access restrictions apply here also.
1342   tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1343                                      OpRange, msg, Kind, BasePath);
1344   if (tcr != TC_NotApplicable)
1345     return tcr;
1346 
1347   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1348   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1349   // just the usual constness stuff.
1350   if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1351     QualType SrcPointee = SrcPointer->getPointeeType();
1352     if (SrcPointer->isCHERICapability() !=
1353         DestType->isCHERICapabilityType(Self.Context)) {
1354       // Changing the capability qualifier is not possible with static_cast.
1355       // Return a more specific message than "is not allowed" for pointer casts.
1356       if (DestType->isAnyPointerType())
1357         msg = diag::err_bad_cxx_cast_capability_qualifier;
1358       return TC_NotApplicable;
1359     }
1360 
1361     if (SrcPointee->isVoidType()) {
1362       if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1363         QualType DestPointee = DestPointer->getPointeeType();
1364         if (DestPointee->isIncompleteOrObjectType()) {
1365           // This is definitely the intended conversion, but it might fail due
1366           // to a qualifier violation. Note that we permit Objective-C lifetime
1367           // and GC qualifier mismatches here.
1368           if (!CStyle) {
1369             Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1370             Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1371             DestPointeeQuals.removeObjCGCAttr();
1372             DestPointeeQuals.removeObjCLifetime();
1373             SrcPointeeQuals.removeObjCGCAttr();
1374             SrcPointeeQuals.removeObjCLifetime();
1375             if (DestPointeeQuals != SrcPointeeQuals &&
1376                 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1377               msg = diag::err_bad_cxx_cast_qualifiers_away;
1378               return TC_Failed;
1379             }
1380           }
1381           Kind = IsAddressSpaceConversion(SrcType, DestType)
1382                      ? CK_AddressSpaceConversion
1383                      : CK_BitCast;
1384           return TC_Success;
1385         }
1386 
1387         // Microsoft permits static_cast from 'pointer-to-void' to
1388         // 'pointer-to-function'.
1389         if (!CStyle && Self.getLangOpts().MSVCCompat &&
1390             DestPointee->isFunctionType()) {
1391           Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1392           Kind = CK_BitCast;
1393           return TC_Success;
1394         }
1395       }
1396       else if (DestType->isObjCObjectPointerType()) {
1397         // allow both c-style cast and static_cast of objective-c pointers as
1398         // they are pervasive.
1399         Kind = CK_CPointerToObjCPointerCast;
1400         return TC_Success;
1401       }
1402       else if (CStyle && DestType->isBlockPointerType()) {
1403         // allow c-style cast of void * to block pointers.
1404         Kind = CK_AnyPointerToBlockPointerCast;
1405         return TC_Success;
1406       }
1407     }
1408   }
1409   // Allow arbitrary objective-c pointer conversion with static casts.
1410   if (SrcType->isObjCObjectPointerType() &&
1411       DestType->isObjCObjectPointerType()) {
1412     Kind = CK_BitCast;
1413     return TC_Success;
1414   }
1415   // Allow ns-pointer to cf-pointer conversion in either direction
1416   // with static casts.
1417   if (!CStyle &&
1418       Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1419     return TC_Success;
1420 
1421   // See if it looks like the user is trying to convert between
1422   // related record types, and select a better diagnostic if so.
1423   if (auto SrcPointer = SrcType->getAs<PointerType>())
1424     if (auto DestPointer = DestType->getAs<PointerType>())
1425       if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1426           DestPointer->getPointeeType()->getAs<RecordType>())
1427        msg = diag::err_bad_cxx_cast_unrelated_class;
1428 
1429   // We tried everything. Everything! Nothing works! :-(
1430   return TC_NotApplicable;
1431 }
1432 
1433 /// Tests whether a conversion according to N2844 is valid.
TryLValueToRValueCast(Sema & Self,Expr * SrcExpr,QualType DestType,bool CStyle,CastKind & Kind,CXXCastPath & BasePath,unsigned & msg)1434 TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1435                                     QualType DestType, bool CStyle,
1436                                     CastKind &Kind, CXXCastPath &BasePath,
1437                                     unsigned &msg) {
1438   // C++11 [expr.static.cast]p3:
1439   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1440   //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1441   const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1442   if (!R)
1443     return TC_NotApplicable;
1444 
1445   if (!SrcExpr->isGLValue())
1446     return TC_NotApplicable;
1447 
1448   // Because we try the reference downcast before this function, from now on
1449   // this is the only cast possibility, so we issue an error if we fail now.
1450   // FIXME: Should allow casting away constness if CStyle.
1451   QualType FromType = SrcExpr->getType();
1452   QualType ToType = R->getPointeeType();
1453   if (CStyle) {
1454     FromType = FromType.getUnqualifiedType();
1455     ToType = ToType.getUnqualifiedType();
1456   }
1457 
1458   Sema::ReferenceConversions RefConv;
1459   Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1460       SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
1461   if (RefResult != Sema::Ref_Compatible) {
1462     if (CStyle || RefResult == Sema::Ref_Incompatible)
1463       return TC_NotApplicable;
1464     // Diagnose types which are reference-related but not compatible here since
1465     // we can provide better diagnostics. In these cases forwarding to
1466     // [expr.static.cast]p4 should never result in a well-formed cast.
1467     msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1468                               : diag::err_bad_rvalue_to_rvalue_cast;
1469     return TC_Failed;
1470   }
1471 
1472   if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
1473     Kind = CK_DerivedToBase;
1474     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1475                        /*DetectVirtual=*/true);
1476     if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
1477                             R->getPointeeType(), Paths))
1478       return TC_NotApplicable;
1479 
1480     Self.BuildBasePathArray(Paths, BasePath);
1481   } else
1482     Kind = CK_NoOp;
1483 
1484   return TC_Success;
1485 }
1486 
1487 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1488 TryCastResult
TryStaticReferenceDowncast(Sema & Self,Expr * SrcExpr,QualType DestType,bool CStyle,SourceRange OpRange,unsigned & msg,CastKind & Kind,CXXCastPath & BasePath)1489 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1490                            bool CStyle, SourceRange OpRange,
1491                            unsigned &msg, CastKind &Kind,
1492                            CXXCastPath &BasePath) {
1493   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1494   //   cast to type "reference to cv2 D", where D is a class derived from B,
1495   //   if a valid standard conversion from "pointer to D" to "pointer to B"
1496   //   exists, cv2 >= cv1, and B is not a virtual base class of D.
1497   // In addition, DR54 clarifies that the base must be accessible in the
1498   // current context. Although the wording of DR54 only applies to the pointer
1499   // variant of this rule, the intent is clearly for it to apply to the this
1500   // conversion as well.
1501 
1502   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1503   if (!DestReference) {
1504     return TC_NotApplicable;
1505   }
1506   bool RValueRef = DestReference->isRValueReferenceType();
1507   if (!RValueRef && !SrcExpr->isLValue()) {
1508     // We know the left side is an lvalue reference, so we can suggest a reason.
1509     msg = diag::err_bad_cxx_cast_rvalue;
1510     return TC_NotApplicable;
1511   }
1512 
1513   QualType DestPointee = DestReference->getPointeeType();
1514 
1515   if (IsBadCheriReferenceCast(DestReference, SrcExpr, Self.getASTContext())) {
1516     msg = diag::err_bad_cxx_reference_cast_capability_qualifier;
1517     return TC_Failed;
1518   }
1519 
1520   // FIXME: If the source is a prvalue, we should issue a warning (because the
1521   // cast always has undefined behavior), and for AST consistency, we should
1522   // materialize a temporary.
1523   return TryStaticDowncast(Self,
1524                            Self.Context.getCanonicalType(SrcExpr->getType()),
1525                            Self.Context.getCanonicalType(DestPointee), CStyle,
1526                            OpRange, SrcExpr->getType(), DestType, msg, Kind,
1527                            BasePath);
1528 }
1529 
1530 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1531 TryCastResult
TryStaticPointerDowncast(Sema & Self,QualType SrcType,QualType DestType,bool CStyle,SourceRange OpRange,unsigned & msg,CastKind & Kind,CXXCastPath & BasePath)1532 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1533                          bool CStyle, SourceRange OpRange,
1534                          unsigned &msg, CastKind &Kind,
1535                          CXXCastPath &BasePath) {
1536   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1537   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
1538   //   is a class derived from B, if a valid standard conversion from "pointer
1539   //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1540   //   class of D.
1541   // In addition, DR54 clarifies that the base must be accessible in the
1542   // current context.
1543 
1544   const PointerType *DestPointer = DestType->getAs<PointerType>();
1545   if (!DestPointer) {
1546     return TC_NotApplicable;
1547   }
1548 
1549   const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1550   if (!SrcPointer) {
1551     msg = diag::err_bad_static_cast_pointer_nonpointer;
1552     return TC_NotApplicable;
1553   }
1554 
1555   return TryStaticDowncast(Self,
1556                    Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1557                   Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1558                            CStyle, OpRange, SrcType, DestType, msg, Kind,
1559                            BasePath);
1560 }
1561 
1562 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1563 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1564 /// DestType is possible and allowed.
1565 TryCastResult
TryStaticDowncast(Sema & Self,CanQualType SrcType,CanQualType DestType,bool CStyle,SourceRange OpRange,QualType OrigSrcType,QualType OrigDestType,unsigned & msg,CastKind & Kind,CXXCastPath & BasePath)1566 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1567                   bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1568                   QualType OrigDestType, unsigned &msg,
1569                   CastKind &Kind, CXXCastPath &BasePath) {
1570   // We can only work with complete types. But don't complain if it doesn't work
1571   if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1572       !Self.isCompleteType(OpRange.getBegin(), DestType))
1573     return TC_NotApplicable;
1574 
1575   // Downcast can only happen in class hierarchies, so we need classes.
1576   if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1577     return TC_NotApplicable;
1578   }
1579 
1580   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1581                      /*DetectVirtual=*/true);
1582   if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1583     return TC_NotApplicable;
1584   }
1585 
1586   // Target type does derive from source type. Now we're serious. If an error
1587   // appears now, it's not ignored.
1588   // This may not be entirely in line with the standard. Take for example:
1589   // struct A {};
1590   // struct B : virtual A {
1591   //   B(A&);
1592   // };
1593   //
1594   // void f()
1595   // {
1596   //   (void)static_cast<const B&>(*((A*)0));
1597   // }
1598   // As far as the standard is concerned, p5 does not apply (A is virtual), so
1599   // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1600   // However, both GCC and Comeau reject this example, and accepting it would
1601   // mean more complex code if we're to preserve the nice error message.
1602   // FIXME: Being 100% compliant here would be nice to have.
1603 
1604   // Must preserve cv, as always, unless we're in C-style mode.
1605   if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1606     msg = diag::err_bad_cxx_cast_qualifiers_away;
1607     return TC_Failed;
1608   }
1609 
1610   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1611     // This code is analoguous to that in CheckDerivedToBaseConversion, except
1612     // that it builds the paths in reverse order.
1613     // To sum up: record all paths to the base and build a nice string from
1614     // them. Use it to spice up the error message.
1615     if (!Paths.isRecordingPaths()) {
1616       Paths.clear();
1617       Paths.setRecordingPaths(true);
1618       Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1619     }
1620     std::string PathDisplayStr;
1621     std::set<unsigned> DisplayedPaths;
1622     for (clang::CXXBasePath &Path : Paths) {
1623       if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1624         // We haven't displayed a path to this particular base
1625         // class subobject yet.
1626         PathDisplayStr += "\n    ";
1627         for (CXXBasePathElement &PE : llvm::reverse(Path))
1628           PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1629         PathDisplayStr += QualType(DestType).getAsString();
1630       }
1631     }
1632 
1633     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1634       << QualType(SrcType).getUnqualifiedType()
1635       << QualType(DestType).getUnqualifiedType()
1636       << PathDisplayStr << OpRange;
1637     msg = 0;
1638     return TC_Failed;
1639   }
1640 
1641   if (Paths.getDetectedVirtual() != nullptr) {
1642     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1643     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1644       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1645     msg = 0;
1646     return TC_Failed;
1647   }
1648 
1649   if (!CStyle) {
1650     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1651                                       SrcType, DestType,
1652                                       Paths.front(),
1653                                 diag::err_downcast_from_inaccessible_base)) {
1654     case Sema::AR_accessible:
1655     case Sema::AR_delayed:     // be optimistic
1656     case Sema::AR_dependent:   // be optimistic
1657       break;
1658 
1659     case Sema::AR_inaccessible:
1660       msg = 0;
1661       return TC_Failed;
1662     }
1663   }
1664 
1665   Self.BuildBasePathArray(Paths, BasePath);
1666   Kind = CK_BaseToDerived;
1667   return TC_Success;
1668 }
1669 
1670 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1671 /// C++ 5.2.9p9 is valid:
1672 ///
1673 ///   An rvalue of type "pointer to member of D of type cv1 T" can be
1674 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
1675 ///   where B is a base class of D [...].
1676 ///
1677 TryCastResult
TryStaticMemberPointerUpcast(Sema & Self,ExprResult & SrcExpr,QualType SrcType,QualType DestType,bool CStyle,SourceRange OpRange,unsigned & msg,CastKind & Kind,CXXCastPath & BasePath)1678 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1679                              QualType DestType, bool CStyle,
1680                              SourceRange OpRange,
1681                              unsigned &msg, CastKind &Kind,
1682                              CXXCastPath &BasePath) {
1683   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1684   if (!DestMemPtr)
1685     return TC_NotApplicable;
1686 
1687   bool WasOverloadedFunction = false;
1688   DeclAccessPair FoundOverload;
1689   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1690     if (FunctionDecl *Fn
1691           = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1692                                                     FoundOverload)) {
1693       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1694       SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1695                       Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1696       WasOverloadedFunction = true;
1697     }
1698   }
1699 
1700   const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1701   if (!SrcMemPtr) {
1702     msg = diag::err_bad_static_cast_member_pointer_nonmp;
1703     return TC_NotApplicable;
1704   }
1705 
1706   // Lock down the inheritance model right now in MS ABI, whether or not the
1707   // pointee types are the same.
1708   if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1709     (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1710     (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1711   }
1712 
1713   // T == T, modulo cv
1714   if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1715                                            DestMemPtr->getPointeeType()))
1716     return TC_NotApplicable;
1717 
1718   // B base of D
1719   QualType SrcClass(SrcMemPtr->getClass(), 0);
1720   QualType DestClass(DestMemPtr->getClass(), 0);
1721   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1722                   /*DetectVirtual=*/true);
1723   if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1724     return TC_NotApplicable;
1725 
1726   // B is a base of D. But is it an allowed base? If not, it's a hard error.
1727   if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1728     Paths.clear();
1729     Paths.setRecordingPaths(true);
1730     bool StillOkay =
1731         Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1732     assert(StillOkay);
1733     (void)StillOkay;
1734     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1735     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1736       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1737     msg = 0;
1738     return TC_Failed;
1739   }
1740 
1741   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1742     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1743       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1744     msg = 0;
1745     return TC_Failed;
1746   }
1747 
1748   if (!CStyle) {
1749     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1750                                       DestClass, SrcClass,
1751                                       Paths.front(),
1752                                       diag::err_upcast_to_inaccessible_base)) {
1753     case Sema::AR_accessible:
1754     case Sema::AR_delayed:
1755     case Sema::AR_dependent:
1756       // Optimistically assume that the delayed and dependent cases
1757       // will work out.
1758       break;
1759 
1760     case Sema::AR_inaccessible:
1761       msg = 0;
1762       return TC_Failed;
1763     }
1764   }
1765 
1766   if (WasOverloadedFunction) {
1767     // Resolve the address of the overloaded function again, this time
1768     // allowing complaints if something goes wrong.
1769     FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1770                                                                DestType,
1771                                                                true,
1772                                                                FoundOverload);
1773     if (!Fn) {
1774       msg = 0;
1775       return TC_Failed;
1776     }
1777 
1778     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1779     if (!SrcExpr.isUsable()) {
1780       msg = 0;
1781       return TC_Failed;
1782     }
1783   }
1784 
1785   Self.BuildBasePathArray(Paths, BasePath);
1786   Kind = CK_DerivedToBaseMemberPointer;
1787   return TC_Success;
1788 }
1789 
1790 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1791 /// is valid:
1792 ///
1793 ///   An expression e can be explicitly converted to a type T using a
1794 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
1795 TryCastResult
TryStaticImplicitCast(Sema & Self,ExprResult & SrcExpr,QualType DestType,Sema::CheckedConversionKind CCK,SourceRange OpRange,unsigned & msg,CastKind & Kind,bool ListInitialization)1796 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1797                       Sema::CheckedConversionKind CCK,
1798                       SourceRange OpRange, unsigned &msg,
1799                       CastKind &Kind, bool ListInitialization) {
1800   if (DestType->isRecordType()) {
1801     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1802                                  diag::err_bad_cast_incomplete) ||
1803         Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1804                                     diag::err_allocation_of_abstract_type)) {
1805       msg = 0;
1806       return TC_Failed;
1807     }
1808   }
1809 
1810   InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1811   InitializationKind InitKind
1812     = (CCK == Sema::CCK_CStyleCast)
1813         ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1814                                                ListInitialization)
1815     : (CCK == Sema::CCK_FunctionalCast)
1816         ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1817     : InitializationKind::CreateCast(OpRange);
1818   Expr *SrcExprRaw = SrcExpr.get();
1819   // FIXME: Per DR242, we should check for an implicit conversion sequence
1820   // or for a constructor that could be invoked by direct-initialization
1821   // here, not for an initialization sequence.
1822   InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1823 
1824   // At this point of CheckStaticCast, if the destination is a reference,
1825   // or the expression is an overload expression this has to work.
1826   // There is no other way that works.
1827   // On the other hand, if we're checking a C-style cast, we've still got
1828   // the reinterpret_cast way.
1829   bool CStyle
1830     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1831   if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1832     return TC_NotApplicable;
1833 
1834   ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1835   if (Result.isInvalid()) {
1836     msg = 0;
1837     return TC_Failed;
1838   }
1839 
1840   if (InitSeq.isConstructorInitialization())
1841     Kind = CK_ConstructorConversion;
1842   else
1843     Kind = CK_NoOp;
1844 
1845   SrcExpr = Result;
1846   return TC_Success;
1847 }
1848 
1849 /// TryConstCast - See if a const_cast from source to destination is allowed,
1850 /// and perform it if it is.
TryConstCast(Sema & Self,ExprResult & SrcExpr,QualType DestType,bool CStyle,unsigned & msg)1851 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1852                                   QualType DestType, bool CStyle,
1853                                   unsigned &msg) {
1854   DestType = Self.Context.getCanonicalType(DestType);
1855   QualType SrcType = SrcExpr.get()->getType();
1856   bool NeedToMaterializeTemporary = false;
1857 
1858   if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1859     // C++11 5.2.11p4:
1860     //   if a pointer to T1 can be explicitly converted to the type "pointer to
1861     //   T2" using a const_cast, then the following conversions can also be
1862     //   made:
1863     //    -- an lvalue of type T1 can be explicitly converted to an lvalue of
1864     //       type T2 using the cast const_cast<T2&>;
1865     //    -- a glvalue of type T1 can be explicitly converted to an xvalue of
1866     //       type T2 using the cast const_cast<T2&&>; and
1867     //    -- if T1 is a class type, a prvalue of type T1 can be explicitly
1868     //       converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1869 
1870     if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1871       // Cannot const_cast non-lvalue to lvalue reference type. But if this
1872       // is C-style, static_cast might find a way, so we simply suggest a
1873       // message and tell the parent to keep searching.
1874       msg = diag::err_bad_cxx_cast_rvalue;
1875       return TC_NotApplicable;
1876     }
1877 
1878     if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1879       if (!SrcType->isRecordType()) {
1880         // Cannot const_cast non-class prvalue to rvalue reference type. But if
1881         // this is C-style, static_cast can do this.
1882         msg = diag::err_bad_cxx_cast_rvalue;
1883         return TC_NotApplicable;
1884       }
1885 
1886       // Materialize the class prvalue so that the const_cast can bind a
1887       // reference to it.
1888       NeedToMaterializeTemporary = true;
1889     }
1890 
1891     // It's not completely clear under the standard whether we can
1892     // const_cast bit-field gl-values.  Doing so would not be
1893     // intrinsically complicated, but for now, we say no for
1894     // consistency with other compilers and await the word of the
1895     // committee.
1896     if (SrcExpr.get()->refersToBitField()) {
1897       msg = diag::err_bad_cxx_cast_bitfield;
1898       return TC_NotApplicable;
1899     }
1900 
1901     if (IsBadCheriReferenceCast(DestTypeTmp, SrcExpr.get(),
1902                                 Self.getASTContext())) {
1903       msg = diag::err_bad_cxx_reference_cast_capability_qualifier;
1904       return TC_NotApplicable;
1905     }
1906 
1907     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1908     SrcType = Self.Context.getPointerType(SrcType);
1909   }
1910 
1911   // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1912   //   the rules for const_cast are the same as those used for pointers.
1913 
1914   if (!DestType->isPointerType() &&
1915       !DestType->isMemberPointerType() &&
1916       !DestType->isObjCObjectPointerType()) {
1917     // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1918     // was a reference type, we converted it to a pointer above.
1919     // The status of rvalue references isn't entirely clear, but it looks like
1920     // conversion to them is simply invalid.
1921     // C++ 5.2.11p3: For two pointer types [...]
1922     if (!CStyle)
1923       msg = diag::err_bad_const_cast_dest;
1924     return TC_NotApplicable;
1925   }
1926   if (DestType->isFunctionPointerType() ||
1927       DestType->isMemberFunctionPointerType()) {
1928     // Cannot cast direct function pointers.
1929     // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1930     // T is the ultimate pointee of source and target type.
1931     if (!CStyle)
1932       msg = diag::err_bad_const_cast_dest;
1933     return TC_NotApplicable;
1934   }
1935 
1936   // C++ [expr.const.cast]p3:
1937   //   "For two similar types T1 and T2, [...]"
1938   //
1939   // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1940   // type qualifiers. (Likewise, we ignore other changes when determining
1941   // whether a cast casts away constness.)
1942   if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
1943     return TC_NotApplicable;
1944 
1945   if (NeedToMaterializeTemporary)
1946     // This is a const_cast from a class prvalue to an rvalue reference type.
1947     // Materialize a temporary to store the result of the conversion.
1948     SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1949                                                   SrcExpr.get(),
1950                                                   /*IsLValueReference*/ false);
1951 
1952   return TC_Success;
1953 }
1954 
1955 // Checks for undefined behavior in reinterpret_cast.
1956 // The cases that is checked for is:
1957 // *reinterpret_cast<T*>(&a)
1958 // reinterpret_cast<T&>(a)
1959 // where accessing 'a' as type 'T' will result in undefined behavior.
CheckCompatibleReinterpretCast(QualType SrcType,QualType DestType,bool IsDereference,SourceRange Range)1960 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1961                                           bool IsDereference,
1962                                           SourceRange Range) {
1963   unsigned DiagID = IsDereference ?
1964                         diag::warn_pointer_indirection_from_incompatible_type :
1965                         diag::warn_undefined_reinterpret_cast;
1966 
1967   if (Diags.isIgnored(DiagID, Range.getBegin()))
1968     return;
1969 
1970   QualType SrcTy, DestTy;
1971   if (IsDereference) {
1972     if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1973       return;
1974     }
1975     SrcTy = SrcType->getPointeeType();
1976     DestTy = DestType->getPointeeType();
1977   } else {
1978     if (!DestType->getAs<ReferenceType>()) {
1979       return;
1980     }
1981     SrcTy = SrcType;
1982     DestTy = DestType->getPointeeType();
1983   }
1984 
1985   // Cast is compatible if the types are the same.
1986   if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1987     return;
1988   }
1989   // or one of the types is a char or void type
1990   if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1991       SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1992     return;
1993   }
1994   // or one of the types is a tag type.
1995   if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1996     return;
1997   }
1998 
1999   // FIXME: Scoped enums?
2000   if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
2001       (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
2002     if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
2003       return;
2004     }
2005   }
2006 
2007   Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
2008 }
2009 
DiagnoseCHERICallback(Sema & Self,SourceLocation Loc,QualType SrcType,QualType DestType)2010 static void DiagnoseCHERICallback(Sema &Self, SourceLocation Loc,
2011                                   QualType SrcType, QualType DestType) {
2012   bool SrcIsCallback = false;
2013   bool DestIsCallback = false;
2014   if (auto SrcPointer = dyn_cast<PointerType>(SrcType))
2015     if (auto SrcFnPTy = SrcPointer->getPointeeType()->getAs<FunctionType>())
2016       if (SrcFnPTy->getCallConv() == CC_CHERICCallback)
2017         SrcIsCallback = true;
2018   if (auto DestPointer = dyn_cast<PointerType>(DestType))
2019     if (auto DestFnPTy = DestPointer->getPointeeType()->getAs<FunctionType>())
2020       if (DestFnPTy->getCallConv() == CC_CHERICCallback)
2021         DestIsCallback = true;
2022   if (SrcIsCallback != DestIsCallback)
2023     Self.Diag(Loc, diag::err_cheri_invalid_callback_cast);
2024 }
2025 
DiagnoseCHERIPtr(Sema & Self,Expr * SrcExpr,QualType DestType,CastKind & Kind,SourceRange & Range)2026 static void DiagnoseCHERIPtr(Sema &Self, Expr *SrcExpr, QualType DestType,
2027                               CastKind &Kind, SourceRange &Range) {
2028   if (Kind != CK_BitCast)
2029     return;
2030 
2031   const PointerType *SrcPtr = SrcExpr->getType()->getAs<PointerType>();
2032   const PointerType *DestPtr = DestType->getAs<PointerType>();
2033   if (SrcPtr && DestPtr && !SrcPtr->isCHERICapability() && !DestPtr->isCHERICapability()) {
2034     QualType SrcPointee = SrcPtr->getPointeeType();
2035     QualType DestPointee = DestPtr->getPointeeType();
2036 
2037     // casts from char * and void * are implicitly allowed
2038     if (SrcPointee->isCharType() || SrcPointee->isVoidType())
2039       return;
2040 
2041     if (!SrcPointee->isCHERICapabilityType(Self.Context, true) &&
2042         DestPointee->isCHERICapabilityType(Self.Context, true)) {
2043       CharUnits SrcAlign = Self.Context.getTypeAlignInChars(SrcPointee);
2044       CharUnits DestAlign = Self.Context.getTypeAlignInChars(DestPointee);
2045 
2046       if (SrcAlign >= DestAlign)
2047         return;
2048 
2049       Self.Diag(Range.getBegin(), diag::err_cheri_ptr_align)
2050         << SrcExpr->getType() << DestType
2051         << static_cast<unsigned>(SrcAlign.getQuantity())
2052         << static_cast<unsigned>(DestAlign.getQuantity())
2053         << Range << SrcExpr->getSourceRange();
2054       Self.Diag(Range.getEnd(), diag::note_cheri_ptr_align_fixit);
2055     }
2056   }
2057 }
2058 
checkCapabilityToIntCast()2059 CastKind CastOperation::checkCapabilityToIntCast() {
2060   if (IsCheriFromCap)
2061     return CK_NoOp; // Already doing a __cheri_fromcap cast, no need to check
2062 
2063   QualType SrcType = SrcExpr.get()->getRealReferenceType(Self.Context);
2064   if (SrcType->isDependentType() || DestType->isDependentType())
2065     return CK_NoOp; // can't diagnose this yet
2066   // If the source is not a capability or a __uintcap_t we can ignore it
2067   if (!SrcType->isCHERICapabilityType(Self.Context, /*IncludeIntCap=*/false)) {
2068     return CK_NoOp; // Not casting from a capability
2069   }
2070   if (DestType->isCHERICapabilityType(Self.Context, /*IncludeIntCap=*/true)) {
2071     return CK_NoOp; // cast from capabilty to capability is fine
2072   }
2073   if (DestType->isVoidType()) {
2074     // casting to void to silence unused variable warnings is fine
2075     return CK_NoOp;
2076   }
2077   if (SrcType->isNullPtrType()) {
2078     return CK_NoOp;
2079   }
2080 
2081   if (DestType->isPointerType() || DestType->isReferenceType()) {
2082     Self.Diag(OpRange.getBegin(), diag::warn_capability_pointer_cast)
2083         << SrcType << DestType << OpRange
2084         << FixItHint::CreateReplacement(OpRange, "__cheri_fromcap " +
2085                                                      DestType.getAsString());
2086     return CK_CHERICapabilityToPointer;
2087 
2088   }
2089   // Also check whether we are casting to a memory_address type and if not warn
2090   // unless we are already using a __cheri_addr/__cheri_offset cast.
2091   if (!IsCheriAddrOffset && DestType->isIntegerType()) {
2092     bool IsMemAddressType = DestType->hasAttr(attr::MemoryAddress);
2093     if (!IsMemAddressType)
2094       Self.Diag(OpRange.getBegin(), diag::warn_capability_integer_cast)
2095           << SrcType << DestType << OpRange;
2096   }
2097   return CK_NoOp;
2098 }
2099 
DiagnoseCastOfObjCSEL(Sema & Self,const ExprResult & SrcExpr,QualType DestType)2100 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
2101                                   QualType DestType) {
2102   QualType SrcType = SrcExpr.get()->getType();
2103   if (Self.Context.hasSameType(SrcType, DestType))
2104     return;
2105   if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
2106     if (SrcPtrTy->isObjCSelType()) {
2107       QualType DT = DestType;
2108       if (isa<PointerType>(DestType))
2109         DT = DestType->getPointeeType();
2110       if (!DT.getUnqualifiedType()->isVoidType())
2111         Self.Diag(SrcExpr.get()->getExprLoc(),
2112                   diag::warn_cast_pointer_from_sel)
2113         << SrcType << DestType << SrcExpr.get()->getSourceRange();
2114     }
2115 }
2116 
2117 /// Diagnose casts that change the calling convention of a pointer to a function
2118 /// defined in the current TU.
DiagnoseCallingConvCast(Sema & Self,const ExprResult & SrcExpr,QualType DstType,SourceRange OpRange)2119 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
2120                                     QualType DstType, SourceRange OpRange) {
2121   // Check if this cast would change the calling convention of a function
2122   // pointer type.
2123   QualType SrcType = SrcExpr.get()->getType();
2124   if (Self.Context.hasSameType(SrcType, DstType) ||
2125       !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
2126     return;
2127   const auto *SrcFTy =
2128       SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2129   const auto *DstFTy =
2130       DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2131   CallingConv SrcCC = SrcFTy->getCallConv();
2132   CallingConv DstCC = DstFTy->getCallConv();
2133   if (SrcCC == DstCC)
2134     return;
2135 
2136   // We have a calling convention cast. Check if the source is a pointer to a
2137   // known, specific function that has already been defined.
2138   Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
2139   if (auto *UO = dyn_cast<UnaryOperator>(Src))
2140     if (UO->getOpcode() == UO_AddrOf)
2141       Src = UO->getSubExpr()->IgnoreParenImpCasts();
2142   auto *DRE = dyn_cast<DeclRefExpr>(Src);
2143   if (!DRE)
2144     return;
2145   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2146   if (!FD)
2147     return;
2148 
2149   // Only warn if we are casting from the default convention to a non-default
2150   // convention. This can happen when the programmer forgot to apply the calling
2151   // convention to the function declaration and then inserted this cast to
2152   // satisfy the type system.
2153   CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
2154       FD->isVariadic(), FD->isCXXInstanceMember());
2155   if (DstCC == DefaultCC || SrcCC != DefaultCC)
2156     return;
2157 
2158   // Diagnose this cast, as it is probably bad.
2159   StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
2160   StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
2161   Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
2162       << SrcCCName << DstCCName << OpRange;
2163 
2164   // The checks above are cheaper than checking if the diagnostic is enabled.
2165   // However, it's worth checking if the warning is enabled before we construct
2166   // a fixit.
2167   if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
2168     return;
2169 
2170   // Try to suggest a fixit to change the calling convention of the function
2171   // whose address was taken. Try to use the latest macro for the convention.
2172   // For example, users probably want to write "WINAPI" instead of "__stdcall"
2173   // to match the Windows header declarations.
2174   SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
2175   Preprocessor &PP = Self.getPreprocessor();
2176   SmallVector<TokenValue, 6> AttrTokens;
2177   SmallString<64> CCAttrText;
2178   llvm::raw_svector_ostream OS(CCAttrText);
2179   if (Self.getLangOpts().MicrosoftExt) {
2180     // __stdcall or __vectorcall
2181     OS << "__" << DstCCName;
2182     IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
2183     AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2184                              ? TokenValue(II->getTokenID())
2185                              : TokenValue(II));
2186   } else {
2187     // __attribute__((stdcall)) or __attribute__((vectorcall))
2188     OS << "__attribute__((" << DstCCName << "))";
2189     AttrTokens.push_back(tok::kw___attribute);
2190     AttrTokens.push_back(tok::l_paren);
2191     AttrTokens.push_back(tok::l_paren);
2192     IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
2193     AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2194                              ? TokenValue(II->getTokenID())
2195                              : TokenValue(II));
2196     AttrTokens.push_back(tok::r_paren);
2197     AttrTokens.push_back(tok::r_paren);
2198   }
2199   StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
2200   if (!AttrSpelling.empty())
2201     CCAttrText = AttrSpelling;
2202   OS << ' ';
2203   Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
2204       << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
2205 }
2206 
checkNonCapToCapCast(const SourceRange & OpRange,const Expr * SrcExpr,const QualType & DestType,Sema & Self,const QualType & SrcType)2207 void checkNonCapToCapCast(const SourceRange &OpRange, const Expr *SrcExpr,
2208                           const QualType &DestType, Sema &Self,
2209                           const QualType &SrcType) {
2210   ASTContext &Ctx = Self.getASTContext();
2211   if (DestType->isCHERICapabilityType(Ctx, true) &&
2212       !SrcType->isCHERICapabilityType(Ctx, true) &&
2213       !SrcExpr->isValueDependent() && !SrcExpr->isTypeDependent()) {
2214     auto IsPurecap = Ctx.getTargetInfo().areAllPointersCapabilities();
2215     bool ShouldWarn;
2216     bool IsIntConstant = SrcExpr->isIntegerConstantExpr(Ctx);
2217     bool StrictMode =
2218         Self.getLangOpts().getCheriIntToCap() == LangOptions::CapInt_Strict;
2219     if (IsPurecap) {
2220       // In purecap mode we warn if the source expression is not a constant
2221       // expression and emit an error if the int->cap conversion mode is strict.
2222       ShouldWarn = StrictMode || !IsIntConstant;
2223     } else {
2224       // Only warn in hybrid mode if we are using strict int->cap conversions.
2225       // No need to warn in hybrid mode (inside a function) since we will
2226       // generate a DDC-relative capability unless we are using the "address"
2227       // conversion mode.
2228       ShouldWarn =
2229           Self.getLangOpts().getCheriIntToCap() == LangOptions::CapInt_Address;
2230     }
2231     if (ShouldWarn) {
2232       auto DiagID = StrictMode ? diag::err_capability_no_provenance
2233                                : diag::warn_capability_no_provenance;
2234       Self.Diag(OpRange.getBegin(), DiagID) << DestType;
2235       // Only suggest the cast via __intcap_t if the value is a constant. If
2236       // not this cause programmers to silence a real problem that should be
2237       // fixed differently.
2238       if (IsIntConstant)
2239         Self.Diag(OpRange.getBegin(), diag::note_capability_no_provenance_fixit)
2240             << !IsPurecap;
2241     }
2242   }
2243 }
2244 
checkIntToPointerCast(bool CStyle,const SourceRange & OpRange,const Expr * SrcExpr,QualType DestType,Sema & Self)2245 static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
2246                                   const Expr *SrcExpr, QualType DestType,
2247                                   Sema &Self) {
2248   QualType SrcType = SrcExpr->getType();
2249   checkNonCapToCapCast(OpRange, SrcExpr, DestType, Self, SrcType);
2250 
2251   // Not warning on reinterpret_cast, boolean, constant expressions, etc
2252   // are not explicit design choices, but consistent with GCC's behavior.
2253   // Feel free to modify them if you've reason/evidence for an alternative.
2254   if (CStyle && SrcType->isIntegralType(Self.Context) &&
2255       !SrcType->isBooleanType() && !SrcType->isEnumeralType() &&
2256       !SrcExpr->isIntegerConstantExpr(Self.Context) &&
2257       Self.Context.getIntRange(DestType) > Self.Context.getIntRange(SrcType)) {
2258     // Separate between casts to void* and non-void* pointers.
2259     // Some APIs use (abuse) void* for something like a user context,
2260     // and often that value is an integer even if it isn't a pointer itself.
2261     // Having a separate warning flag allows users to control the warning
2262     // for their workflow.
2263     unsigned Diag = DestType->isVoidPointerType() ?
2264                       diag::warn_int_to_void_pointer_cast
2265                     : diag::warn_int_to_pointer_cast;
2266     Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2267   }
2268 }
2269 
fixOverloadedReinterpretCastExpr(Sema & Self,QualType DestType,ExprResult & Result)2270 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
2271                                              ExprResult &Result) {
2272   // We can only fix an overloaded reinterpret_cast if
2273   // - it is a template with explicit arguments that resolves to an lvalue
2274   //   unambiguously, or
2275   // - it is the only function in an overload set that may have its address
2276   //   taken.
2277 
2278   Expr *E = Result.get();
2279   // TODO: what if this fails because of DiagnoseUseOfDecl or something
2280   // like it?
2281   if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2282           Result,
2283           Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
2284           ) &&
2285       Result.isUsable())
2286     return true;
2287 
2288   // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2289   // preserves Result.
2290   Result = E;
2291   if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
2292           Result, /*DoFunctionPointerConversion=*/true))
2293     return false;
2294   return Result.isUsable();
2295 }
2296 
TryReinterpretCast(Sema & Self,ExprResult & SrcExpr,QualType DestType,bool CStyle,SourceRange OpRange,unsigned & msg,CastKind & Kind)2297 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
2298                                         QualType DestType, bool CStyle,
2299                                         SourceRange OpRange,
2300                                         unsigned &msg,
2301                                         CastKind &Kind) {
2302   bool IsLValueCast = false;
2303 
2304   DestType = Self.Context.getCanonicalType(DestType);
2305   QualType SrcType = SrcExpr.get()->getType();
2306 
2307   // Is the source an overloaded name? (i.e. &foo)
2308   // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2309   if (SrcType == Self.Context.OverloadTy) {
2310     ExprResult FixedExpr = SrcExpr;
2311     if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
2312       return TC_NotApplicable;
2313 
2314     assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2315     SrcExpr = FixedExpr;
2316     SrcType = SrcExpr.get()->getType();
2317   }
2318 
2319   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2320     if (!SrcExpr.get()->isGLValue()) {
2321       // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2322       // similar comment in const_cast.
2323       msg = diag::err_bad_cxx_cast_rvalue;
2324       return TC_NotApplicable;
2325     }
2326 
2327     if (!CStyle) {
2328       Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2329                                           /*IsDereference=*/false, OpRange);
2330     }
2331 
2332     // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2333     //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
2334     //   built-in & and * operators.
2335 
2336     const char *inappropriate = nullptr;
2337     switch (SrcExpr.get()->getObjectKind()) {
2338     case OK_Ordinary:
2339       break;
2340     case OK_BitField:
2341       msg = diag::err_bad_cxx_cast_bitfield;
2342       return TC_NotApplicable;
2343       // FIXME: Use a specific diagnostic for the rest of these cases.
2344     case OK_VectorComponent: inappropriate = "vector element";      break;
2345     case OK_MatrixComponent:
2346       inappropriate = "matrix element";
2347       break;
2348     case OK_ObjCProperty:    inappropriate = "property expression"; break;
2349     case OK_ObjCSubscript:   inappropriate = "container subscripting expression";
2350                              break;
2351     }
2352     if (inappropriate) {
2353       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2354           << inappropriate << DestType
2355           << OpRange << SrcExpr.get()->getSourceRange();
2356       msg = 0; SrcExpr = ExprError();
2357       return TC_NotApplicable;
2358     }
2359 
2360     if (IsBadCheriReferenceCast(DestTypeTmp, SrcExpr.get(), Self.getASTContext())) {
2361       msg = diag::err_bad_cxx_reference_cast_capability_qualifier;
2362       return TC_Failed;
2363     }
2364 
2365     // This code does this transformation for the checked types.
2366     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2367     SrcType = Self.Context.getPointerType(SrcType);
2368 
2369     IsLValueCast = true;
2370   }
2371 
2372   // Canonicalize source for comparison.
2373   SrcType = Self.Context.getCanonicalType(SrcType);
2374 
2375   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2376                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2377   if (DestMemPtr && SrcMemPtr) {
2378     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2379     //   can be explicitly converted to an rvalue of type "pointer to member
2380     //   of Y of type T2" if T1 and T2 are both function types or both object
2381     //   types.
2382     if (DestMemPtr->isMemberFunctionPointer() !=
2383         SrcMemPtr->isMemberFunctionPointer())
2384       return TC_NotApplicable;
2385 
2386     if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2387       // We need to determine the inheritance model that the class will use if
2388       // haven't yet.
2389       (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2390       (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2391     }
2392 
2393     // Don't allow casting between member pointers of different sizes.
2394     if (Self.Context.getTypeSize(DestMemPtr) !=
2395         Self.Context.getTypeSize(SrcMemPtr)) {
2396       msg = diag::err_bad_cxx_cast_member_pointer_size;
2397       return TC_Failed;
2398     }
2399 
2400     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2401     //   constness.
2402     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2403     // we accept it.
2404     if (auto CACK =
2405             CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2406                                /*CheckObjCLifetime=*/CStyle))
2407       return getCastAwayConstnessCastKind(CACK, msg);
2408 
2409     // A valid member pointer cast.
2410     assert(!IsLValueCast);
2411     Kind = CK_ReinterpretMemberPointer;
2412     return TC_Success;
2413   }
2414 
2415   // See below for the enumeral issue.
2416   if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2417     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2418     //   type large enough to hold it. A value of std::nullptr_t can be
2419     //   converted to an integral type; the conversion has the same meaning
2420     //   and validity as a conversion of (void*)0 to the integral type.
2421     bool SrcIsCap = SrcType->isCHERICapabilityType(Self.Context);
2422     // In purecap ABI casting to uint64_t is fine as we want the pointer range
2423     uint64_t Size = SrcIsCap
2424         ? Self.Context.getTargetInfo().getPointerRangeForCHERICapability()
2425         : Self.Context.getTypeSize(SrcType);
2426     if (Size > Self.Context.getTypeSize(DestType)) {
2427       msg = SrcIsCap ? diag::err_bad_cap_reinterpret_cast_small_int :
2428                        diag::err_bad_reinterpret_cast_small_int;
2429       return TC_Failed;
2430     }
2431     Kind = SrcIsCap && !DestType->isIntCapType() ? CK_CHERICapabilityToAddress
2432                                                  : CK_PointerToIntegral;
2433     return TC_Success;
2434   }
2435 
2436   // Allow reinterpret_casts between vectors of the same size and
2437   // between vectors and integers of the same size.
2438   bool destIsVector = DestType->isVectorType();
2439   bool srcIsVector = SrcType->isVectorType();
2440   if (srcIsVector || destIsVector) {
2441     // The non-vector type, if any, must have integral type.  This is
2442     // the same rule that C vector casts use; note, however, that enum
2443     // types are not integral in C++.
2444     if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2445         (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2446       return TC_NotApplicable;
2447 
2448     // The size we want to consider is eltCount * eltSize.
2449     // That's exactly what the lax-conversion rules will check.
2450     if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2451       Kind = CK_BitCast;
2452       return TC_Success;
2453     }
2454 
2455     // Otherwise, pick a reasonable diagnostic.
2456     if (!destIsVector)
2457       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2458     else if (!srcIsVector)
2459       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2460     else
2461       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2462 
2463     return TC_Failed;
2464   }
2465 
2466   if (SrcType == DestType) {
2467     // C++ 5.2.10p2 has a note that mentions that, subject to all other
2468     // restrictions, a cast to the same type is allowed so long as it does not
2469     // cast away constness. In C++98, the intent was not entirely clear here,
2470     // since all other paragraphs explicitly forbid casts to the same type.
2471     // C++11 clarifies this case with p2.
2472     //
2473     // The only allowed types are: integral, enumeration, pointer, or
2474     // pointer-to-member types.  We also won't restrict Obj-C pointers either.
2475     Kind = CK_NoOp;
2476     TryCastResult Result = TC_NotApplicable;
2477     if (SrcType->isIntegralOrEnumerationType() ||
2478         SrcType->isAnyPointerType() ||
2479         SrcType->isMemberPointerType() ||
2480         SrcType->isBlockPointerType()) {
2481       Result = TC_Success;
2482     }
2483     return Result;
2484   }
2485 
2486   bool destIsPtr = DestType->isAnyPointerType() ||
2487                    DestType->isBlockPointerType();
2488   bool srcIsPtr = SrcType->isAnyPointerType() ||
2489                   SrcType->isBlockPointerType();
2490   if (!destIsPtr && !srcIsPtr) {
2491     // Except for std::nullptr_t->integer and lvalue->reference, which are
2492     // handled above, at least one of the two arguments must be a pointer.
2493     return TC_NotApplicable;
2494   }
2495 
2496   if (DestType->isIntegralType(Self.Context)) {
2497     assert(srcIsPtr && "One type must be a pointer");
2498     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2499     //   type large enough to hold it; except in Microsoft mode, where the
2500     //   integral type size doesn't matter (except we don't allow bool).
2501     bool SrcIsCap = SrcType->isCHERICapabilityType(Self.Context);
2502     // Note: In purecap ABI casting to uint64_t is fine -> use getIntRange().
2503     if ((Self.Context.getIntRange(SrcType) >
2504          Self.Context.getTypeSize(DestType))) {
2505       bool MicrosoftException =
2506           Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
2507       if (MicrosoftException) {
2508         unsigned Diag = SrcType->isVoidPointerType()
2509                             ? diag::warn_void_pointer_to_int_cast
2510                             : diag::warn_pointer_to_int_cast;
2511         Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2512       } else {
2513         msg = SrcIsCap ? diag::err_bad_cap_reinterpret_cast_small_int
2514                        : diag::err_bad_reinterpret_cast_small_int;
2515         return TC_Failed;
2516       }
2517     }
2518     if (SrcIsCap && !DestType->isIntCapType()) {
2519       // Note: In offset mode (size_t)cap_ptr always returns an address and not
2520       // an offset. Changing that behaviour would change offset mode from being
2521       // "mostly compatible" to being "completely incompatible" with existing C
2522       // code. Therefore we shouldn't use the following here:
2523       //   Kind = Self.getLangOpts().cheriUIntCapUsesAddr()
2524       //           ? CK_CHERICapabilityToAddress
2525       //           : CK_CHERICapabilityToOffset;
2526       Kind = CK_CHERICapabilityToAddress;
2527     } else {
2528       Kind = CK_PointerToIntegral;
2529     }
2530     return TC_Success;
2531   }
2532 
2533   if (SrcType->isIntegralOrEnumerationType()) {
2534     assert(destIsPtr && "One type must be a pointer");
2535     checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
2536     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2537     //   converted to a pointer.
2538     // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2539     //   necessarily converted to a null pointer value.]
2540     Kind = CK_IntegralToPointer;
2541     return TC_Success;
2542   }
2543 
2544   if (!destIsPtr || !srcIsPtr) {
2545     // With the valid non-pointer conversions out of the way, we can be even
2546     // more stringent.
2547     return TC_NotApplicable;
2548   }
2549 
2550   // Cannot convert between block pointers and Objective-C object pointers.
2551   if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2552       (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2553     return TC_NotApplicable;
2554 
2555   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2556   // The C-style cast operator can.
2557   TryCastResult SuccessResult = TC_Success;
2558   if (auto CACK =
2559           CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2560                              /*CheckObjCLifetime=*/CStyle))
2561     SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2562 
2563   if (IsAddressSpaceConversion(SrcType, DestType)) {
2564     Kind = CK_AddressSpaceConversion;
2565     assert(SrcType->isPointerType() && DestType->isPointerType());
2566     if (!CStyle &&
2567         !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2568             SrcType->getPointeeType().getQualifiers())) {
2569       SuccessResult = TC_Failed;
2570     }
2571   } else if (IsLValueCast) {
2572     Kind = CK_LValueBitCast;
2573   } else if (DestType->isObjCObjectPointerType()) {
2574     Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2575   } else if (DestType->isBlockPointerType()) {
2576     if (!SrcType->isBlockPointerType()) {
2577       Kind = CK_AnyPointerToBlockPointerCast;
2578     } else {
2579       Kind = CK_BitCast;
2580     }
2581   } else {
2582     bool SrcIsCapPtr = SrcType->isCapabilityPointerType();
2583     bool DestIsCapPtr = DestType->isCapabilityPointerType();
2584     if (!SrcIsCapPtr && DestIsCapPtr) {
2585       checkNonCapToCapCast(OpRange, SrcExpr.get(), DestType, Self, SrcType);
2586       Kind = CK_PointerToCHERICapability;
2587     } else if (SrcIsCapPtr && !DestIsCapPtr) {
2588       Kind = CK_CHERICapabilityToPointer;
2589     } else {
2590       Kind = CK_BitCast;
2591     }
2592   }
2593 
2594   // Any pointer can be cast to an Objective-C pointer type with a C-style
2595   // cast.
2596   if (CStyle && DestType->isObjCObjectPointerType()) {
2597     return SuccessResult;
2598   }
2599   if (CStyle)
2600     DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2601 
2602   DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2603 
2604   // Not casting away constness, so the only remaining check is for compatible
2605   // pointer categories.
2606 
2607   if (SrcType->isFunctionPointerType()) {
2608     if (DestType->isFunctionPointerType()) {
2609       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2610       // a pointer to a function of a different type.
2611       return SuccessResult;
2612     }
2613 
2614     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2615     //   an object type or vice versa is conditionally-supported.
2616     // Compilers support it in C++03 too, though, because it's necessary for
2617     // casting the return value of dlsym() and GetProcAddress().
2618     // FIXME: Conditionally-supported behavior should be configurable in the
2619     // TargetInfo or similar.
2620     Self.Diag(OpRange.getBegin(),
2621               Self.getLangOpts().CPlusPlus11 ?
2622                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2623       << OpRange;
2624     return SuccessResult;
2625   }
2626 
2627   if (DestType->isFunctionPointerType()) {
2628     // See above.
2629     Self.Diag(OpRange.getBegin(),
2630               Self.getLangOpts().CPlusPlus11 ?
2631                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2632       << OpRange;
2633     return SuccessResult;
2634   }
2635 
2636   // Diagnose address space conversion in nested pointers.
2637   QualType DestPtee = DestType->getPointeeType().isNull()
2638                           ? DestType->getPointeeType()
2639                           : DestType->getPointeeType()->getPointeeType();
2640   QualType SrcPtee = SrcType->getPointeeType().isNull()
2641                          ? SrcType->getPointeeType()
2642                          : SrcType->getPointeeType()->getPointeeType();
2643   while (!DestPtee.isNull() && !SrcPtee.isNull()) {
2644     if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2645       Self.Diag(OpRange.getBegin(),
2646                 diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2647           << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2648       break;
2649     }
2650     DestPtee = DestPtee->getPointeeType();
2651     SrcPtee = SrcPtee->getPointeeType();
2652   }
2653 
2654   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2655   //   a pointer to an object of different type.
2656   // Void pointers are not specified, but supported by every compiler out there.
2657   // So we finish by allowing everything that remains - it's got to be two
2658   // object pointers.
2659   return SuccessResult;
2660 }
2661 
TryAddressSpaceCast(Sema & Self,ExprResult & SrcExpr,QualType DestType,bool CStyle,unsigned & msg,CastKind & Kind)2662 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2663                                          QualType DestType, bool CStyle,
2664                                          unsigned &msg, CastKind &Kind) {
2665   if (!Self.getLangOpts().OpenCL)
2666     // FIXME: As compiler doesn't have any information about overlapping addr
2667     // spaces at the moment we have to be permissive here.
2668     return TC_NotApplicable;
2669   // Even though the logic below is general enough and can be applied to
2670   // non-OpenCL mode too, we fast-path above because no other languages
2671   // define overlapping address spaces currently.
2672   auto SrcType = SrcExpr.get()->getType();
2673   // FIXME: Should this be generalized to references? The reference parameter
2674   // however becomes a reference pointee type here and therefore rejected.
2675   // Perhaps this is the right behavior though according to C++.
2676   auto SrcPtrType = SrcType->getAs<PointerType>();
2677   if (!SrcPtrType)
2678     return TC_NotApplicable;
2679   auto DestPtrType = DestType->getAs<PointerType>();
2680   if (!DestPtrType)
2681     return TC_NotApplicable;
2682   auto SrcPointeeType = SrcPtrType->getPointeeType();
2683   auto DestPointeeType = DestPtrType->getPointeeType();
2684   if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
2685     msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2686     return TC_Failed;
2687   }
2688   auto SrcPointeeTypeWithoutAS =
2689       Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2690   auto DestPointeeTypeWithoutAS =
2691       Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2692   if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2693                                DestPointeeTypeWithoutAS)) {
2694     Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2695                ? CK_NoOp
2696                : CK_AddressSpaceConversion;
2697     return TC_Success;
2698   } else {
2699     return TC_NotApplicable;
2700   }
2701 }
2702 
checkAddressSpaceCast(QualType SrcType,QualType DestType)2703 void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2704   // In OpenCL only conversions between pointers to objects in overlapping
2705   // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2706   // with any named one, except for constant.
2707 
2708   // Converting the top level pointee addrspace is permitted for compatible
2709   // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2710   // if any of the nested pointee addrspaces differ, we emit a warning
2711   // regardless of addrspace compatibility. This makes
2712   //   local int ** p;
2713   //   return (generic int **) p;
2714   // warn even though local -> generic is permitted.
2715   if (Self.getLangOpts().OpenCL) {
2716     const Type *DestPtr, *SrcPtr;
2717     bool Nested = false;
2718     unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2719     DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2720     SrcPtr  = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2721 
2722     while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
2723       const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2724       const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2725       QualType DestPPointee = DestPPtr->getPointeeType();
2726       QualType SrcPPointee = SrcPPtr->getPointeeType();
2727       if (Nested
2728               ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
2729               : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
2730         Self.Diag(OpRange.getBegin(), DiagID)
2731             << SrcType << DestType << Sema::AA_Casting
2732             << SrcExpr.get()->getSourceRange();
2733         if (!Nested)
2734           SrcExpr = ExprError();
2735         return;
2736       }
2737 
2738       DestPtr = DestPPtr->getPointeeType().getTypePtr();
2739       SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2740       Nested = true;
2741       DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2742     }
2743   }
2744 }
2745 
CheckCXXCStyleCast(bool FunctionalStyle,bool ListInitialization)2746 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2747                                        bool ListInitialization) {
2748   assert(Self.getLangOpts().CPlusPlus);
2749 
2750   // Handle placeholders.
2751   if (isPlaceholder()) {
2752     // C-style casts can resolve __unknown_any types.
2753     if (claimPlaceholder(BuiltinType::UnknownAny)) {
2754       SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2755                                          SrcExpr.get(), Kind,
2756                                          ValueKind, BasePath);
2757       return;
2758     }
2759 
2760     checkNonOverloadPlaceholders();
2761     if (SrcExpr.isInvalid())
2762       return;
2763   }
2764 
2765   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2766   // This test is outside everything else because it's the only case where
2767   // a non-lvalue-reference target type does not lead to decay.
2768   if (DestType->isVoidType()) {
2769     Kind = CK_ToVoid;
2770 
2771     if (claimPlaceholder(BuiltinType::Overload)) {
2772       Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2773                   SrcExpr, /* Decay Function to ptr */ false,
2774                   /* Complain */ true, DestRange, DestType,
2775                   diag::err_bad_cstyle_cast_overload);
2776       if (SrcExpr.isInvalid())
2777         return;
2778     }
2779 
2780     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2781     return;
2782   }
2783 
2784   // If the type is dependent, we won't do any other semantic analysis now.
2785   if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2786       SrcExpr.get()->isValueDependent()) {
2787     assert(Kind == CK_Dependent);
2788     return;
2789   }
2790 
2791   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2792       !isPlaceholder(BuiltinType::Overload)) {
2793     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2794     if (SrcExpr.isInvalid())
2795       return;
2796   }
2797 
2798   // AltiVec vector initialization with a single literal.
2799   if (const VectorType *vecTy = DestType->getAs<VectorType>())
2800     if (vecTy->getVectorKind() == VectorType::AltiVecVector
2801         && (SrcExpr.get()->getType()->isIntegerType()
2802             || SrcExpr.get()->getType()->isFloatingType())) {
2803       Kind = CK_VectorSplat;
2804       SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2805       return;
2806     }
2807 
2808   // C++ [expr.cast]p5: The conversions performed by
2809   //   - a const_cast,
2810   //   - a static_cast,
2811   //   - a static_cast followed by a const_cast,
2812   //   - a reinterpret_cast, or
2813   //   - a reinterpret_cast followed by a const_cast,
2814   //   can be performed using the cast notation of explicit type conversion.
2815   //   [...] If a conversion can be interpreted in more than one of the ways
2816   //   listed above, the interpretation that appears first in the list is used,
2817   //   even if a cast resulting from that interpretation is ill-formed.
2818   // In plain language, this means trying a const_cast ...
2819   // Note that for address space we check compatibility after const_cast.
2820   unsigned msg = diag::err_bad_cxx_cast_generic;
2821   TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2822                                    /*CStyle*/ true, msg);
2823   if (SrcExpr.isInvalid())
2824     return;
2825   if (isValidCast(tcr))
2826     Kind = CK_NoOp;
2827 
2828   Sema::CheckedConversionKind CCK =
2829       FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
2830   if (tcr == TC_NotApplicable) {
2831     tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2832                               Kind);
2833     if (SrcExpr.isInvalid())
2834       return;
2835 
2836     if (tcr == TC_NotApplicable) {
2837       // ... or if that is not possible, a static_cast, ignoring const and
2838       // addr space, ...
2839       tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2840                           BasePath, ListInitialization);
2841       if (SrcExpr.isInvalid())
2842         return;
2843 
2844       if (tcr == TC_NotApplicable) {
2845         // ... and finally a reinterpret_cast, ignoring const and addr space.
2846         tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2847                                  OpRange, msg, Kind);
2848         if (SrcExpr.isInvalid())
2849           return;
2850       }
2851     }
2852   }
2853 
2854   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2855       isValidCast(tcr))
2856     checkObjCConversion(CCK);
2857 
2858   if (tcr != TC_Success && msg != 0) {
2859     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2860       DeclAccessPair Found;
2861       FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2862                                 DestType,
2863                                 /*Complain*/ true,
2864                                 Found);
2865       if (Fn) {
2866         // If DestType is a function type (not to be confused with the function
2867         // pointer type), it will be possible to resolve the function address,
2868         // but the type cast should be considered as failure.
2869         OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2870         Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2871           << OE->getName() << DestType << OpRange
2872           << OE->getQualifierLoc().getSourceRange();
2873         Self.NoteAllOverloadCandidates(SrcExpr.get());
2874       }
2875     } else {
2876       diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2877                       OpRange, SrcExpr.get(), DestType, ListInitialization);
2878     }
2879   }
2880 
2881   if (isValidCast(tcr)) {
2882     if (Kind == CK_BitCast)
2883       checkCastAlign();
2884   } else {
2885     SrcExpr = ExprError();
2886   }
2887 }
2888 
2889 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2890 ///  non-matching type. Such as enum function call to int, int call to
2891 /// pointer; etc. Cast to 'void' is an exception.
DiagnoseBadFunctionCast(Sema & Self,const ExprResult & SrcExpr,QualType DestType)2892 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2893                                   QualType DestType) {
2894   if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2895                            SrcExpr.get()->getExprLoc()))
2896     return;
2897 
2898   if (!isa<CallExpr>(SrcExpr.get()))
2899     return;
2900 
2901   QualType SrcType = SrcExpr.get()->getType();
2902   if (DestType.getUnqualifiedType()->isVoidType())
2903     return;
2904   if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2905       && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2906     return;
2907   if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2908       (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2909       (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2910     return;
2911   if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2912     return;
2913   if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2914     return;
2915   if (SrcType->isComplexType() && DestType->isComplexType())
2916     return;
2917   if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2918     return;
2919 
2920   Self.Diag(SrcExpr.get()->getExprLoc(),
2921             diag::warn_bad_function_cast)
2922             << SrcType << DestType << SrcExpr.get()->getSourceRange();
2923 }
2924 
2925 /// Check the common semantics of a __cheri_addr/__cheri_offset/
2926 /// __cheri_fromcap/__cheri_tocap cast operation.
2927 /// This also performs the default array-to-pointer, etc coversions
CheckCheriCast()2928 void CastOperation::CheckCheriCast() {
2929   // Perform the default function/array to pointer decay first:
2930   SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2931   if (SrcExpr.isInvalid())
2932     return;
2933   // Cannot cast to an incomplete struct type
2934   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2935                                diag::err_typecheck_cast_to_incomplete)) {
2936     SrcExpr = ExprError();
2937     return;
2938   }
2939 }
2940 
CheckCapabilityConversions()2941 void CastOperation::CheckCapabilityConversions() {
2942   if (SrcExpr.isInvalid())
2943     return; // already invalid -> nothing to check.
2944 
2945   if (Kind == CK_ToVoid || Kind == CK_Dependent || Kind == CK_ToUnion)
2946     return; // Nothing we can/should check for these casts
2947 
2948   auto SrcType = SrcExpr.get()->getType();
2949   bool SrcIsCap =
2950       SrcType->isCHERICapabilityType(Self.Context, /*IncludeIntCap=*/false);
2951   bool DestIsCap =
2952       DestType->isCHERICapabilityType(Self.Context, /*IncludeIntCap=*/false);
2953   // Since references are handled differently, only perform this check if both
2954   // src and dest are references.
2955   if (DestType->isReferenceType() == SrcType->isReferenceType() &&
2956       DestIsCap != SrcIsCap) {
2957     switch (Kind) {
2958     case CK_PointerToCHERICapability:
2959     case CK_CHERICapabilityToPointer:
2960     case CK_CHERICapabilityToAddress:
2961     case CK_CHERICapabilityToOffset:
2962     case CK_IntegralToPointer:
2963     case CK_PointerToIntegral:
2964     case CK_NullToPointer:
2965     case CK_NullToMemberPointer:
2966       break;
2967     default:
2968 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2969       llvm::errs() << "Invalid cast kind: " << CastExpr::getCastKindName(Kind)
2970                    << "\n";
2971       SrcExpr.get()->dump();
2972       SrcExpr.get()->getSourceRange().dump(Self.getSourceManager());
2973       DestType->dump();
2974 #endif
2975       llvm_unreachable("Invalid cap <-> non-cap cast!");
2976     }
2977   }
2978 
2979   if (Kind == CK_PointerToCHERICapability &&
2980       Self.getLangOpts().explicitConversionsToCap()) {
2981     Expr *Placeholder = nullptr;
2982     Self.Diag(
2983         SrcExpr.get()->getBeginLoc(),
2984         Self.CheckCHERIAssignCompatible(SrcType, DestType, Placeholder, false)
2985             ? diag::err_typecheck_convert_ptr_to_cap
2986             : diag::err_typecheck_convert_ptr_to_cap_unrelated_type)
2987         << SrcType << DestType << false
2988         << FixItHint::CreateReplacement(
2989                OpRange, "(__cheri_tocap " + DestType.getAsString() + ")");
2990     SrcExpr = ExprError();
2991     return;
2992   }
2993   if (Kind == CK_CHERICapabilityToPointer &&
2994       Self.getLangOpts().explicitConversionsFromCap()) {
2995     Self.Diag(SrcExpr.get()->getBeginLoc(),
2996               diag::err_typecheck_convert_cap_to_ptr)
2997         << SrcType << DestType << false
2998         << FixItHint::CreateReplacement(
2999                OpRange, "(__cheri_fromcap " + DestType.getAsString() + ")");
3000     SrcExpr = ExprError();
3001     return;
3002   }
3003 }
3004 
CheckCStyleCast()3005 void CastOperation::CheckCStyleCast() {
3006   assert(!Self.getLangOpts().CPlusPlus);
3007 
3008   // C-style casts can resolve __unknown_any types.
3009   if (claimPlaceholder(BuiltinType::UnknownAny)) {
3010     SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
3011                                        SrcExpr.get(), Kind,
3012                                        ValueKind, BasePath);
3013     return;
3014   }
3015 
3016   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3017   // type needs to be scalar.
3018   if (DestType->isVoidType()) {
3019     // We don't necessarily do lvalue-to-rvalue conversions on this.
3020     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
3021     if (SrcExpr.isInvalid())
3022       return;
3023 
3024     // Cast to void allows any expr type.
3025     Kind = CK_ToVoid;
3026     return;
3027   }
3028 
3029   // Overloads are allowed with C extensions, so we need to support them.
3030   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
3031     DeclAccessPair DAP;
3032     if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
3033             SrcExpr.get(), DestType, /*Complain=*/true, DAP))
3034       SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
3035     else
3036       return;
3037     assert(SrcExpr.isUsable());
3038   }
3039   SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
3040   if (SrcExpr.isInvalid())
3041     return;
3042   QualType SrcType = SrcExpr.get()->getType();
3043 
3044   assert(!SrcType->isPlaceholderType());
3045 
3046   checkAddressSpaceCast(SrcType, DestType);
3047   if (SrcExpr.isInvalid())
3048     return;
3049 
3050   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
3051                                diag::err_typecheck_cast_to_incomplete)) {
3052     SrcExpr = ExprError();
3053     return;
3054   }
3055 
3056   // Allow casting a sizeless built-in type to itself.
3057   if (DestType->isSizelessBuiltinType() &&
3058       Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
3059     Kind = CK_NoOp;
3060     return;
3061   }
3062 
3063   if (!DestType->isScalarType() && !DestType->isVectorType()) {
3064     const RecordType *DestRecordTy = DestType->getAs<RecordType>();
3065 
3066     if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
3067       // GCC struct/union extension: allow cast to self.
3068       Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
3069         << DestType << SrcExpr.get()->getSourceRange();
3070       Kind = CK_NoOp;
3071       return;
3072     }
3073 
3074     // GCC's cast to union extension.
3075     if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
3076       RecordDecl *RD = DestRecordTy->getDecl();
3077       if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
3078         Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
3079           << SrcExpr.get()->getSourceRange();
3080         Kind = CK_ToUnion;
3081         return;
3082       } else {
3083         Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3084           << SrcType << SrcExpr.get()->getSourceRange();
3085         SrcExpr = ExprError();
3086         return;
3087       }
3088     }
3089 
3090     // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
3091     if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
3092       Expr::EvalResult Result;
3093       if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
3094         llvm::APSInt CastInt = Result.Val.getInt();
3095         if (0 == CastInt) {
3096           Kind = CK_ZeroToOCLOpaqueType;
3097           return;
3098         }
3099         Self.Diag(OpRange.getBegin(),
3100                   diag::err_opencl_cast_non_zero_to_event_t)
3101                   << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
3102         SrcExpr = ExprError();
3103         return;
3104       }
3105     }
3106 
3107     // Reject any other conversions to non-scalar types.
3108     Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
3109       << DestType << SrcExpr.get()->getSourceRange();
3110     SrcExpr = ExprError();
3111     return;
3112   }
3113 
3114   // The type we're casting to is known to be a scalar or vector.
3115 
3116   // Require the operand to be a scalar or vector.
3117   if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
3118     Self.Diag(SrcExpr.get()->getExprLoc(),
3119               diag::err_typecheck_expect_scalar_operand)
3120       << SrcType << SrcExpr.get()->getSourceRange();
3121     SrcExpr = ExprError();
3122     return;
3123   }
3124 
3125   if (DestType->isExtVectorType()) {
3126     SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
3127     return;
3128   }
3129 
3130   if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
3131     if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
3132           (SrcType->isIntegerType() || SrcType->isFloatingType())) {
3133       Kind = CK_VectorSplat;
3134       SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
3135     } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
3136       SrcExpr = ExprError();
3137     }
3138     return;
3139   }
3140 
3141   if (SrcType->isVectorType()) {
3142     if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
3143       SrcExpr = ExprError();
3144     return;
3145   }
3146 
3147   // The source and target types are both scalars, i.e.
3148   //   - arithmetic types (fundamental, enum, and complex)
3149   //   - all kinds of pointers
3150   // Note that member pointers were filtered out with C++, above.
3151 
3152   if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
3153     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
3154     SrcExpr = ExprError();
3155     return;
3156   }
3157 
3158   // Can't cast to or from bfloat
3159   if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) {
3160     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16)
3161         << SrcExpr.get()->getSourceRange();
3162     SrcExpr = ExprError();
3163     return;
3164   }
3165   if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) {
3166     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16)
3167         << SrcExpr.get()->getSourceRange();
3168     SrcExpr = ExprError();
3169     return;
3170   }
3171 
3172   // If either type is a pointer, the other type has to be either an
3173   // integer or a pointer.
3174   if (!DestType->isArithmeticType()) {
3175     if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
3176       Self.Diag(SrcExpr.get()->getExprLoc(),
3177                 diag::err_cast_pointer_from_non_pointer_int)
3178         << SrcType << SrcExpr.get()->getSourceRange();
3179       SrcExpr = ExprError();
3180       return;
3181     }
3182     checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
3183                           Self);
3184   } else if (!SrcType->isArithmeticType()) {
3185     if (!DestType->isIntegralType(Self.Context) &&
3186         DestType->isArithmeticType()) {
3187       Self.Diag(SrcExpr.get()->getBeginLoc(),
3188                 diag::err_cast_pointer_to_non_pointer_int)
3189           << DestType << SrcExpr.get()->getSourceRange();
3190       SrcExpr = ExprError();
3191       return;
3192     }
3193 
3194     if ((Self.Context.getIntRange(SrcType) >
3195          Self.Context.getTypeSize(DestType)) &&
3196         !DestType->isBooleanType()) {
3197       // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3198       // Except as previously specified, the result is implementation-defined.
3199       // If the result cannot be represented in the integer type, the behavior
3200       // is undefined. The result need not be in the range of values of any
3201       // integer type.
3202       unsigned Diag;
3203       if (SrcType->isVoidPointerType())
3204         Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
3205                                           : diag::warn_void_pointer_to_int_cast;
3206       else if (DestType->isEnumeralType())
3207         Diag = diag::warn_pointer_to_enum_cast;
3208       else
3209         Diag = diag::warn_pointer_to_int_cast;
3210       Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
3211     }
3212   }
3213 
3214   if (Self.getLangOpts().OpenCL &&
3215       !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
3216     if (DestType->isHalfType()) {
3217       Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
3218           << DestType << SrcExpr.get()->getSourceRange();
3219       SrcExpr = ExprError();
3220       return;
3221     }
3222   }
3223 
3224   // ARC imposes extra restrictions on casts.
3225   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3226     checkObjCConversion(Sema::CCK_CStyleCast);
3227     if (SrcExpr.isInvalid())
3228       return;
3229 
3230     const PointerType *CastPtr = DestType->getAs<PointerType>();
3231     if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
3232       if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
3233         Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
3234         Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
3235         if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
3236             ExprPtr->getPointeeType()->isObjCLifetimeType() &&
3237             !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
3238           Self.Diag(SrcExpr.get()->getBeginLoc(),
3239                     diag::err_typecheck_incompatible_ownership)
3240               << SrcType << DestType << Sema::AA_Casting
3241               << SrcExpr.get()->getSourceRange();
3242           return;
3243         }
3244       }
3245     }
3246     else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
3247       Self.Diag(SrcExpr.get()->getBeginLoc(),
3248                 diag::err_arc_convesion_of_weak_unavailable)
3249           << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3250       SrcExpr = ExprError();
3251       return;
3252     }
3253   }
3254 
3255   DiagnoseCHERICallback(Self, SrcExpr.get()->getBeginLoc(), SrcType, DestType);
3256   DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
3257   DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
3258   DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
3259   Kind = Self.PrepareScalarCast(SrcExpr, DestType);
3260   DiagnoseCHERIPtr(Self, SrcExpr.get(), DestType, Kind, OpRange);
3261 
3262   if (SrcExpr.isInvalid())
3263     return;
3264 
3265   if (Kind == CK_BitCast)
3266     checkCastAlign();
3267 }
3268 
CheckBuiltinBitCast()3269 void CastOperation::CheckBuiltinBitCast() {
3270   QualType SrcType = SrcExpr.get()->getType();
3271 
3272   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
3273                                diag::err_typecheck_cast_to_incomplete) ||
3274       Self.RequireCompleteType(OpRange.getBegin(), SrcType,
3275                                diag::err_incomplete_type)) {
3276     SrcExpr = ExprError();
3277     return;
3278   }
3279 
3280   if (SrcExpr.get()->isRValue())
3281     SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
3282                                                   /*IsLValueReference=*/false);
3283 
3284   CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
3285   CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
3286   if (DestSize != SourceSize) {
3287     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
3288         << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
3289     SrcExpr = ExprError();
3290     return;
3291   }
3292 
3293   if (!DestType.isTriviallyCopyableType(Self.Context)) {
3294     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3295         << 1;
3296     SrcExpr = ExprError();
3297     return;
3298   }
3299 
3300   if (!SrcType.isTriviallyCopyableType(Self.Context)) {
3301     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3302         << 0;
3303     SrcExpr = ExprError();
3304     return;
3305   }
3306 
3307   Kind = CK_LValueToRValueBitCast;
3308 }
3309 
3310 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3311 /// const, volatile or both.
DiagnoseCastQual(Sema & Self,const ExprResult & SrcExpr,QualType DestType)3312 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
3313                              QualType DestType) {
3314   if (SrcExpr.isInvalid())
3315     return;
3316 
3317   QualType SrcType = SrcExpr.get()->getType();
3318   if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
3319         DestType->isLValueReferenceType()))
3320     return;
3321 
3322   QualType TheOffendingSrcType, TheOffendingDestType;
3323   Qualifiers CastAwayQualifiers;
3324   if (CastsAwayConstness(Self, SrcType, DestType, true, false,
3325                          &TheOffendingSrcType, &TheOffendingDestType,
3326                          &CastAwayQualifiers) !=
3327       CastAwayConstnessKind::CACK_Similar)
3328     return;
3329 
3330   // FIXME: 'restrict' is not properly handled here.
3331   int qualifiers = -1;
3332   if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
3333     qualifiers = 0;
3334   } else if (CastAwayQualifiers.hasConst()) {
3335     qualifiers = 1;
3336   } else if (CastAwayQualifiers.hasVolatile()) {
3337     qualifiers = 2;
3338   }
3339   // This is a variant of int **x; const int **y = (const int **)x;
3340   if (qualifiers == -1)
3341     Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
3342         << SrcType << DestType;
3343   else
3344     Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
3345         << TheOffendingSrcType << TheOffendingDestType << qualifiers;
3346 }
3347 
BuildCStyleCastExpr(SourceLocation LPLoc,TypeSourceInfo * CastTypeInfo,SourceLocation RPLoc,Expr * CastExpr)3348 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
3349                                      TypeSourceInfo *CastTypeInfo,
3350                                      SourceLocation RPLoc,
3351                                      Expr *CastExpr) {
3352   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
3353   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3354   Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
3355 
3356   if (getLangOpts().CPlusPlus) {
3357     Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3358                           isa<InitListExpr>(CastExpr));
3359   } else {
3360     Op.CheckCStyleCast();
3361   }
3362   // Check that we don't incorrectly convert T* <-> T* __capability
3363   Op.CheckCapabilityConversions();
3364 
3365   if (Op.SrcExpr.isInvalid())
3366     return ExprError();
3367 
3368   // -Wcast-qual
3369   DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
3370 
3371   return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
3372                               Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3373                               &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
3374 }
3375 
BuildCXXFunctionalCastExpr(TypeSourceInfo * CastTypeInfo,QualType Type,SourceLocation LPLoc,Expr * CastExpr,SourceLocation RPLoc)3376 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
3377                                             QualType Type,
3378                                             SourceLocation LPLoc,
3379                                             Expr *CastExpr,
3380                                             SourceLocation RPLoc) {
3381   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
3382   CastOperation Op(*this, Type, CastExpr);
3383   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3384   Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
3385 
3386   Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3387   if (Op.SrcExpr.isInvalid())
3388     return ExprError();
3389 
3390   auto *SubExpr = Op.SrcExpr.get();
3391   if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
3392     SubExpr = BindExpr->getSubExpr();
3393   if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
3394     ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
3395 
3396   return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
3397                          Op.ValueKind, CastTypeInfo, Op.Kind,
3398                          Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
3399 }
3400 
BuildCheriToOrFromCap(SourceLocation LParenLoc,bool IsToCap,TypeSourceInfo * TSInfo,SourceLocation RParenLoc,Expr * _SubExpr)3401 ExprResult Sema::BuildCheriToOrFromCap(SourceLocation LParenLoc, bool IsToCap,
3402                                        TypeSourceInfo *TSInfo,
3403                                        SourceLocation RParenLoc,
3404                                        Expr *_SubExpr) {
3405   // NOTE: __cheri_tocap and __cheri_fromcap are no-ops in both the hybrid and
3406   //       purecap ABI if both source and destination types are capabilities
3407   //       and the types are compatible.
3408   CastOperation Op(*this, TSInfo->getType(), _SubExpr);
3409   Op.DestRange = TSInfo->getTypeLoc().getSourceRange();
3410   Op.OpRange = SourceRange(LParenLoc, _SubExpr->getEndLoc());
3411   Op.IsCheriFromCap = !IsToCap;
3412   // Do all the default cast checks (including array-to-pointer decay, etc.)
3413   Op.CheckCheriCast();
3414   // Update the SubExpr pointer after potential conversions
3415   const Expr *const SubExpr = Op.SrcExpr.get();
3416   const QualType DestTy = Op.DestType;
3417   // Use getRealReferenceType() because getType() only returns T for T&
3418   const QualType SrcTy = SubExpr->getRealReferenceType(Context, false);
3419   if (SrcTy->isDependentType() || DestTy->isDependentType()) {
3420     // Don't perform any checking for dependent types:
3421     if (Op.SrcExpr.isInvalid())
3422       return ExprError();
3423     auto CE = CStyleCastExpr::Create(
3424         Context, Op.ResultType, Op.ValueKind, CK_Dependent, Op.SrcExpr.get(),
3425         &Op.BasePath, TSInfo, LParenLoc, RParenLoc);
3426     // We need to set the dependent cast kind to allow reassembly in the
3427     // template instantiation in TreeTransform.h
3428     CE->setDependentCastKind(IsToCap ? CK_PointerToCHERICapability
3429                                      : CK_CHERICapabilityToPointer);
3430     return Op.complete(CE);
3431   }
3432 
3433   // We allow __cheri_fromcap to convert from capability pointers and uintcap_t
3434   // to pointer types (both integral and capability, i.e. no-op casts).
3435   // __cheri_tocap can be used from integral pointers to capability pointers,
3436   // but not to convert to __uintcap_t (yet).
3437   const bool SrcIsCapPtr = SrcTy->isCapabilityPointerType();
3438   const bool SrcIsIntCap = SrcTy->isIntCapType();
3439   const bool DestIsCapPtr = DestTy->isCapabilityPointerType();
3440   const bool DestIsIntCap = DestTy->isIntCapType();
3441 
3442   // TODO: C++ references
3443   Op.Kind = CK_NoOp;
3444   bool CheckPtrConversion = true;
3445   if (IsToCap) {
3446     // __cheri_tocap can be used to convert integer pointers to capability
3447     // pointers and __(u)intcap_t
3448     if (!SrcTy->isPointerType()) {
3449       Diag(SubExpr->getExprLoc(),
3450            diag::err_cheri_to_from_cap_invalid_source_type)
3451           << SrcTy << IsToCap;
3452       return ExprError();
3453     }
3454     if (!DestIsCapPtr && !DestIsIntCap) {
3455       Diag(TSInfo->getTypeLoc().getBeginLoc(),
3456            diag::err_cheri_to_from_cap_invalid_target_type)
3457           << DestTy << IsToCap;
3458       return ExprError();
3459     }
3460     if (DestIsIntCap) {
3461       assert(SrcTy->isPointerType());
3462       // We are not converting between pointer types -> no need to check
3463       CheckPtrConversion = false;
3464       Op.Kind =
3465           SrcIsCapPtr ? CK_PointerToIntegral : CK_PointerToCHERICapability;
3466     } else if (SrcIsCapPtr) {
3467       // No-op if SrcTy is alrady a capability pointer
3468       Op.Kind = CK_NoOp;
3469     } else {
3470       Op.Kind = CK_PointerToCHERICapability;
3471     }
3472   } else {
3473     // __cheri_fromcap can be used for capability pointers and __(u)intcap_t
3474     bool SrcIsValidCapTy = SrcIsCapPtr || SrcIsIntCap;
3475     if (!SrcIsValidCapTy) {
3476       Diag(SubExpr->getExprLoc(),
3477            diag::err_cheri_to_from_cap_invalid_source_type)
3478           << SrcTy << IsToCap;
3479       return ExprError();
3480     }
3481     // TODO: allow the DestTy->isIntegerType() case?
3482     if (!DestTy->isPointerType()) {
3483       Diag(TSInfo->getTypeLoc().getBeginLoc(),
3484            diag::err_cheri_to_from_cap_invalid_target_type)
3485           << DestTy << IsToCap;
3486       return ExprError();
3487     }
3488     if (SrcIsIntCap || DestIsIntCap) {
3489       // We are not converting between pointer types -> no need to check whether
3490       // the two pointer types are compatible:
3491       CheckPtrConversion = false;
3492       if (SrcIsIntCap && DestIsIntCap) {
3493         Op.Kind = CK_NoOp;
3494       } else if (SrcIsIntCap) {
3495         Op.Kind =
3496             DestIsCapPtr ? CK_IntegralToPointer : CK_CHERICapabilityToPointer;
3497       } else if (DestIsIntCap) {
3498         assert(SrcIsCapPtr);
3499         Op.Kind = CK_PointerToIntegral;
3500       }
3501     } else if (DestIsCapPtr) {
3502       // Both pointers, CheckCHERIAssignCompatible can change it to CK_BitCast
3503       Op.Kind = CK_NoOp;
3504     } else {
3505       Op.Kind = CK_CHERICapabilityToPointer;
3506     }
3507   }
3508 
3509   // C++ checks if the types are exactly the same -> this will fail because
3510   // capability and non-capability Type* are different instances
3511   //
3512   // Types compatible source:
3513   //   if (getLangOpts().CPlusPlus)
3514   //     return hasSameType(LHS, RHS);
3515   //  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
3516   Expr *MaybeImpConv = Op.SrcExpr.get();
3517   if (CheckPtrConversion &&
3518       !CheckCHERIAssignCompatible(DestTy, SrcTy, MaybeImpConv)) {
3519     Diag(MaybeImpConv->getExprLoc(), diag::err_cheri_to_from_cap_unrelated_type)
3520         << IsToCap << SrcTy << DestTy;
3521     return ExprError();
3522   }
3523   Op.SrcExpr = MaybeImpConv;
3524 
3525   // Warn about no-op cheri casts.
3526   if (Op.Kind == CK_NoOp) {
3527     Diag(LParenLoc, diag::warn_cheri_to_from_cap_noop)
3528         << IsToCap << SrcTy << DestTy
3529         << FixItHint::CreateRemoval(SourceRange(LParenLoc, RParenLoc));
3530     // If we are casting to void*
3531   }
3532   assert(Op.ValueKind == VK_RValue);
3533   assert(Op.DestType == DestTy);
3534   return Op.complete(CStyleCastExpr::Create(
3535       Context, Op.DestType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3536       &Op.BasePath, TSInfo, LParenLoc, RParenLoc));
3537 }
3538 
3539 // Check if LHS and RHS are assign compatible for CHERI (ignoring capability
3540 // qualifiers). Insert an implicit bitcast if necessary (when InsertBitCast is
3541 // true - the default) and update RHSExpr to point to it.
3542 //
3543 // Two types LHS and RHS are assign compatible (ignoring capability qualifiers)
3544 // if:
3545 // - LHS == RHS
3546 // - either of LHS or RHS is void*
3547 //
3548 // In the case of LHS being void*, an implicit bitcast from RHSExpr to void*
3549 // will be inserted and RHSExpr updated to point to this ImplicitCastExpr.
CheckCHERIAssignCompatible(QualType LHS,QualType RHS,Expr * & RHSExpr,bool InsertBitCast)3550 bool Sema::CheckCHERIAssignCompatible(QualType LHS, QualType RHS,
3551                                       Expr *&RHSExpr, bool InsertBitCast) {
3552   // XXXAR: I had to modify mergeTypes() to add a IncludeCapabilityQualifier
3553   // flag because here we want to compare everything but the __capability
3554   // qualifier
3555   // XXXKG: I also extended mergeTypes() with a MergeVoidPtr flag to allow the
3556   // <-> void* case (and still get the checking of qualifiers).
3557   // XXXKG: Allow non-const to const assignment
3558   QualType MergedTy = Context.mergeTypes(
3559       LHS, RHS, /*OfBlockPointer=*/false, /*Unqualified=*/false,
3560       /*BlockReturnType=*/false, /*IncludeCapabilityQualifier=*/false,
3561       /*MergeVoidPtr=*/false, /*MergeLHSConst=*/false);
3562   if (MergedTy.isNull()) {
3563     // As a special case we allow changing the types if either:
3564     // - LHS or RHS is a pointer to void
3565     // - LHS has a const-qualified pointee type and the RHS pointee is not
3566     //   const-qualified
3567     MergedTy = Context.mergeTypes(
3568         LHS, RHS, /*OfBlockPointer=*/false, /*Unqualified=*/false,
3569         /*BlockReturnType=*/false, /*IncludeCapabilityQualifier=*/false,
3570         /*MergeVoidPtr=*/true, /*MergeLHSConst=*/true);
3571     if (!MergedTy.isNull()) {
3572       if (InsertBitCast) {
3573         // Insert a CK_BitCast to ensure we don't crash during codegen (see
3574         // https://github.com/CTSRD-CHERI/clang/issues/178)
3575         bool RHSIsCap = RHS->isCHERICapabilityType(Context, false);
3576         QualType BitCastTy = Context.getPointerType(
3577             LHS->getAs<PointerType>()->getPointeeType(),
3578             RHSIsCap ? PIK_Capability : PIK_Integer);
3579         RHSExpr = ImplicitCastExpr::Create(Context, BitCastTy, CK_BitCast,
3580                                            RHSExpr, nullptr, VK_RValue);
3581       }
3582       return true;
3583     }
3584     return false;
3585   }
3586   return true;
3587 }
3588 
BuildCheriOffsetOrAddress(SourceLocation LParenLoc,bool IsOffsetCast,TypeSourceInfo * TSInfo,SourceLocation RParenLoc,Expr * _SubExpr)3589 ExprResult Sema::BuildCheriOffsetOrAddress(SourceLocation LParenLoc,
3590                                            bool IsOffsetCast,
3591                                            TypeSourceInfo *TSInfo,
3592                                            SourceLocation RParenLoc,
3593                                            Expr *_SubExpr) {
3594   CastOperation Op(*this, TSInfo->getType(), _SubExpr);
3595   Op.DestRange = TSInfo->getTypeLoc().getSourceRange();
3596   Op.OpRange = SourceRange(LParenLoc, _SubExpr->getEndLoc());
3597   // Do all the default cast checks (including array-to-pointer decay, etc.)
3598   Op.CheckCheriCast();
3599   // Update the SubExpr pointer after potential conversions
3600   const Expr *const SubExpr = Op.SrcExpr.get();
3601   const QualType DestTy = Op.DestType;
3602   Op.Kind =
3603       IsOffsetCast ? CK_CHERICapabilityToOffset : CK_CHERICapabilityToAddress;
3604   Op.IsCheriAddrOffset = true;
3605   // Check the source type:
3606   // Use getRealReferenceType() because getType() only returns T for T&
3607   const QualType SrcTy = SubExpr->getRealReferenceType(Context, false);
3608   // Dependent types not yet handled, would probably need a new AST node to
3609   // differentiate from normal C-style casts
3610   if (SrcTy->isDependentType() || DestTy->isDependentType()) {
3611     // Don't perform any checking for dependent types:
3612     if (Op.SrcExpr.isInvalid())
3613       return ExprError();
3614     auto CE = CStyleCastExpr::Create(
3615         Context, Op.ResultType, Op.ValueKind, CK_Dependent, Op.SrcExpr.get(),
3616         &Op.BasePath, TSInfo, LParenLoc, RParenLoc);
3617     // We need to set the dependent cast kind to allow reassembly in the
3618     // template instantiation in TreeTransform.h
3619     CE->setDependentCastKind(Op.Kind);
3620     return Op.complete(CE);
3621   }
3622   // __cheri_offset and __cheri_addr is valid for __uintcap_t and pointers:
3623   bool SrcIsValidCap = SrcTy->isIntCapType();
3624   if (const PointerType *PT = SrcTy->getAs<PointerType>())
3625     SrcIsValidCap = PT->isCHERICapability();
3626   if (!SrcIsValidCap) {
3627     // Note: __cheri_addr can be used on plain pointers since otherwise it would
3628     // be very difficult to write code that compiles both in hybrid and in
3629     // purecap mode. However, the offset cast only makes sense for capabilities!
3630     if (IsOffsetCast || (!SrcTy->isPointerType() && !SrcTy->isIntCapType())) {
3631       // XXXKG: What about functions?
3632       Diag(SubExpr->getBeginLoc(),
3633            diag::err_cheri_offset_addr_invalid_source_type)
3634           << SrcTy << IsOffsetCast;
3635       return ExprError();
3636     } else {
3637       // Casting from pointer to address in hybrid mode
3638       assert(!Context.getTargetInfo().areAllPointersCapabilities());
3639       Op.Kind = CK_PointerToIntegral;
3640     }
3641   }
3642 
3643   // Check the destination type:
3644   // For __cheri_addr, output a more specific error message if DestTy is an
3645   // integral pointer type
3646   if (!IsOffsetCast) {
3647     if (DestTy->isPointerType()) {
3648       Diag(SubExpr->getBeginLoc(), diag::err_cheri_addr_ptr_type)
3649           << DestTy << (int)DestTy->getAs<PointerType>()->isCHERICapability();
3650       return ExprError();
3651     }
3652   }
3653   // Otherwise just check that it is a non-enum integer type
3654   bool DestIsInt = DestTy->isIntegerType() && !DestTy->isEnumeralType();
3655   if (!DestIsInt) {
3656     Diag(SubExpr->getBeginLoc(),
3657          diag::err_cheri_offset_addr_invalid_target_type)
3658         << DestTy << IsOffsetCast;
3659     return ExprError();
3660   }
3661 
3662   // Output warning about truncation if DestTy is smaller than CHERI cap pointer
3663   // range
3664   auto &TI = Context.getTargetInfo();
3665   uint64_t PtrRange = TI.getPointerRangeForCHERICapability();
3666   uint64_t DestRange = Context.getTypeSize(DestTy);
3667   if (DestRange < PtrRange) {
3668     bool DestIsSigned = DestTy->isSignedIntegerOrEnumerationType();
3669     const char *minTy =
3670         TI.getTypeName(TI.getLeastIntTypeByWidth(PtrRange, DestIsSigned));
3671     Diag(SubExpr->getBeginLoc(),
3672          diag::warn_cheri_offset_addr_smaller_target_type)
3673         << DestTy << minTy << IsOffsetCast;
3674   }
3675   return Op.complete(CStyleCastExpr::Create(
3676       Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3677       &Op.BasePath, TSInfo, LParenLoc, RParenLoc));
3678 }
3679 
ActOnCheriCast(Scope * S,SourceLocation LParenLoc,tok::TokenKind Kind,SourceLocation KeywordLoc,ParsedType Type,SourceLocation RParenLoc,Expr * SubExpr)3680 ExprResult Sema::ActOnCheriCast(Scope *S, SourceLocation LParenLoc,
3681                                 tok::TokenKind Kind, SourceLocation KeywordLoc,
3682                                 ParsedType Type, SourceLocation RParenLoc,
3683                                 Expr *SubExpr) {
3684   if (Kind == tok::kw___cheri_cast) {
3685     Diag(KeywordLoc, diag::err_cheri_cast);
3686     return ExprError();
3687   }
3688   TypeSourceInfo *TSInfo = nullptr;
3689   QualType T = GetTypeFromParser(Type, &TSInfo);
3690   if (!TSInfo)
3691     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3692 
3693   switch (Kind) {
3694   case tok::kw___cheri_tocap:
3695   case tok::kw___cheri_fromcap:
3696     return BuildCheriToOrFromCap(LParenLoc, Kind == tok::kw___cheri_tocap,
3697                                  TSInfo, RParenLoc, SubExpr);
3698 
3699   case tok::kw___cheri_offset:
3700   case tok::kw___cheri_addr:
3701     return BuildCheriOffsetOrAddress(LParenLoc, Kind == tok::kw___cheri_offset,
3702                                      TSInfo, RParenLoc, SubExpr);
3703 
3704   default:
3705     llvm_unreachable("Unknown CHERI cast!");
3706   }
3707 }
3708