Coverage Report

Created: 2019-07-24 05:18

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